// nova-tourism/pages/collect/collect-detail/index.js
let Parse = getApp().Parse;
const company = getApp().globalData.company
const uid = Parse.User.current()?.id
let sev = require('../../../service/request')
const login = require("../../../../utils/login");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: 0,
    screenHeight: 0,
    customHeight: 0,
    bottomNavHeight: 0,
    contentHeight: 0,


    gid: null, //商品id
    good: null, //商品详情
    spec: null, //商品规格
    checkSpec: null, //选中的规格
    totalPrice: 0, //订单总价
    address: null, //收货地址
    tradeNo: null, //订单编号
    order: null, //当前订单-parse
    distributeType: 'delivery', //配送方式-默认物流配送
    count: 1, //单独购买商品总数
    specMap: {}, //save到订单的数据
    specBox: false, //规格弹框
    moreBox: false, //选择多款弹框
    listBox: false, //多款列表弹框
    specGoodList: [], //选择的多款商品-多款
    checkSpec_more: null, //选中的规格-多款
    count_more: 1, //购买商品总数-多款
    totalPrice_more: 0, //订单总价-多款
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    const screenHeight = systemInfo.screenHeight || 0;
    const custom = wx.getMenuButtonBoundingClientRect();
    const customHeight = custom.height + 10 + 2 || 0;
    const bottomNavHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom || 0;
    const contentHeight = (screenHeight - bottomNavHeight - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
    this.setData({
      statusBarHeight,
      screenHeight,
      customHeight,
      bottomNavHeight,
      contentHeight
    });
    this.setData({
      gid: options?.gid
    })
    this.refersh()
  },

  async refersh() {
    this.getGood()
  },
  /**获取商品 */
  async getGood() {
    let {
      gid
    } = this.data
    let query = new Parse.Query('ShopGoods')
    query.include('shopStore')
    let d = await query.get(gid)
    let good = d?.toJSON()
    if (!good?.images || good?.images?.length <= 0) good.images = [good.image || 'https://file-cloud.fmode.cn/EbxZUK5lBI/20250321/vdq1j1110711455.jpg']
    if (!good?.specMap || !good?.specMap?.specList || good?.specMap?.specList?.length <= 0) {
      good.specMap = {
        specList: [good?.name || '暂无规格']
      }
      good.specMap[good?.name || '暂无规格'] = [{
        price: good?.price || 0,
      }]
    }
    console.log(good)
    let spec = good?.specMap?.specList
    let checkSpec = {}
    if (spec && spec?.length > 0) {
      checkSpec = good?.specMap[spec[0]][0]
      checkSpec.title = spec[0]
    }
    let totalPrice = checkSpec?.price || good?.price
    console.log(spec, checkSpec)
    this.setData({
      good,
      store: good.shopStore,
      spec,
      checkSpec,
      totalPrice
    })
    this.getTotalPrice()
  },
  /**切换配送方式 */
  chickDistributeType(e) {
    let {
      type
    } = e.currentTarget.dataset
    this.setData({
      distributeType: type
    })
  },

  /** 打开规格弹框*/
  openSpec() {
    let userInfo = wx.getStorageSync("userLogin");
    if ( userInfo == ''||!userInfo) {
      console.log(userInfo);
      login.loginNow()
      return
    }
    
    let {
      spec
    } = this.data
    if (spec?.length <= 0) return
    this.setData({
      specBox: true
    })
  },
  /**关闭规格弹框 */
  closeSpec() {
    this.setData({
      specBox: false
    })
  },
  /**选择规格 */
  getCheckSpec(e) {
    let {
      good,
      spec,
      checkSpec,
      totalPrice,
    } = this.data
    let {
      title
    } = e.currentTarget.dataset
    checkSpec = good?.specMap[title][0]
    checkSpec.title = title
    totalPrice = checkSpec?.price || good?.price
    console.log(spec, checkSpec)
    this.setData({
      spec,
      checkSpec,
      totalPrice,

    })
    this.getTotalPrice()

  },
  /**单个物品-步进器改变 */
  changeCount(e) {
    this.setData({
      count: e.detail
    })
    this.getTotalPrice()
  },
  /**计算单个物品总价/获取specMap */
  getTotalPrice() {
    let {
      good,
      count,
      checkSpec
    } = this.data
    let specMap = {}
    specMap[good.objectId] = {
      count,
      price: checkSpec.price,
      spec: checkSpec?.title || ''
    }
    let totalPrice = parseFloat((count * checkSpec.price).toFixed(2))
    console.log(specMap, totalPrice)
    this.setData({
      totalPrice,
      specMap
    })
  },




  /** 打开多款弹框*/
  openMoreBox() {
    let {
      spec,
      checkSpec,
      good
    } = this.data
    console.log(spec, checkSpec, good)
    let price = good.specMap[spec[0]][0].price || good.price
    this.setData({
      moreBox: true,
      count_more: 1,
      checkSpec_more: {
        price: price,
        title: spec[0],
        totalPrice: price
      }
    })
    console.log(spec, checkSpec, good)

  },
  /**关闭多款弹框 */
  closeMoreBox() {
    this.setData({
      moreBox: false
    })
  },
  /**多款-步进器改变 */
  changeCount_more(e) {
    this.setData({
      count_more: e.detail
    })
    this.getCurrentSpec()
  },
  /**选择规格-多款 */
  getCheckSpec_more(e) {
    let {
      good,
      spec,
      checkSpec_more,
    } = this.data
    let {
      title
    } = e.currentTarget.dataset
    checkSpec_more = good?.specMap[title][0]
    checkSpec_more.title = title
    console.log(spec, checkSpec_more)
    this.setData({
      checkSpec_more,
    })
    this.getCurrentSpec()
  },
  /**计算当前款式价格/specMap - 多款 */
  getCurrentSpec() {
    let {
      checkSpec_more,
      count_more
    } = this.data
    let totalPrice = (checkSpec_more.price * count_more || 0).toFixed(2)
    checkSpec_more.totalPrice = totalPrice
    console.log(checkSpec_more, count_more)
    this.setData({
      checkSpec_more
    })
  },
  /**确定当前款 */
  confirmCurrent() {
    let {
      specGoodList,
      count_more,
      checkSpec_more,
    } = this.data
    let index = specGoodList?.findIndex(item => item.spec == checkSpec_more.title)
    if (index < 0) {
      specGoodList.push({
        count: count_more,
        price: checkSpec_more.price,
        spec: checkSpec_more.title,
        checked: true
      })
    } else {
      specGoodList[index] = {
        count: count_more,
        price: checkSpec_more.price,
        spec: checkSpec_more.title,
        checked: true
      }
      wx.showToast({
        title: `已勾选并修改 ${checkSpec_more.title} 款式数量为${count_more}`,
        icon: 'none'
      })
    }
    this.setData({
      specGoodList
    })
    this.getTotalPrice_more()
    this.closeMoreBox()
    this.openListBox()
  },
  /**计算物品总价 - 多款*/
  getTotalPrice_more() {
    let {
      good,
      specGoodList,
      totalPrice_more,
    } = this.data
    totalPrice_more = 0
    let list = specGoodList.filter(item => item.checked)
    for (let i in list) {
      let item = list[i]
      if (item.checked) {
        totalPrice_more = parseFloat((totalPrice_more + (item.price * item.count)).toFixed(2))
      }
    }
    let specMap = {}
    specMap[good.objectId] = {
      price: totalPrice_more || 0,
      list: list || []
    }
    console.log(specMap, specGoodList, totalPrice_more)
    this.setData({
      totalPrice_more: parseFloat(totalPrice_more),
      specMap,
      specGoodList
    })
  },
  /**列表-多款-步进器改变 */
  changeLMCount(e) {
    let {
      specGoodList
    } = this.data
    let {
      index
    } = e.currentTarget.dataset
    specGoodList[index].count = parseInt(e.detail || 1)
    this.setData({
      specGoodList
    })
    this.getTotalPrice_more()
  },
  /**列表-是否选中 */
  changeChecked(e) {
    console.log(e)
    let {
      specGoodList
    } = this.data
    let {
      index
    } = e.currentTarget.dataset
    specGoodList[index].checked = e.detail
    this.setData({
      specGoodList
    })
    this.getTotalPrice_more()
  },



  /**多款款式弹框-去结算 */
  settlement() {
    this.closeMoreBox()
    this.openListBox()
  },


  /** 打开多款列表弹框*/
  openListBox() {
    this.setData({
      listBox: true,

    })
  },
  /**关闭多款列表弹框 */
  closeListBox() {
    this.setData({
      listBox: false
    })
  },




  /** 判断是否可创建订单*/
  judgeOrder() {
    let {
      address,
      distributeType
    } = this.data
    if (distributeType == 'delivery' && !address?.objectId) {
      wx.showToast({
        title: '请确认收货地址',
        icon: 'none',
      });
      return false
    }
    return true
  },
  /** 判断是否可创建订单-多款*/
  judgeOrder_more() {
    let addCheck = this.judgeOrder()
    let {specGoodList} = this.data
    let index = specGoodList.findIndex(item=>item.checked)
    if(addCheck&&index!=-1) return true
    return false
  },
  /**创建订单-单个商品 */
  async submitOrder() {
    this.getTotalPrice()
    let isPass = this.judgeOrder()
    if (!isPass) return
    let {
      good,
      totalPrice,
      address,
      order,
      tradeNo,
      specMap,
      distributeType
    } = this.data
    let o = order
    if (!order?.id) {
      let Order = Parse.Object.extend("Order");
      o = new Order()
      o.set("company", {
        __type: 'Pointer',
        className: 'Company',
        objectId: company
      })
      o.set("store", {
        __type: 'Pointer',
        className: 'ShopStore',
        objectId: good?.shopStore?.objectId
      })
      o.set("user", {
        __type: 'Pointer',
        className: '_User',
        objectId: uid
      })
      o.set('status', '100') //待支付
      o.set('type', 'scenery')
      o.set("targetObject", [{
        "__type": "Pointer",
        "className": "ShopGoods",
        "objectId": good?.objectId
      }])
    }
    let now = new Date()
    tradeNo = "C" +
      String(now.getFullYear()) +
      (now.getMonth() + 1) +
      now.getDate() +
      now.getHours() +
      now.getMinutes() +
      now.getSeconds() +
      Math.random().toString().slice(-6);
    o.set("orderNum", tradeNo);
    o.set("totalPrice", totalPrice || 0);
    o.set("distributeType", distributeType || 'verify');
    if (distributeType == 'verify') {
      o.set("info", {});
    } else {
      o.set("address", {
        __type: 'Pointer',
        className: 'ShopAddress',
        objectId: address?.objectId
      });
      o.set("info", {
        name: address?.name,
        mobile: address?.mobile,
        address: address?.full_region + address?.address
      });
    }
    o.set("specMap", specMap);
    try {
      order = await o.save()
      this.setData({
        tradeNo,
        order: o,
        showPay: true,
        showPay_more:false,
      })
      wx.showToast({
        title: '已创建订单',
        icon: 'none'
      })
    } catch (error) {
      wx.showToast({
        title: '出错了请检查后重试',
        icon: 'error'
      })
    }
  },
  /**创建订单-多款规格 */
  async submitOrder_more() {
    this.getTotalPrice_more()
    let isPass = this.judgeOrder_more()
    if (!isPass) return
    let {
      good,
      totalPrice_more,
      address,
      order,
      tradeNo,
      specMap,
      distributeType
    } = this.data
    let o = order
    if (!order?.id) {
      let Order = Parse.Object.extend("Order");
      o = new Order()
      o.set("company", {
        __type: 'Pointer',
        className: 'Company',
        objectId: company
      })
      o.set("store", {
        __type: 'Pointer',
        className: 'ShopStore',
        objectId: good?.shopStore?.objectId
      })
      o.set("user", {
        __type: 'Pointer',
        className: '_User',
        objectId: uid
      })
      o.set('status', '100') //待支付
      o.set('type', 'scenery')
      o.set("targetObject", [{
        "__type": "Pointer",
        "className": "ShopGoods",
        "objectId": good?.objectId
      }])
    }
    let now = new Date()
    tradeNo = "C" +
      String(now.getFullYear()) +
      (now.getMonth() + 1) +
      now.getDate() +
      now.getHours() +
      now.getMinutes() +
      now.getSeconds() +
      Math.random().toString().slice(-6);
    o.set("orderNum", tradeNo);
    o.set("totalPrice", totalPrice_more || 0);
    o.set("distributeType", distributeType || 'verify');
    if (distributeType == 'verify') {
      o.set("info", {});
    } else {
      o.set("address", {
        __type: 'Pointer',
        className: 'ShopAddress',
        objectId: address?.objectId
      });
      o.set("info", {
        name: address?.name,
        mobile: address?.mobile,
        address: address?.full_region + address?.address
      });
    }
    o.set("specMap", specMap);
    try {
      order = await o.save()
      this.setData({
        tradeNo,
        order: o,
        showPay: false,
        showPay_more:true
      })
      wx.showToast({
        title: '已创建订单',
        icon: 'none'
      })
    } catch (error) {
      wx.showToast({
        title: '出错了请检查后重试',
        icon: 'error'
      })
    }
  },
  /**支付回调 */
  async acceptResult(e) {
    let {
      order,good
    } = this.data
    let {
      params
    } = e.detail
    if (params == 'ok') {
      wx.showLoading({
        title: '加载中',
      })
      order.set('status', '200')
      order.set('payTime',new Date())
      order.set('payType', 'wx')
      order.set('isPay', true)
      try {
        await order.save()
        // let query = new Parse.Query('_User')
        // let userParse = await query.get(uid)
        // console.log(userParse)
        // if(!userParse?.get('invite')){
        //   let shop_query = new Parse.Query('ShopStore')
        //   let shop = await shop_query.get(good?.shopStore?.objectId)
        //     if(shop?.get('user')?.id){
        //      await sev.bindShop(uid,shop?.id)
        //     }
        // }
        setTimeout(() => {
          wx.hideLoading()
          wx.redirectTo({
            url: '/nova-tourism/pages/my/my-order/index?active=0',
          })
        }, 1000);
      } catch (error) {
        console.log(error)
        wx.showToast({
          title: '保存订单出错，请联系客服核对订单',
          icon: 'none'
        })
      }
    } else {
      wx.showToast({
        title: '支付失败',
        icon: 'none'
      })
    }
  },
/**预览图片 */
preview(e){
  let {
    list,index
  } = e.currentTarget.dataset
  sev.previewImgs(list,index)
},
  /** 跳转*/
  tourl(e) {
    let userInfo = wx.getStorageSync("userLogin");
    if ( userInfo == ''||!userInfo) {
      console.log(userInfo);
      login.loginNow()
      return
    }
    const url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: `${url}` // 目标页面的路径
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    let address = await sev.getAddress()
    console.log(address)
    this.setData({
      address
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})