// pages/confirmOrder/confirmOrder.js
const wxService = require('../../utils/wxService')
const { memberId } = wx.getStorageSync('_baseUserInfo')

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    couponId: null,
    checkByPremium: false,
    addressInfo: [],
    showSelectCoupon: false,
    skuIds: [],
    trolleySku2Buy: Array,
    currentOrderList: Array,
    isSelect: false,
    goodsAddress: false,
    citys: null,
    cityView: '',
    multiIndex: [0, 0, 0],
    selectCityName: ['', ''],
    currentCoupon: '无可用优惠券',
    wxAddress: false,
    currentCoupon: '',
    orderPrice: null, // 订单金额
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // const { couponId, trolleySku2Buy } = this.options

    // let tradeDto = {
    //   couponId: couponId,
    //   trolleySku2Buy: JSON.parse(trolleySku2Buy)
    // }

    const { trolleySku2Buy } = this.options

    let tradeDto = {
      trolleySku2Buy: JSON.parse(trolleySku2Buy)
    }

    console.log('tradeDto', tradeDto)

    // 下单 && 计算优惠价

    this.setData({ trolleySku2Buy: tradeDto.trolleySku2Buy }, () => {
      const { trolleySku2Buy, checkByPremium } = this.data
      let params = {
        checkByPremium,
        trolleySku2Buy
      }
      this.calPreferentialPrice(params)  // 计算优惠价
    })

    this.initCitys()
    // 地址列表
    if (!this.data.wxAddress){
      this.getAddressList()
    }
  },
  updateCoupon(e) {
    // faceAmount 抵用多少钱（分） 1 抵用券  2 折扣券
    const { faceAmount, type, id } = e.detail
    const { orderPrice } = this.data

    if (type == 1) {
      this.setData({
        couponId: id,
        haveCoupon: true,
        currentCoupon: `${faceAmount / 100} 元`
      })
    } else if (type == 2) {
      let discounPrice = (faceAmount / 100) * (orderPrice)
      let spread = Math.round(orderPrice - discounPrice)

      this.setData({
        couponId: id,
        haveCoupon: true,
        currentCoupon: `${spread} 元`
      })
    }
    // 实付款
    this.setPayPrice()
  },
  setPayPrice() {
    const { currentCoupon, orderPrice } = this.data
    let orderCoupon = parseFloat(currentCoupon)
  
    this.setData({
      orderPrice: Math.round(orderPrice - orderCoupon)
    })
  },
  formSubmit(e) {
    const { goodsAddress } = this.data
    // 保存地址 && 支付
    if (goodsAddress) {
      if (!e.detail.value.name) {
        wx.showToast({
          title: `请输入姓名`,
          icon: 'none'
        })
        return false;
      }
      if (!e.detail.value.phone) {
        wx.showToast({
          title: `请输入电话`,
          icon: 'none'
        })
        return false;
      }
      if (!this.data.cityView) {
        wx.showToast({
          title: `请选择地区`,
          icon: 'none'
        })
        return false;
      }
      if (!e.detail.value.address) {
        wx.showToast({
          title: `请输入详细地址`,
          icon: 'none'
        })
        return false;
      }

      this.setData({
        params: {
          userId: memberId,
          name: e.detail.value.name,
          phone: e.detail.value.phone,
          fullArea: this.data.cityView,
          address: e.detail.value.address,
          type: this.data.isSelect ? 1 : 0
        }
      })
      wx.showLoading({
        title: '加载中'
      })

      wxService.post(`/member/addressManage/save`, this.data.params).then(res => {
        const { result } = res.data
        if (result == 0) {
          wx.hideLoading()
          wx.showToast({
            title: `保存成功`,
            icon: 'none'
          })
          // 调起支付
          this.handelGobuy()
        }
      })
    } else {
      // 调起支付
      this.handelGobuy()
    }

  },
  initCitys() {
    wxService.getC1().then((c1) => {
      return wxService.Promise.all([wxService.Promise.resolve(c1), wxService.getC2ByC1('北京'), wxService.getC3ByC2('北京北京市')])
    }).then(res => {
      const citys = res.map(item => {
        return [...item]
      })
      this.setData({
        citys
      })
    })
  },
  bindMultiPickerChange(e) {
    const citys = this.data.citys
    const multiIndex = e.detail.value
    if (citys) {
      const cityView = [citys[0][multiIndex[0]], citys[1][multiIndex[1]], citys[2][multiIndex[2]]].join(' ')
      this.setData({
        multiIndex,
        cityView
      }, () => {
        console.log('================0', this.data.cityView, this.data.multiIndex)
      })
    }
  },
  bindMultiPickerColumnChange(e) {
    const detail = e.detail
    const index = detail.value
    let cityName = ''
    switch (detail.column) {
      case 0:
        cityName = this.data.citys[0][index]
        this.data.selectCityName[0] = cityName
        wxService.getC2ByC1(cityName)
          .then(item => {
            let c2 = [...item]
            this.data.selectCityName[1] = c2[0]
            return wxService.Promise.all([wxService.Promise.resolve(item), wxService.getC3ByC2(this.data.selectCityName.join(''))])
          }).then((res) => {
            this.setData({
              'citys[1]': [...res[0]],
              'citys[2]': [...res[1]]
            })
          })
        break
      case 1:
        cityName = this.data.citys[1][index]
        this.data.selectCityName[1] = cityName
        wxService.getC3ByC2(this.data.selectCityName.join(''))
          .then(item => {
            this.setData({
              'citys[2]': [...item]
            })
          })
        break
      default:
        break
    }
  },

  handelChangeSelectVip() {
    this.setData({
      isSelect: !this.data.isSelect
    }, () => {
      const { isSelect } = this.data
      console.log('isSelect', isSelect)
      this.setData({
        checkByPremium: isSelect
      }, () => {
        const { trolleySku2Buy, checkByPremium } = this.data
        let params = {
          checkByPremium,
          trolleySku2Buy
        }
        this.calPreferentialPrice(params)  // 重新计算优惠价
      })

    })
  },
  // 默认地址 
  selectAddress() {
    wxService.router('/pages/myAddress/myAddress')
  },
  // 计算优惠价
  calPreferentialPrice(params) {
    wx.showLoading({
      title: '加载中'
    })
    wxService.post(`/sale/trade/buyer/preview`, params).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({ 
            currentOrderList: data,
            orderPrice: data.amount
          })
        }
      }
    })
  },
  handelGobuy() {
    const { trolleySku2Buy, couponId } = this.data
    let params = {
      couponId,
      trolleySku2Buy
    }
    this.getBill(params) // 下单
  },
  //  下单
  getBill(params) {
    wx.showLoading({
      title: '加载中'
    })
    wxService.post(`/sale/trade/buyer/bill`, params).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          delete data.appId
          console.log('dddd', data.amount)
          let amount = data.amount || 0
          wx.requestPayment(Object.assign({
            success(res) {
              wx.hideLoading()
              // 支付成功页面
              wxService.router(`/subPackage/page/pages/paymentStatus/paymentStatus?amount=${amount}`)
            },
            fail(res) {
              wx.hideLoading()
              wx.showToast({
                title: '已取消',
                icon: 'none',
                mask: true
              })
            }
          }, data.wxParams))
        }
      }
    })
  },
  // 获取地址列表
  getAddressList() {
    wxService.post(`/member/addressManage/getall`, {
      userId: memberId
    }).then(res => {
      if (!res) return false
      const { result, data } = res.data
      if (result == 0) {
        if (!data.length) {
          this.setData({
            goodsAddress: true
          })
        } else {
          // 缓存有没有地址
          let hasDefalut = wx.getStorageSync('_defalutAddress')
          let _defalutAddress = null

          if (hasDefalut) {
            _defalutAddress = hasDefalut
          } else {
            data.forEach(item => {
              if (item.type == 1) {
                _defalutAddress = item
              }
            })
          }

          this.setData({
            addressInfo: _defalutAddress
          })
          console.log(this.data.addressInfo)
        }
      }
    }).finally(() => {
    })
  },
  //获取微信地址
  chooseWxAddress() {
    wx.chooseAddress({
      success: (res) => {
        console.log('微信地址', res)
        res.name = res.userName
        res.phone = res.telNumber
        res.fullArea = res.provinceName + res.cityName + res.countyName
        res.address = res.detailInfo
        this.setData({
          goodsAddress: false,
          wxAddress: true,
          addressInfo: res
        })
        console.log('WX---------------------', this.data.addressInfo)
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },

  //选择优惠券
  selectCoupon() {
    this.setData({
      showSelectCoupon: true
    })
  }


})