// pages/ticketMake/ticketMake.js
const utils = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    seller: '', //销方信息
    buyer: '', //购方信息
    invoiceCategory: 1, //发票种类
    proList: [{ //产品列表
      price: '',
      taxRate: '',
      taxRateArr: [], // 税率数组
      taxRateArrIndex: 0, //选中税率下标
      noRatePrice: '', //不含税单价
      noRateTotal: '', //不含税金额
      totalMoney: '', //价税合计
      totalRate: '', //合计税额
      quantity: '',
      spreadFlag: false
    }],
    moneyTotal: 0, //价税合计
    noRateTotal: 0, //合计金额(不含税)
    rateTotal: 0, //合计税额
    curValue: 1, //接收方式
    interactTypeDetail: '',
    payees: ['手动输入'], //收款人
    payeesIndex: '',
    payeesText: '',
    reviewers: ['手动输入'], //复核人
    reviewersIndex: '',
    reviewersText: '',
    drawers: ['手动输入'], //开票人
    drawersIndex: '',
    drawersText: '',
    userInfo: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUser()
  },

  //销方和购方企业信息
  getUser() {
    this.setData({
      buyer: wx.getStorageSync('ticketMakeData'),
      seller:utils.getCurrEntInfo(),
      userInfo: utils.getInfo(),
    })
    this.setData({
      curValue: this.data.buyer.interactType,
      interactTypeDetail: this.data.buyer.customerEmail
    })
    let payees = this.data.payees
    if (this.data.seller.payees) {
      let arr = this.data.seller.payees.split(',')
      payees = payees.concat(arr)
      this.setData({
        payees
      })
    }
    let reviewers = this.data.reviewers
    if (this.data.seller.reviewers) {
      let arr = this.data.seller.reviewers.split(',')
      reviewers = reviewers.concat(arr)
      this.setData({
        reviewers
      })
    }
    let drawers = this.data.drawers
    if (this.data.seller.drawers) {
      let arr = this.data.seller.drawers.split(',')
      arr.push(this.data.userInfo.userName)
      drawers = drawers.concat(arr)
      this.setData({
        drawers
      })
    }
    // utils.getCompany().then(res => {
    //   this.setData({
    //     seller: res.data
    //   })
    // })
  },
  //收款人，复核人, 开票人
  setPayees(e) {
    let index = Number(e.detail.value)
    this.setData({
      payeesIndex: index
    })
  },
  getPayees(e) {
    let value = e.detail.value
    this.setData({
      payeesText: value
    })
  },
  setReviewers(e) {
    let index = Number(e.detail.value)
    this.setData({
      reviewersIndex: index
    })
  },
  setDrawers(e) {
    let index = Number(e.detail.value)
    this.setData({
      drawersIndex: index
    })
  },
  getReviewers(e) {
    let value = e.detail.value
    this.setData({
      reviewersText: value
    })
  },
  getDrawers(e) {
    let value = e.detail.value
    this.setData({
      drawersText: value
    })
  },
  //提交开票
  submitData() {
    //产品信息
    let proList = this.data.proList
    let proListSubmit = []
    let isList = 0
    for (let i = 0; i < proList.length; i++) {
      if (proList[i].totalMoney && proList[i].productName) {
        proListSubmit.push(proList[i])
      }
    }
    let COMMON_FPKJ_XMXX = []
    if (proListSubmit.length <= 0) {
      utils.toast('商品信息不能为空')
      return
    } else {
      if (proListSubmit.length > 8) {
        isList = 1
      } else{
        isList = 0
      }
      for (let i = 0; i < proListSubmit.length; i++) {
        let item = {
          "SPHH": i + 1,
          "FPHXZ": 0,
          "SPBM": proListSubmit[i].taxationCateCode,
          "ZXBM": '',
          "YHZCBS": proListSubmit[i].preferentialFlag,
          "LSLBS": proListSubmit[i].zeroRateFlag,
          "ZZSTSGL": proListSubmit[i].preferentialType,
          "XMMC": proListSubmit[i].productName,
          "GGXH": proListSubmit[i].specsModel,
          "DW": proListSubmit[i].unit,
          "XMJE": proListSubmit[i].noRateTotal,
          "SL": proListSubmit[i].taxRate,
          "SE": proListSubmit[i].totalRate
        }
        // 如果数量为存在并且不为0则传递参数
        if (proListSubmit[i].quantity) {
          item.XMSL = proListSubmit[i].quantity
        }
        // 如果不含税单价存在(为0也可以)则传递参数
        if (proListSubmit[i].noRatePrice !== '') {
          item.XMDJ = proListSubmit[i].noRatePrice
        }
        COMMON_FPKJ_XMXX.push(item)
      }
    }
    //接收方式
    let interactTypeDetail = utils.trimAll(this.data.interactTypeDetail)
    if (interactTypeDetail === '') {
      utils.toast('接收方式不能为空')
      return
    } else {
      if (this.data.curValue === 1) {
        if (!utils.testEmail(interactTypeDetail)) {
          utils.toast('接收方式请填写正确的邮箱')
          return
        }
      }
      if (this.data.curValue === 2) {
        if (!utils.testMobile(interactTypeDetail)) {
          utils.toast('接收方式请填写正确的手机号码')
          return
        }
      }
    }
     //复核人，收款人, 开票人
     let SKR = ''
     let payeesIndex = this.data.payeesIndex
     if (payeesIndex !== '') {
       if (payeesIndex === 0) {
         SKR = utils.trimAll(this.data.payeesText)
       } else {
         SKR = this.data.payees[payeesIndex]
       }
     }
     let FHR = ''
     let reviewersIndex = this.data.reviewersIndex
     if (reviewersIndex !== '') {
       if (reviewersIndex === 0) {
         FHR = utils.trimAll(this.data.reviewersText)
       } else {
         FHR = this.data.reviewers[reviewersIndex]
       }
     }
     let KPR = ''
     let drawersIndex = this.data.drawersIndex
     if (drawersIndex !== '') {
       if (drawersIndex === 0) {
         KPR = utils.trimAll(this.data.drawersText)
       } else {
         KPR = this.data.drawers[drawersIndex]
       }
     }
    //要传递的参数
    let params = {
      mobile: utils.getInfo().mobile,
      reqChannel: 5,
      todoRecordId: this.data.buyer.recordId,
      interactType: this.data.curValue,
      todoRecordId: this.data.buyer.recordId,
      interactTypeDetail: utils.trimAll(this.data.interactTypeDetail),
      cmdParam: {
        "REQUEST_COMMON_FPKJ": {
          "SBLX": this.data.seller.defaultDeviceInfo.deviceType,
          "SBBH": this.data.seller.defaultDeviceInfo.taxDiscId,
          "KPLX": 0,
          "FPZL": this.data.invoiceCategory,
          "TTLX": this.data.buyer.customerType,
          "KPF_NSRSBH": this.data.seller.entTaxId,
          "KPF_MC": this.data.seller.entName,
          "KPF_DZ": this.data.seller.entAddress,
          "KPF_DH": this.data.seller.entPhone,
          "KPF_YHZH": this.data.seller.bankAccountNumber,
          "KPF_KHHMC": this.data.seller.bankName,
          "SPF_NSRSBH": utils.trimAll(this.data.buyer.customerEntTaxId),
          "SPF_MC": utils.trimAll(this.data.buyer.customerName),
          "SPF_DH": utils.trimAll(this.data.buyer.contactPhone),
          "SPF_DZ": utils.trimAll(this.data.buyer.address),
          "SPF_YHZH": utils.trimAll(this.data.buyer.bankAccountNo),
          "SPF_KHHMC": utils.trimAll(this.data.buyer.bankName),          
          "KPR": KPR,
          "SKR": SKR,
          "FHR": FHR,
          "JSHJ": this.data.moneyTotal,
          "HJJE": this.data.noRateTotal,
          "HJSE": this.data.rateTotal,
          "KCE": 0,
          "BZ": utils.trimAll(this.data.buyer.remark),
          "TSPZ": '00',
          "ZSFS": "0",
          "KCE": null,
          "QDBZ": isList,
          "COMMON_FPKJ_XMXXS": {
            "COMMON_FPKJ_XMXX": COMMON_FPKJ_XMXX
          }
        }
      }
    }
    console.log(params);
    utils.axios({
      method: 'post',
      url: '/sys/taitou/todo/handle',
      data: params,
      sendBefore() {
        wx.showLoading({
          title: '提交中...',
          mask: true
        })
      },
      complete() {
        wx.hideLoading()
      },
      success: res => {
        wx.navigateTo({
          url: '/pages/ticketMake/success'
        })
      }
    })
  },

  //计算发票总金额、总税额
  calcMoney() {
    let list = this.data.proList
    let moneyTotal = 0
    let noRateTotal = 0
    let rateTotal = 0
    for (let i = 0; i < list.length; i++) {
      //计算不含税单价、不含税项目金额、价税合计金额
      if (list[i].price !== null && list[i].price !== '' && list[i].quantity) {
        list[i].noRatePrice = parseFloat(list[i].price / (1 + (list[i].taxRate ? list[i].taxRate : 0))).toFixed(6)
        list[i].noRateTotal = parseFloat(list[i].noRatePrice * (list[i].quantity ? list[i].quantity : 0)).toFixed(2)
        list[i].totalMoney = parseFloat(list[i].price * (list[i].quantity ? list[i].quantity : 0)).toFixed(2)
        //税额计算公式：价税合计金额/(1+税率)*税率
        list[i].totalRate = parseFloat(list[i].totalMoney / (1 + (list[i].taxRate ? list[i].taxRate : 0)) * (list[i].taxRate ? list[i].taxRate : 0)).toFixed(2)
      } else {
        list[i].totalMoney = 0
        list[i].noRateTotal = 0
        list[i].totalRate = 0
      }
      //总的相加
      moneyTotal += Number(list[i].totalMoney)
      noRateTotal += Number(list[i].noRateTotal)
      rateTotal += Number(list[i].totalRate)
    }
    this.setData({
      moneyTotal: parseFloat(moneyTotal).toFixed(2),
      noRateTotal: parseFloat(noRateTotal).toFixed(2),
      rateTotal: parseFloat(rateTotal).toFixed(2),
      proList: list
    })
  },
  getTotalMoney(e) {
    let moneyTotal = 0
    let noRateTotal = 0
    let rateTotal = 0
    let list = this.data.proList
    let index = Number(e.currentTarget.dataset.index)
    let totalMoney = e.detail.value
    list[index].totalMoney = parseFloat(Number(totalMoney)).toFixed(2)
    if (list[index].quantity) {
      list[index].price = list[index].totalMoney / list[index].quantity
      list[index].noRatePrice = parseFloat(list[index].price / (1 + (list[index].taxRate ? list[index].taxRate : 0))).toFixed(6)
    } else {
      list[index].price = ''
      list[index].noRatePrice = ''
    }
    for (let i = 0; i < list.length; i++) {
      //计算不含税单价、不含税项目金额、价税合计金额
      if (list[i].totalMoney) {
        list[i].noRateTotal = parseFloat(list[i].totalMoney / (1 + (list[i].taxRate ? list[i].taxRate : 0))).toFixed(2)
        if (i !== index) {
          list[i].totalMoney = parseFloat(list[i].price * (list[i].quantity ? list[i].quantity : 0)).toFixed(2)
        }
        //税额计算公式：价税合计金额/(1+税率)*税率
        list[i].totalRate = parseFloat(list[i].totalMoney / (1 + (list[i].taxRate ? list[i].taxRate : 0)) * (list[i].taxRate ? list[i].taxRate : 0)).toFixed(2)
      }
      //总的相加
      moneyTotal += Number(list[i].totalMoney)
      noRateTotal += Number(list[i].noRateTotal)
      rateTotal += Number(list[i].totalRate)
    }
    this.setData({
      moneyTotal: parseFloat(moneyTotal).toFixed(2),
      noRateTotal: parseFloat(noRateTotal).toFixed(2),
      rateTotal: parseFloat(rateTotal).toFixed(2),
      proList: list
    })
  },
  getPrice(e) {
    let proList = this.data.proList
    let index = Number(e.currentTarget.dataset.index)
    let price = e.detail.value
    proList[index].price = price
    this.setData({
      proList
    })
    this.calcMoney()
  },

  //查询商品
  toSearchPro(e) {
    let index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: `/pages/searchPro/searchPro?index=${index}`
    })
  },

  //添加商品
  addTicket() {
    let proList = this.data.proList
    proList.push({
      price: '',
      taxRate: '',
      taxRateArr: [],
      taxRateArrIndex: 0,
      noRatePrice: '',
      noRateTotal: '',
      totalMoney: '',
      totalRate: '',
      quantity: '',
      spreadFlag: false
    })
    this.setData({
      proList
    })
  },
  // 获取商品编号税率
  getTaxRate(prevIndex, taxCateCode, taxRate) {
    let params = {
      taxCateCode,
      entTaxId: wx.getStorageSync('entTaxId')
    }
    utils.axios({
      method: 'get',
      url: '/sys/entInfo/rates',
      data: params,
      sendBefore() {},
      complete() {},
      success: res => {
        let index = prevIndex
        let proList = this.data.proList
        let result = res.data
        for (let i = 0; i < result.length; i++) {
          result[i] = Number(result[i])
          if (result[i] === taxRate) {
            proList[prevIndex].taxRateArrIndex = i
          }
        }
        proList[prevIndex].taxRateArr = result
        this.setData({
          proList
        })
        this.calcMoney()
      }
    })
  },
  setRate(e) {
    let index = e.currentTarget.dataset.index
    let proList = this.data.proList
    proList[index].taxRateArrIndex = e.detail.value
    proList[index].taxRate = proList[index].taxRateArr[proList[index].taxRateArrIndex]
    this.setData({
      proList
    })
    this.calcMoney()
  },

  //单个商品展开收起
  spread(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      [`proList[${index}].spreadFlag`]: !this.data.proList[index].spreadFlag
    })
  },
  delete(e) {
    let index = e.currentTarget.dataset.index
    let proList = this.data.proList
    proList.splice(index, 1)
    this.setData({
      proList
    })
    this.calcMoney()
  },

  //购物车加
  add(e) {
    let proList = this.data.proList
    let index = e.currentTarget.dataset.index
    let curNum = proList[index].quantity
    curNum++
    let str = 'proList[' + index + '].quantity'
    this.setData({
      [str]: curNum
    })
    this.calcMoney()
  },
  //购物车减
  minus(e) {
    let proList = this.data.proList
    let index = e.currentTarget.dataset.index
    let curNum = proList[index].quantity
    curNum--
    if (curNum <= 0) {
      curNum = 0
    }
    let str = 'proList[' + index + '].quantity'
    this.setData({
      [str]: curNum
    })
    this.calcMoney()
  },
  //input输入框
  inputNum(e) {
    let index = e.currentTarget.dataset.index
    let str = 'proList[' + index + '].quantity'
    this.setData({
      [str]: Number(e.detail)
    })
    this.calcMoney()
  },

  //选择接收方式
  selectType(e) {
    let curValue = e.detail.value
    let interactTypeDetail = ''
    if (curValue === 1) {
      if (this.data.buyer.customerEmail) {
        interactTypeDetail = this.data.buyer.customerEmail
      }
    }
    if (curValue === 2) {
      if (this.data.buyer.customerMobile) {
        interactTypeDetail = this.data.buyer.customerMobile
      }
    }
    if (curValue === 3) {
      interactTypeDetail = '微信卡包'
    }
    if (curValue === 4) {
      interactTypeDetail = '支付宝发票管家'
    }
    this.setData({
      curValue,
      interactTypeDetail
    })
  },
  getDetail(e) {
    this.setData({
      interactTypeDetail: e.detail.value
    })
  },

  //以下是获取表单信息的函数
  //发票种类
  selectCate(e) {
    let invoiceCategory = e.detail.value
    this.setData({
      invoiceCategory
    })
  },
  getremark(e) {
    this.setData({
      ['buyer.remark']: e.detail.value
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '诺信云',
      path: '/pages/index/index'
    }
  }
})