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'
VueLikePage([], {
  data: {
    detail: {}
  },
  methods: {
    async onLoad (options) {
      const { goods_id } = options
      this.goods_id = goods_id
      const res = await this.getGoodsDetail()
      this.getGuide()
      this.getGoodsCollectStatus()
      this.setData({
        detail: res.data
      })
      const companyRes = await CompanyApi.getCompanyDetail(res.data.companyId)
      this.company = companyRes.data
    },
    getGoodsDetail () {
      return GoodsApi.getGoodsDetail(this.goods_id)
    },
    getGoodsCollectStatus () {
      return GoodsApi.getGoodsCollectStatus(this.goods_id).then(res => {
        this.setData({
          collectStatus: res.data
        })
      })
    },
    changeCollect () {
      const collectStatus = this.data.collectStatus
      const apiFn = collectStatus === 1 ? GoodsApi.cancleCollect : GoodsApi.collectGoods
      return apiFn(this.goods_id).then(res => {
        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.guide.viewerId}).then(() => {
        Router.push({
          url: 'chat',
          query: {
            toId: this.guide.viewerId
          }
        })
      })
      
    }
  }
})