// pages/confirmOrder/confirmOrder.js
const wxService = require('../../utils/wxService')
const app = getApp()

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: ['', ''],
    wxAddress: false,
    currentCoupon: '',
    orderPrice: null, // 订单金额
    orderInitPrice: 0,
    plusMemberPrice: 0, // plus 默认价
    plusMemberName: '',
    defalutCoupon: '',
    addressId: '', // 收货地址id
    showPlus: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('dddd', app.globalData.isPlusVip)

    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];

    const { trolleySku2Buy } = this.options

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

    // 下单 && 计算优惠价

    this.setData({
      trolleySku2Buy: tradeDto.trolleySku2Buy,
      showPlus: app.globalData.isPlusVip ? false : true
    }, () => {
      this.initCitys()
      // 地址列表
      this.getAddressList()
      // if (!this.data.wxAddress){
      //   this.getAddressList()
      // }
    })

    // this.initCitys()
    // // 地址列表
    // this.getAddressList()
    // // 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, orderInitPrice, isSelect, plusMemberPrice } = this.data
    let newCurrentCoupon = currentCoupon ? currentCoupon : 0
    let orderCoupon = parseFloat(newCurrentCoupon) // 优惠券价格
    let plusPrice = isSelect ? plusMemberPrice : 0 // plus
    // 实际价格 - 优惠价 + plus
    this.setData({
      // orderPrice: Math.round(orderInitPrice - orderCoupon)
      orderPrice: orderInitPrice - orderCoupon + plusPrice
    })
  },
  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;
      }
      const { memberId } = wx.getStorageSync('_baseUserInfo')
      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, addressId, addressInfo } = this.data

        let params = {
          checkByPremium,
          trolleySku2Buy,
          addressId: addressId ? addressId : addressInfo.id // 微信地址 or 地址id
        }
        this.calPreferentialPrice(params)  // 重新计算优惠价
        // 获取默认付费会员设置
        this.getPremiumDefault()
      })
    })

  },
  // /premium/getDefault
  getPremiumDefault() {
    wx.showLoading({
      title: '加载中'
    })
    wxService.get(`/sale/premium/getDefault`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({
            plusMemberPrice: data.price,
            plusMemberName: data.name
          }, () => {
            // 实付款
            this.setPayPrice()
          })
        }
      }
    })
  },
  // 默认地址 
  selectAddress() {
    wxService.router('/pages/myAddress/myAddress')
  },
  // 计算优惠价
  calPreferentialPrice(params) {
    console.log('params', 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,
            defalutCoupon: data && data.couponDiscountPreviews.length && data.couponDiscountPreviews[0].couponDiscount || '',
            orderInitPrice: data.amount
          }, () => {
            // 实付款
            this.setPayPrice()
          })
        }
      }
    })
  },
  handelGobuy() {
    const { trolleySku2Buy, couponId, addressId, addressInfo } = this.data
    let params = {
      couponId,
      trolleySku2Buy,
      addressId: addressId ? addressId : addressInfo.id // 微信地址 or 地址id
    }

    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?status=S&amount=${amount}`)
            },
            fail(res) {
              wx.hideLoading()
              wxService.router(`/subPackage/page/pages/paymentStatus/paymentStatus?status=F`)
            }
          }, data.wxParams))
        }
      }
    })
  },
  // 获取地址列表
  getAddressList() {
    const { memberId } = wx.getStorageSync('_baseUserInfo')
    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
          }, () => {
            // preview
            const { trolleySku2Buy, checkByPremium, addressId, addressInfo } = this.data
            let params = {
              checkByPremium,
              trolleySku2Buy,
              addressId: addressId ? addressId : addressInfo.id // 微信地址 or 地址id
            }
            this.calPreferentialPrice(params)  // 计算优惠价
          })
        }
      }
    }).finally(() => {
    })
  },
  //获取微信地址
  chooseWxAddress() {
    const { memberId } = wx.getStorageSync('_baseUserInfo')
    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,
          params: {
            userId: memberId,
            name: res.userName,
            phone: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            district: res.countyName,
            address: res.detailInfo,
            type: 0
          }
        })
        wxService.post(`/member/addressManage/save`, this.data.params).then(res => {
          const { result, data } = res.data
          if (result == 0) {
            wx.hideLoading()
            this.setData({
              addressId: data
            })
          }
        }).finally(() => {
          wx.hideLoading()
        })

        console.log('WX---------------------', this.data.addressInfo)
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },

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


})