import { VueLikePage } from '../../utils/page'
import GoodsApi from '../../apis/goods'
import Router from '../../utils/routes'
import ImSend from '../../utils/imSend'
import CenSus from '../../apis/census'
import CompanyApi from '../../apis/company'
import { saveCollectHistory, loadCollectHistory, removeCollect } from '../../utils/storage'

VueLikePage([], {
  data: {
    detail: {}
  },
  methods: {
    async onLoad (options) {
      console.log(options)
      const { goods_id, company_id } = options
      this.goods_id = goods_id
      const goodsDetail = await this.getGoodsDetail()
      this.setData({
        detail: goodsDetail
      })
      // this.getGuide()
      this.getGoodsCollectStatus()
      
      const companyRes = await CompanyApi.getCompanyDetail(company_id)
      console.log(companyRes)
      this.company = companyRes.data
    },
    async getGoodsDetail () {
      let res = await GoodsApi.getShopGoodsDetail(this.goods_id)
      let goodsDetail = res.data
      goodsDetail.banner = goodsDetail.gallery.map(item => item.img_url)
      goodsDetail.info.goods_desc = goodsDetail.info.goods_desc && goodsDetail.info.goods_desc.replace(/(\<img)/gi, function ($0, $1) {
        return {
          "<img": '<img style="width:100%;height:auto;display:block;" '
        }[$1];
      })
      return goodsDetail
    },
    getGoodsCollectStatus () {
      const status = loadCollectHistory(this.goods_id)
      this.setData({
        collectStatus: Boolean(status) ? 1 : 0
      })
    },
    changeCollect () {
      const collectStatus = this.data.collectStatus
      let data = '', apiFn
      if (collectStatus === 1) {
        data = this.goods_id
        apiFn = removeCollect
      } else {
        apiFn = saveCollectHistory
        data = {
          img_url: this.data.detail.banner[0],
          title: this.data.detail.info.name,
          id: this.goods_id
        }
      }
      
      apiFn(data)
      wx.showToast({
        title: `${collectStatus === 1 ? '取消' : '收藏'}成功`,
      })
      this.getGoodsCollectStatus()
    },
    getGuide () {
      GoodsApi.getGuideByGoods(this.goods_id).then(res => {
        this.guide = res.data
      })
    },
    toChat () {
      // if (!this.guide) return
      if (!getApp().globalData.token) {
        Router.push('login')
        return
      }
      CenSus.addGoodsQueryNum({
        goodsId: this.goods_id,
        sceneNum: this.company.sceneNum
      })
      ImSend.sendMsg({content:'你好', msgType:'text', toId:this.company.guideId}).then(() => {
        Router.push({
          url: 'chat',
          query: {
            toId: this.company.guideId
          }
        })
      })
      
    }
  }
})