const mixins = require('@/mixins/index.js')
const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const app = getApp();
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    // 预存金额 预收金额
    amountArr: [{
        title: mixins.$t('receivableAmount'),
        code: 'receivableResidue'
      },
      {
        title: mixins.$t('advancePaymentAmount'),
        code: 'receiptResidue'
      }
    ],
    table: Constants.tables.outlay,
    cardList: [{
        name: 'main'
      },
      {
        name: 'items',
        title: mixins.$t('meet'), //'应付',
        chooseFlag: true,
        addFlag: false,
        chooseTitle: mixins.$t('selectCategory'), //'选类别',
        urlKey: 'selectIncomeCategory'
      },
      {
        name: 'file'
      }
    ],
    contentObj: {
      main: [{
          code: 'accDate',
          name: 'accDate',
          title: mixins.$t('paymentDate'), //'收款日期',
          type: 'date',
          required: true,
        },
        {
          code: 'staffId',
          name: 'staffName',
          required: true,
          title: mixins.$t('payer'), //''付款人',
          type: 'choose',
          urlKey: 'chooseStaff'
        },
        {
          code: 'orgId',
          name: 'orgName',
          required: true,
          type: 'choose',
          urlKey: 'chooseOrg'
        },
        {
          code: 'sumAmount',
          type: 'number',
          title: mixins.$t('thisPaymentgo'), //'本次付款',
          required: true
        },

      ],
      items: [{
          code: 'receivableTypeName',
          name: '',
          type: 'str',
          title: mixins.$t('expenditureCategory'), //'支出类别',
          readonly: true,
          required: true
        },
        {
          code: 'amtPayable',
          type: 'number',
          title: mixins.$t('paymentAmount'), //''付款金额',
          required: true,
          control: 'receivableTypeName'
        },

      ],
      file: [{
          code: 'remarks',
          type: 'textarea',
          title: mixins.$t('remarks'), //'备注'
        },
        {
          code: 'file',
          type: 'uploader',
          title: mixins.$t('uploader'), //'附件'
        }
      ]
    },
    totalObj: {
      items: [{
          code: 'receivableWaive',
          title: mixins.$t('totalPayable'), //'合计应付',
        },
        {
          code: 'verificationAmount',
          title: mixins.$t('verificationAmount'), //'核销金额',
        },
      ],
    },
    // 弹出按钮
    buttonList: [{
      name: 'merge',
      title: mixins.$t('collection')
    }],
    contentList: [{
      code: 'need',
      title: mixins.$t('amountCollected'),
      type: 'str'
    }, {
      code: 'amount',
      content: 0,
      type: 'number'
    }],
    btnFormData: null,
    routeObjName: 'otherPayable'
  },
  /**
   * @desc : 2024-04-28类型转成时间戳
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  convertDateToMillisecondsTimestamp(dateString) {
    // 创建Date对象  
    const date = new Date(`${dateString}T00:00:00Z`); // 假设dateString是YYYY-MM-DD格式，并添加T00:00:00Z使其成为ISO 8601格式  
    // 获取毫秒级时间戳  
    const timestamp = date.getTime();
    return timestamp;
  },
  /**
   * @desc : 给表单赋值
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setValuesByEdit(data) {
    console.log("setValuesByEdit", data);
    let formData = JSON.parse(this.data.formData)
    let cardList = this.data.cardList
    formData = data.data
    data.dataItem.forEach(element => {
      element.dataId = element.payableType
      element.receivableTypeName = element.payableTypeName
    });
    formData.itemList = data.dataItem
    let itemNumber = 0
    //收入类别list
    formData.itemList.forEach(element => {
      if (!isNaN(element.amtPayable)) { //是数字才能加减
        itemNumber = Number(itemNumber) + Number(element.amtPayable)
      }
    });
    formData.sumAmount = data.data.sumAmtPay //本次付款
    formData.verificationAmount = formData.sumAmount //核销金额
    formData.receivableWaive = itemNumber // 合计金额 
    formData.supId = data.data.objectId

    let objInfo = {
      supId: data.data.objectId,
      supCode: data.data.supCode,
      supName: data.data.supName,
    }
    let contentList = this.data.contentList
    contentList.forEach(it => {
      if (it.type == 'number') {
        it.content = formData.sumAmount
      }
    })
    formData.objInfo = objInfo
    let dataTime = this.convertDateToMillisecondsTimestamp(formData.accDate)
    this.setData({
      contentList: contentList,
      dataTime: dataTime,
      itemData: data,
      formData: JSON.stringify(formData),
      cardList: cardList,
    })
    this.changeItemNumberField()
    this.changeNumber()
  },
  /**
   * @desc   : 绑定数据-选择页面返回的逻辑处理
   * @author : 王英杰
   * @date   : 2024年3月12日
   */
  chooseData(e) {
    console.log("t", e, this.data.formData);
    let formData = JSON.parse(this.data.formData)
    let cardList_ = this.data.cardList
    let code = e.detail.code
    let data = e.detail.data.data
    if (code == "supId") { //供应商
      formData.supId = data.id
      formData.supName = data.name
    }
    if (code == "staffId") { //员工
      formData.staffId = data.id
      formData.staffName = data.name
    }
    if (code == "orgId") { //部门
      formData.orgId = data.id
      formData.orgName = data.name
    }
    if (code == "items") { //选单 
      if (data && data.list) {
        data.list.forEach(element => {
          element.receivableType = element.dataCode
          element.receivableTypeName = element.dataValue
        });
        formData.itemList = data.list
      }
    }

    this.setData({
      cardList: cardList_,
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc   : 删除明细回调
   * @author : 王英杰
   * @date   : 2024年3月12日
   */
  delItem() {
    let formData = JSON.parse(this.data.formData)
    let cardList = this.data.cardList
    if (formData.itemList) {
      let itemNumber = 0
      formData.itemList.forEach(element => {
        if (!isNaN(element.amtPayable)) { //是数字才能加减
          itemNumber = Number(itemNumber) + Number(element.amtPayable)
        }
      });
      cardList.forEach(element => {
        if (element.name == 'items') {
          element.receivableWaive = itemNumber
        }
      });
      this.setData({
        cardList: cardList,
      })
    }
  },
  /**
   * @desc : form表单 上 number类型修改回调
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  changeNumber() {
    let formData = JSON.parse(this.data.formData)
    let contentList = this.data.contentList
    contentList.forEach(it => {
      if (it.type == 'number') {
        it.content = formData.sumAmount
      }
    })
    formData.verificationAmount = formData.sumAmount
    this.setData({
      contentList: contentList,
      formData: JSON.stringify(formData),
    })

  },
  /**
   * @desc : 明细里得 收入金额 输入完回调 计算出合计
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  changeItemNumberField() {
    let formData = JSON.parse(this.data.formData)
    if (formData.itemList) {
      let itemNumber = 0
      formData.itemList.forEach(element => {
        if (!isNaN(element.amtPayable)) { //是数字才能加减
          itemNumber = Number(itemNumber) + Number(element.amtPayable)
        }
      });
      formData.receivableWaive = itemNumber
      this.setData({
        formData: JSON.stringify(formData),
      })
    }
  },
  /**
   * @desc : 保存数据服务--校验
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  validData() {
    let formData = JSON.parse(this.data.formData)
    if (formData.receivableWaive < formData.verificationAmount) { //核销金额不能大于应收金额
      util.showToast('核销金额不能大于应收金额');
      return false
    }

    return true
  },
  /**
   * @desc : 保存的參數設置
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  setParams(params) {
    let formData = JSON.parse(this.data.formData)
    //收付款类型-收款的查询参数
    params.objectType = '对象类型-供应商'
    params.objectId = formData.objInfo.cusId
    params.orgId = formData.orgId //组织部门
    params.staffId = formData.staffId // 员工
    params.accDate = formData.accDate
    params.annexPaths = formData.annexPaths || [] //附件 
    params.remarks = formData.remarks // 备注
    params.makeStaff = app.globalData.user.staffId // 制单人 
    let itemList = []
    let itemNumber = 0
    formData.itemList.forEach(element => {
      if (!isNaN(element.amtPayable)) { //是数字才能加减
        itemNumber = Number(itemNumber) + Number(element.amtPayable)
      }
      let item = {}
      item.payableType = element.dataId //收入类别
      item.amtPayable = element.amtPayable //收入金额  
      itemList.push(item)
    });
    params.itemList = itemList //商品明细 
    params.sumAmtPayable = itemNumber
    return params
  },

  /**
   * @desc : 保存数据服务
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  saveData() {
    if (this.data.formMode == Constants.formMode.edit) {
      return this.excute(this.data.service, this.data.service.update, this.data.params)
    } else {
      this.open()
    }
  },
  /**
   * @desc :处理保存后续
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  handleData() {
    this.initdata(this)
  },
  /**
   * @desc : 保存数据服务-跳转收款页面
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  open(e) {
    let _this = this
    wx.navigateTo({
      url: '/package-base-select/pages/select-collection_confirm/select-collection_confirm',
      events: {
        // 回调后
        refresh: function (data) {
          _this.initdata(_this)
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 
        res.eventChannel.emit('params', {
          item: _this.data.formData,
          formType: 9
        })
      }
    })
  },
        /**
   * @desc : 初始化赋值
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  initdata(_this){
    let formData = {}
    let contentList = _this.data.contentList
    //采购人员和采购部门默认带出来（当前登录人
    formData.staffId = app.globalData.user.staffId
    formData.orgId = app.globalData.user.orgId
    formData.staffName = app.globalData.user.staffName
    formData.orgName = app.globalData.user.orgName 
    let  dataTime = _this.getTomorrowsDateTimestamp()
    formData.accDate = _this.getTomorrowsDateString() 
    contentList.forEach(it => {
      if (it.type == 'number') {
        it.content = 0
      }
    })
    _this.setData({
      contentList:contentList,
      dataTime:dataTime,
      formData: JSON.stringify(formData)
    })
  },
  /**
   * @desc : 返回   时间戳
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  getTomorrowsDateTimestamp() {
    // 创建一个表示当前日期和时间的 Date 对象  
    let now = new Date();
    // 将日期增加一天以获取明天的日期  
    now.setDate(now.getDate());
    // 设置时间为 00:00:00，即不带时分秒  
    now.setHours(0, 0, 0, 0);
    // 获取不带时分秒的时间戳  
    let timestamp = now.getTime();
    // 返回时间戳  
    return timestamp;
  },
  /**
   * @desc : 返回   YYYY-MM-DD 的日期
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  getTomorrowsDateString() {
    // 创建一个表示当前日期和时间的 Date 对象  
    let now = new Date();
    // 将日期增加一天以获取明天的日期  
    // now.setDate(now.getDate() + 1);  
    // 获取年份、月份和日期  
    let year = now.getFullYear();
    let month = String(now.getMonth() + 1).padStart(2, '0'); // 月份是从 0 开始的，所以要加 1，并用 0 填充到两位数  
    let date = String(now.getDate()).padStart(2, '0'); // 用 0 填充到两位数   
    // 组合成字符串并返回  
    return `${year}-${month}-${date}`;
  },
  /**
   * @desc : 页面加载数据方法
   * @date : 2024/2/1 15:49
   * @author : 王英杰
   */
  loadInit() {
    if (this.data.formMode == Constants.formMode.edit) {
      wx.setNavigationBarTitle({
        title: mixins.$t('otherExpenditureOrdersEdit'),
      })
    } else {
      wx.setNavigationBarTitle({
        title: mixins.$t('otherExpenditureOrdersAdd'),
      })
      //下面的赋值 只能新建赋值 编辑在setValuesByEdit里赋值
      this.initdata(this)
    }
  },
})