const Http = require('../../utils/HttpBasics.js')
const config = require('../../config/config.js')
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tempFilePaths: [],
    BtempFilePaths: [],
    // typeIndex: 0, //类型下标
    timeIndex: 0, //时间下标
    // typeArray: ['优惠券 >', '代金卷 >',],
    timeArray: ['按日期 >', '按领取天数 >'],
    useLimitRuleLsit: ['限制领取该券总数量', '只限制券包中未使用的该券数量'],
    refundText: ['是', '否'],
    refundIndex: 0, //0 =>是 1=>否
    beginTime: '请选择时间',
    endTime: '请选择时间',
    numDays: "", //按天数
    title: '', //标题
    faceValue: 0, //面值
    selling: 0, //售价\
    bank: 0, //库存
    everyday: 0, //每人限领
    explain: '',
    ifUpdata: false, //判断是否修改
    id: '', //修改id
    examineColor_back: '',
    putApplyStatus: 0, //0未提交审批 1待审批 2审批成功 3审批驳回 
    putApplyText: "待审批通过",
    noUpdata: true,
    couponId: '',
    useLimitRule: 0
  },

  addPicture() {
    const num = this.data.tempFilePaths.length
    if (num == 5) {
      wx.showToast({
        title: '主图限制为5张！',
        icon: 'error'
      })
      console.log(this.data.tempFilePaths, 'tempFilePaths');
      return
    }
    wx.navigateTo({
      url: '/pages/upload/upload?save=1',
    })
  },

  BaddPicture() {
    const num = this.data.BtempFilePaths.length
    if (num == 5) {
      wx.showToast({
        title: '主图限制为5张！',
        icon: 'error'
      })
      console.log(this.data.BtempFilePaths, 'BtempFilePaths');
      return
    }
    wx.navigateTo({
      url: '/pages/upload/upload?save=2',
    })
  },
  /**
   * 取消
   */
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 保存
   */
  save() {
    wx.showLoading({
      title: '加载中',
    })
    if (this.data.timeIndex == 0) {
      if (this.data.beginTime.indexOf('请选择时间') != -1) {
        wx.showToast({
          title: '请选择开始时间',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (this.data.endTime.indexOf('请选择时间') != -1) {
        wx.showToast({
          title: '请选择结束时间',
          icon: 'none',
          duration: 2000
        })
        return
      }
    } else {
      if (this.data.numDays == '') {
        wx.showToast({
          title: '请输入有效期',
          icon: 'none',
          duration: 2000
        })
        return
      }
    }

    let _that = this
    let postData = {
      title: _that.data.title,
      type: "6",
      priceStr: _that.data.faceValue,
      salePriceStr: _that.data.selling,
      inventory: _that.data.bank,
      useLimitQuantity: _that.data.everyday,
      validStartDate: _that.data.timeIndex == 0 ? _that.data.beginTime + ' 00:00:00' : '',
      validEndDate: _that.data.timeIndex == 0 ? _that.data.endTime + ' 23:59:59' : '',
      validDays: _that.data.numDays,
      remark: _that.data.explain,
      subTitle: '', //不用管管副标题 B端没用
      sendType: "1",
      remainInventory: _that.data.bank, //剩余库存
      autoRefund: _that.data.refundIndex, //是否退款
      useLimitRule: (_that.data.useLimitRule * 1) + 1

    }
    if (this.data.timeIndex == 0) {
      //1是时间类型 2是领取后多少天有效
      postData.validType = '1'
    } else {
      postData.validType = '2'
    }
    if (postData.title == '' || postData.priceStr == 0 || postData.inventory == 0 || postData.useLimitQuantity == 0 || postData.validStartDate == '请选择时间' || postData.validEndDate == '请选择时间' || postData.html == '') {
      console.log(postData, 'postData');
      wx.hideLoading();
      wx.showToast({
        title: '请输入完整信息',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (parseInt(postData.priceStr) < parseInt(postData.salePriceStr)) {
      wx.hideLoading();
      wx.showToast({
        title: '面值必须小于售价',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (parseInt(postData.inventory) < parseInt(postData.useLimitQuantity)) {
      wx.hideLoading();
      wx.showToast({
        title: '库存必须大于每人限领',
        icon: 'none',
        duration: 2000
      })
      return
    }
    const beginTime = new Date(_that.data.beginTime)
    const endTime = new Date(_that.data.endTime)
    if (beginTime > endTime) {
      wx.showToast({
        title: '起始时间必须小于结束时间',
        icon: 'none',
        duration: 2000
      })
      return
    }

    if (_that.data.tempFilePaths.length < 1) {
      wx.showToast({
        title: '请至少上传一张主图！',
        icon: 'none',
        duration: 2000
      })
      return
    }
    // if (_that.data.selling<=0){
    //   wx.showToast({
    //     title: '售价必须大于0',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return
    // }
    // console.log(beginTime, endTime)
    // 编辑
    if (_that.data.ifUpdata || _that.data.id != '') {
      // if (_that.data.receiptUrl.indexOf('//tmp') != -1 || _that.data.receiptUrl.indexOf('"http://tmp') != -1) {
      //   console.log(1234568);
      //   wx.uploadFile({
      //     url: config.api.imgUpload,
      //     filePath: _that.data.receiptUrl,
      //     name: 'file',
      //     header: {
      //       'token': app.globalData.token
      //     },
      //     success(res) {
      //       const data = res.data
      //       console.log(data, 'data');
      //       // console.log(JSON.parse(res.data).data.url ,"????hhahah66666")
      //       postData.coverImg = _that.data.receiptUrl
      //       postData.coverPicture = JSON.stringify([_that.data.receiptUrl])
      //       postData.id = _that.data.id
      //       Http.post({
      //         url: config.api.updataCoupon,
      //         data: postData
      //       }).then(res => {
      //         const {
      //           code,
      //           data
      //         } = res
      //         if (code == 200) {
      //           wx.hideLoading();
      //           wx.showToast({
      //             title: '保存成功',
      //             icon: "none",
      //             duration: 1000,
      //           })
      //         }
      //       }).catch(res => {
      //         wx.hideLoading();
      //         wx.showToast({
      //           title: `${res.message}`,
      //           icon: "none",
      //           duration: 1000,
      //         })
      //       })
      //     },
      //     fail(res) {
      //       wx.hideLoading();
      //       wx.showToast({
      //         title: '请上传主图',
      //         icon: "none",
      //         duration: 1000
      //       })
      //     }
      //   })
      //  }
      postData.coverImg = _that.data.tempFilePaths[0]
      postData.coverPicture = JSON.stringify(_that.data.tempFilePaths)
      postData.detailPicture = JSON.stringify(_that.data.BtempFilePaths)
      postData.id = _that.data.id
      Http.post({
        url: config.api.updataCoupon,
        data: postData
      }).then(res => {
        const {
          code,
          data
        } = res
        console.log(code, data, "666")
        _that.setData({
          id: data
        })
        if (code == 200) {
          wx.hideLoading();
          wx.showToast({
            title: '保存成功',
            icon: "none",
            duration: 1000,
            success() {
              setTimeout(() => {
                wx.navigateBack()
              }, 1000);
            }
          })
        }
      }).catch(res => {
        wx.hideLoading();
        wx.showToast({
          title: `${res.message}`,
          icon: "none",
          duration: 1000
        })
      })

    } else {
      // 新建
      console.log(1234567);
      postData.coverImg = _that.data.tempFilePaths[0]
      postData.coverPicture = JSON.stringify(_that.data.tempFilePaths)
      postData.detailPicture = JSON.stringify(_that.data.BtempFilePaths)
      console.log(postData, 'postData');
      Http.post({
        url: config.api.addCoupon,
        data: postData
      }).then(res => {
        const {
          code,
          data
        } = res
        if (code == 200) {
          _that.setData({
            id: data
          })
          wx.hideLoading();
          wx.showToast({
            title: '保存成功',
            icon: "none",
            duration: 1000,
            success() {
              setTimeout(() => {
                wx.navigateBack()
              }, 1000);
            }
          })
        }
      }).catch(res => {
        wx.hideLoading();
        wx.showToast({
          title: `${res.message}`,
          icon: "none",
          duration: 1000,
        })
      })

    }
  },
  /**
   * 提交审批
   */
  examine() {
    wx.showLoading({
      title: '加载中',
    })
    if (this.data.putApplyStatus == 1) {
      wx.hideLoading();
      wx.showToast({
        title: "待审批请勿重复提交",
        icon: 'none',
        duration: 2000,
      })
      return
    }
    if (this.data.id != '') {
      let postData = {
        id: this.data.id,
        remark: ''
      }
      Http.post({
        url: config.api.submitExamine,
        data: postData
      }).then(res => {
        const {
          code,
          message
        } = res;
        console.log(code, message)
        if (code == 200) {
          wx.hideLoading();
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000,
            success: (res => {
              this.goBack()
            })
          })
        }
      })
    } else {
      wx.hideLoading();
      wx.showToast({
        title: '请先保存再提交审核',
        icon: 'error',
        duration: 2000
      })
    }
  },

  /**
   * 获取卷标题
   */
  getTitle(e) {
    this.setData({
      title: e.detail.value
    })
  },
  /**
   * 获取面值
   */
  getfaceValue(e) {
    this.setData({
      faceValue: e.detail.value
    })
  },
  /**
   * 获取售价
   */
  getselling(e) {
    this.setData({
      selling: e.detail.value
    })
  },
  /**
   * 获取库存
   */
  getbank(e) {
    this.setData({
      bank: e.detail.value
    })
  },
  /**
   * 每人限领
   */
  geteveryday(e) {
    this.setData({
      everyday: e.detail.value
    })
  },
  /**
   * 购买须知
   */
  getexplain(e) {
    this.setData({
      explain: e.detail.value
    })
  },
  /**
   * 选择天数获取天数
   */
  getNumDays(e) {
    this.setData({
      numDays: e.detail.value
    })
  },

  //删除图片
  pictureDel(e) {
    const index = e.currentTarget.dataset.index
    const tempFilePaths = this.data.tempFilePaths
    tempFilePaths.splice(index, 1)
    this.setData({
      tempFilePaths,
    })
  },

  //删除图片
  BpictureDel(e) {
    const index = e.currentTarget.dataset.index
    const BtempFilePaths = this.data.BtempFilePaths
    BtempFilePaths.splice(index, 1)
    this.setData({
      BtempFilePaths
    })
  },

  //卷类型选择器：
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      tpyeIndex: e.detail.value
    })
  },
  //先领规则
  setUseLimitRule: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      useLimitRule: e.detail.value
    })
  },
  //时间类型
  timeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      timeIndex: e.detail.value
    })
  },
  //过期是否退款类型
  refundChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      refundIndex: e.detail.value
    })
  },
  setDeginTime: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      beginTime: e.detail.value
    })
  },
  setEndTime: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endTime: e.detail.value
    })
  },
  setRefund: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endTime: e.detail.value
    })
  },
  /**
   * 上架
   */
  putaway() {
    if (this.data.bank <= 0) {
      wx.showToast({
        title: '库存不能为0',
        icon: 'none',
        duration: 2000
      })
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    let postData = {
      couponIds: this.data.id,
      channelId: "1",
      beginTime: "",
      endTime: ""
    }
    Http.post({
      url: config.api.addbatch,
      data: postData
    }).then(res => {
      const {
        code,
        data
      } = res
      if (code == 200) {
        wx.hideLoading();
        wx.showToast({
          title: '上架成功',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.hideLoading();
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000,
        })
      }
    })
  },
  /**
   * 下架
   */
  soldOut() {
    wx.showLoading({
      title: '加载中',
    })
    let postData = {
      id: this.data.id,
      status: "1",
    }
    Http.post({
      url: config.api.soldOut,
      data: postData
    }).then(res => {
      const {
        code,
        data
      } = res
      if (code == 200) {
        wx.hideLoading();
        wx.showToast({
          title: '下架成功',
          icon: 'none',
          duration: 2000,
          success: (res => {
            this.goBack()
          })
        })
      } else {
        wx.hideLoading();
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000,
        })
      }
    })
  },
  /**
   * 作废
   */
  cancellation() {
    wx.showLoading({
      title: '加载中',
    })
    let postData = {
      id: this.data.couponId != '' ? this.data.couponId : this.data.id,
      status: "1",
    }
    Http.post({
      url: config.api.cancellation,
      data: postData
    }).then(res => {
      const {
        code,
        data
      } = res
      if (code == 200) {
        wx.hideLoading();
        wx.showToast({
          title: '作废成功',
          icon: 'none',
          duration: 2000,
          success: (res => {
            this.goBack()
          })
        })
      } else {
        wx.hideLoading();
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000,
        })
      }
    })
  },
  /**
   * 审批历史记录
   */
  lookExamine() {
    console.log("查看审批历史")
    wx.navigateTo({
      url: `/pages/lookExamine/lookExamine?id=${this.data.id}`,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const storTempData = wx.getStorageSync('tmepdata')
    console.log(storTempData);
    if (storTempData) {
      let tempData = JSON.parse(storTempData)
      console.log(tempData)
      this.setData({
        title: tempData.title,
        faceValue: tempData.priceStr,
        selling: tempData.salePriceStr,
        bank: tempData.remainInventory,
        everyday: tempData.useLimitQuantity,
        timeIndex: tempData.validType - 1,
        explain: tempData.remark,
        numDays: tempData.numDays,
        beginTime: tempData.validStartDate,
        endTime: tempData.validEndDate,
        status: tempData.status,
        ifUpdata: true,
        id: tempData.id,
        couponId: tempData.couponId,
        refundIndex: tempData.autoRefund,
        putApplyStatus: tempData.putApplyStatus, //0未提交审批 1待审批 2审批成功 3审批驳回
        channel: tempData.channel, //已上架按钮判断条件 1是已上架,
        noUpdata: tempData.noUpdata, //是否能修改
        useLimitRule: (tempData.useLimitRule * 1) - 1,
      })

      if (tempData.coverPicture) {
        this.setData({
          tempFilePaths: JSON.parse(tempData.coverPicture),
        })
      } else {
        this.setData({
          tempFilePaths: tempData.coverImg,
        })
      }

      if (tempData.detailPicture) {
        this.setData({
          BtempFilePaths: JSON.parse(tempData.detailPicture)
        })
      }

      console.log(this.data.channel, "channel")
      if (this.data.putApplyStatus == 1) {
        this.setData({
          examineColor_back: 'background-color: yellow;color: red;',
          putApplyText: "待审批通过",
        })
      } else if (this.data.putApplyStatus == 3) {
        this.setData({
          examineColor_back: 'background-color: red;color: #fff;',
          putApplyText: "审批未通过",
        })
      } else if (this.data.putApplyStatus == 2) {
        this.setData({
          examineColor_back: 'background-color: green;color: #fff;',
          putApplyText: "审批已通过",
        })
      }
    } else {
      this.setData({
        tempFilePaths: [options.res]
      })
    }
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("123456789")
    if (wx.getStorageSync('tmepdata')) {
      wx.removeStorageSync('tmepdata')
    }
  },

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

  },

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

  },

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

  }
})