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

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    couponId: null, // 当前选中优惠券 id
    couponSettingId: null, // 当前选中plus优惠券 id
    checkByPremium: false,
    addressInfo: [],
    showSelectCoupon: false,
    skuIds: [],
    trolleySku2Buy: Array,
    currentOrderList: Array,
    isSelect: false,
    selectPrice:'',
    noSelectPrice:'',
    plusSpread:'',
    goodsAddress: false,
    citys: null,
    cityView: '',
    multiIndex: [0, 0, 0],
    selectCityName: ['', ''],
    wxAddress: false,
    currentCoupon: '',
    orderPrice: null, // 订单金额
    orderInitPrice: 0,
    plusMemberPrice: 0, // plus 默认价
    plusMemberName: '',
    defalutCoupon: '',
    defalutCouponId: '', // 默认第一项
    addressId: '', // 收货地址id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    const { trolleySku2Buy } = this.options;
    let tradeDto = {
      trolleySku2Buy: JSON.parse(trolleySku2Buy)
    }

    // 下单 && 计算优惠价
    this.setData({
      trolleySku2Buy: tradeDto.trolleySku2Buy
    }, () => {
      this.initCitys()
      // 地址列表
      this.getAddressList()
    });
  },
  // select 传过来
  updateCoupon(e) {
    // faceAmount 抵用多少钱（分） 1 抵用券  2 折扣券
    if(!e.detail) {
      this.setData({
        defalutCoupon: 0,
        couponId: '',
        couponSettingId: '',
        defalutCouponId: ''
      })
      return
    } 
    const { faceAmount, type, id, couponDiscount,sid } = e.detail
    const { defalutCouponId } = this.data
    const { orderPrice } = this.data
    // couponId---id couponSettingId --sid
    let finCouponId = id ? id : sid
    let finCouponName =  id ? 'couponId' : 'couponSettingId';
    if (type == 1) {
      this.setData({
        defalutCoupon: true,
        defalutCouponId: finCouponId ? '' : defalutCouponId,
        [finCouponName] : finCouponId,
        // couponId: id,
        haveCoupon: true,
        currentCoupon: `${faceAmount / 100} 元`
      })
    } else if (type == 2) {
      // let discounPrice = (faceAmount / 100) * (orderPrice)
      // let spread = Math.round(orderPrice - discounPrice)
      this.setData({
        defalutCoupon: true,
        [finCouponName] : finCouponId,
        defalutCouponId: finCouponId ? '' : defalutCouponId,
        // couponId: id,
        haveCoupon: true,
        currentCoupon: `${couponDiscount} 元`
      })
    }
    
    // 实付款
    this.setPayPrice()
  },
  setPayPrice() {
    const { currentCoupon, orderInitPrice, isSelect, plusMemberPrice, defalutCoupon } = this.data
    let newCurrentCoupon = currentCoupon ? currentCoupon : 0
    let orderCoupon = parseFloat(newCurrentCoupon) // 优惠券价格
    let plusPrice = isSelect ? plusMemberPrice : 0 // plus
    let calCouponPrice = orderCoupon ? orderCoupon : defalutCoupon

    // 实际价格 - 优惠价 + plus
    this.setData({
      // orderPrice: Math.round(orderInitPrice - orderCoupon)
      // orderPrice: orderInitPrice - orderCoupon + plusPrice
      orderPrice: orderInitPrice - calCouponPrice + 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,
          province: this.data.params.province,
          city: this.data.params.city,
          district: this.data.params.district,
          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.data.addressId = res.data.data;

          this.setData({
            addressId: this.data.addressId
          });

          // 调起支付
          this.handelGobuy()
        }
      })
    } else {
      // 调起支付
      this.handelGobuy()
    }

  },
  initCitys() {
    let cityData = city.default;
    let province = []
    let cityList = []
    let district = []
    cityData.forEach((item) => {
      province.push(item.value)
    })
    cityData[0].children.forEach((cityItem) => {
      cityList.push(cityItem.value)
      cityItem.children.forEach((districtItem) => {
        district.push(districtItem.value)
      })
    })

    this.setData({
      citys: [province, cityList, district]
    })
  },
  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,
        'params.province': citys[0][multiIndex[0]],
        'params.city': citys[1][multiIndex[1]],
        'params.district': citys[2][multiIndex[2]]
      })
    }
  },
  bindMultiPickerColumnChange(e) {
    const detail = e.detail
    const index = detail.value
    let cityName = ''
    let cityData = city.default
    let province = []
    let cityList = []
    let district = []
    switch (detail.column) {
      case 0:
        cityName = this.data.citys[0][index]
        this.data.selectCityName[0] = cityName
        cityData.forEach((item) => {
          if (item.value == cityName) {
            item.children.forEach((cityItem) => {
              cityList.push(cityItem.value)
              cityItem.children.forEach((districtItem) => {
                district.push(districtItem.value)
              })
            })
          }
        })
        this.setData({
          'citys[1]': cityList,
          'citys[2]': district
        })
        break
      case 1:
        cityName = this.data.citys[1][index]
        this.data.selectCityName[1] = cityName
        cityData.forEach((item) => {
          item.children.forEach((cityItem) => {
            if (cityName == cityItem.value) {
              cityItem.children.forEach((districtItem) => {
                district.push(districtItem.value)
              })
            }
          })
        })
        this.setData({
          'citys[2]': [...district]
        })
        break
      default:
        break
    }
  },
  handelChangeSelectVip() {
    this.setData({
      isSelect: !this.data.isSelect
    }, () => {
      const { isSelect } = this.data
      this.setData({
        checkByPremium: isSelect,
        defalutCoupon: 0,
        couponId: '',
        couponSettingId: '',
        defalutCouponId: ''
      }, () => {
        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?isFrom=order')
  },
  // 计算优惠价
  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()
         let skuList = data.tradePreviewSkus

        let sum =0
         skuList.forEach((item,index) => {
          //  item.price
          sum += skuList[index].price
         })

         // 初始化商品价格
         const { isSelect } = this.data

         if(isSelect){
           this.setData({
             selectPrice: sum
           })
         } else {
          this.setData({
            noSelectPrice: sum
          })
         }
         // id / couponSettingId
          this.setData({
            currentOrderList: data,
            defalutCoupon: data && data.couponDiscountPreviews.length && 
            data.couponDiscountPreviews[0].couponSettingDTO.type == 1 ? 
            data && data.couponDiscountPreviews.length && 
            data.couponDiscountPreviews[0].couponSettingDTO.faceAmount / 100 : data && 
            data.couponDiscountPreviews.length && data.couponDiscountPreviews[0] && 
            data.couponDiscountPreviews[0].couponDiscount,
            defalutCouponId: data && data.couponDiscountPreviews.length && 
            data.couponDiscountPreviews[0] && data.couponDiscountPreviews[0].couponDTOS[0] && 
            data.couponDiscountPreviews[0].couponDTOS[0].id || '',
            couponSettingId: data && data.couponDiscountPreviews.length && 
            data.couponDiscountPreviews[0] && data.couponDiscountPreviews[0].couponDTOS[0] && 
            data.couponDiscountPreviews[0].couponDTOS[0].couponSettingId || '',
            orderInitPrice: data.amount
          }, () => {
            // 实付款
            this.setPayPrice()
          })
        }
      }
    })
  },
  handelGobuy() {
    // 第一项 defalutCouponId couponId/
    const { 
      isSelect, 
      defalutCoupon,
      trolleySku2Buy, 
      couponId, 
      couponSettingId, 
      addressId, 
      addressInfo, 
      defalutCouponId 
    } = this.data;
   
    let finCouponName,finCouponId 
     if(!defalutCoupon) {
      finCouponName = 'couponId'
      finCouponId = ''
     } else {
      // 当前选中 哪一个id  couponSettingId
      // 默认券存在 id settingId
      let currentCouponId // couponId / 第一项 id
      if(defalutCouponId) {
        finCouponId = defalutCouponId
        finCouponName = 'couponId'
      } else {
        currentCouponId = couponId ? couponId : couponSettingId
        finCouponName = couponId ? 'couponId' : 'couponSettingId'
        finCouponId = currentCouponId
      }
     }
     
    let params = {
      [finCouponName]: finCouponId,
      // couponId: couponId? couponId : defalutCouponId,
      trolleySku2Buy,
      addressId: addressId ? addressId : addressInfo.id // 微信地址 or 地址id
    }

    //判断addressId是不是有
    if (!params.addressId){
      wx.showToast({
        title: '请添加地址或选择地址',
        icon : 'none'
      })
      return ;
    }

    this.getBill(params) // 下单
  },
  //  下单
  getBill(params) {
    wx.showLoading({
      title: '加载中'
    })
    const { isSelect} = this.data
    let url = isSelect ? '/sale/payment/merged/buyer/bill' : '/sale/trade/buyer/bill'
    wxService.post(`${url}`, params).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          delete data.appId
          let amount = data.amount || 0
          wx.requestPayment(Object.assign({
            success(res) {
              wx.hideLoading()
              // 支付成功页面
              wx.redirectTo({
                url: `/subPackage/page/pages/paymentStatus/paymentStatus?status=S&amount=${amount}`,
              });
            },
            fail(res) {
              wx.hideLoading()
              //  wxService.router(`/subPackage/page/pages/paymentStatus/paymentStatus?status=F`)
              wx.redirectTo({
                url: '/pages/order/order',
              });
              //  wxService.router(`/pages/orderDetail/orderDetail?id=${id}`)
            }
          }, 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) {
          wx.removeStorageSync('_defalutAddress');
          this.data.addressId = '';
          this.data.addressInfo = null;
          this.setData({
            goodsAddress: true
          });
          const { trolleySku2Buy, checkByPremium, addressId, addressInfo } = this.data
          let params = {
            checkByPremium,
            trolleySku2Buy,
          }
          this.calPreferentialPrice(params)  // 计算优惠价
        } 
        else {
          // 缓存有没有地址
          let hasDefalut = wx.getStorageSync('_defalutAddress')
          let _defalutAddress = null
          //有默认地址  但是需要判断当前缓存的默认地址在地址列表中还是否存在 如果不存在则删除 存在则使用
          if (hasDefalut){
            let id = hasDefalut.id;
            let filterArr = data.filter(item => item.id == id);
            if(filterArr.length > 0){
              _defalutAddress = hasDefalut
            }
            else{
              //移除地址
              wx.removeStorageSync('_defalutAddress');
              this.setData({
                goodsAddress: true
              });
              const { trolleySku2Buy, checkByPremium} = this.data;
              let params = {
                checkByPremium,
                trolleySku2Buy,
              }
              this.calPreferentialPrice(params) 
            }
          }
          else{
            data.forEach(item => {
              item.fullArea = item.province + ' ' + item.city + ' ' + item.district
              if (item.type == 1) {
                _defalutAddress = item
              }
            })
          }

          this.data.addressId = _defalutAddress ? _defalutAddress.id : '';
          this.setData({
            addressInfo: _defalutAddress,
            addressId: this.data.addressId
          }, () => {
            // 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) => {
        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()
        })

        this.data.addressInfo.fullArea = this.data.addressInfo.provinceName + ' ' + 
          this.data.addressInfo.cityName + ' ' + this.data.addressInfo.countyName
        wx.setStorageSync('_defalutAddress', this.data.addressInfo)
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },

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