// pages/apply/index.js
import * as UTIL from '../../utils/util.js';
import * as API from '../../utils/API.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIPX: app.globalData.isIPX,
    bookName:'', //付款单位
    formData:{
      accountType:'', //账户类型
      accountDate:'', //收入时间
      jieAmount:'', //收入金额
      accountName:'', //存入账户
      incomeType:'', //收入类型
      billNum:'', //单据编码
      accountSummary:'', //备注说明
      contractionId:'', //合同编码
      incomeExpensesType:1, //收支类别
      subjectNameAll:'',//对方科目
      isBill:0
    },
    incomeTypeOptions:[],  //收入类型选项
    incomeTypeText:'222', //收入类型显示文字
    contractionOptions:[], //付款人合同信息列表接口
    showHt:false,
    payerText:'', //付款人
    sjPics:[], //收据图片列表数据
    fpPics:[], //发票图片列表数据
    qtPics:[],  //其他图片列表数据
    //收入时间弹窗显隐
    srShow:false,
    // minDate: new Date(202, 5, 1).getTime(),
    // maxDate: new Date(2023, 0, 31).getTime(),
    minDate:new Date().getTime() - 180* 24 * 60 * 60 * 1000,
    maxDate:new Date().getTime() + 180* 24 * 60 * 60 * 1000,
    crzhShow:false,
    accountListOptions:[], //存入账户类型选项
    crlxShow:false, //收入类型弹窗显隐
    subjectOptions:[],//科目类型
    showKm:false,
  },
  selectKM(){
    this.setData({showKm:true})
  },
  closeBoxKM(){
    this.setData({showKm:false})
  },
  onConfirmContractionKm(value){
    console.log(value);
    let obj = value.detail.value;
    this.setData({
      'formData.subjectNameAll':obj.subjectNameAll,
      showKm:false,
      'formData.subjectId':obj.subjectId,
    })
  },
  onCancelcrlx(){
    this.setData({crlxShow:false,})
  },
  oncrlxShow(){ this.setData({crlxShow:true})},
  onCancelcrzh(){
    this.setData({crzhShow:false})
  },
  oncrzhShow(){ this.setData({crzhShow:true})},
  onConfirmcrzh(e){
    let data = e.detail.value;
    this.setData({
      crzhShow:false,
      'formData.accountName':data.accountName,
      'formData.accountId':data.id,
      'formData.accountType':data.accountType
    })
  },
  onsrDate(){
    this.setData({srShow:true})
  },
  onClose(){ this.setData({srShow:false})},
  onConfirm(e){
    console.log(e);
    let data = this.getNewDate(new Date(e.detail));
    console.log(data);
    this.setData({'formData.accountDate':data})
    this.setData({srShow:false})
  },
  closeBox(){
    this.setData({showHt:false})
  },
  getNewDate(date){
    //date是传过来的时间戳，注意需为13位，10位需*1000
    //也可以不传,获取的就是当前时间
    var time = new Date(date);
    var year= time.getFullYear()  //年
    var month = ("0" + (time.getMonth() + 1)).slice(-2); //月
    var day = ("0" + time.getDate()).slice(-2); //日
    var mydate = year + "-" + month + "-" + day;
    return mydate
  },
  onConfirmContraction(value){
    let obj = value.detail.value;
    this.setData({
      payerText:obj.name,
      showHt:false,
      'formData.contractionId':obj.id,
      contractionIdID:obj.code
    })
  },
  selectContraction(){
    this.setData({showHt:true})
  },
  bindPickerChange (e) {
    let obj =  e.detail.value;

    this.setData({
      crlxShow:false,
      'formData.incomeType':obj.dictValue,
      incomeTypeText:obj.dictLabel
    })
  },
  inputChange(e){
    this.setData({
      [e.currentTarget.dataset.prop]: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    
    let that = this;
 
    //获取收入单位
    UTIL.httpRequest(API.URL_GET_GETINFO, {method:'GET'}, {
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          this.setData({bookName:res.user.bookName})
        }
      }
    })
    //获取收入类型状态
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'income_type', {method:'GET'}, {
      success: (res) => {
        if(res.data.length>0){
          that.setData({
            incomeTypeOptions:res.data,
            incomeTypeText:res.data[0].dictLabel,
            'formData.incomeType':res.data[0].dictValue
          })
        }
      }
    })

    // 获取合同信息列表
    UTIL.httpRequest(API.URL_GET_CONTRACTIONLIST , {method:'GET'}, {
      success: (res) => {
        that.setData({
          contractionOptions:res.rows,
        })
      }
    })

    //获取当前账套付款账户列表
    UTIL.httpRequest(API.URL_GET_ACCOUNTLIST , {method:'GET'}, {
      success: (res) => {
        that.setData({
          accountListOptions:res.rows,
        })
      }
    })
    
    //查询对方科目
    UTIL.httpRequest(API.URL_GET_SUBJECTLIST , {method:'GET'}, {
      success: (res2) => {
        if(res2.rows.length>0){
          that.setData({
            subjectOptions:res2.rows,
          })
        }
      }
    })
  },
   /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onLoad: function () {
    this.setData({
      ["formData.accountDate"]:this.getNewDate(new Date())
    })
  },

   /**
   * 生命周期函数--监听页面显示
   */
  onReady: function () {
    
  },
  
  deleteimg:function(e){
    let oData = e.currentTarget.dataset;
    let file = this.data[oData.status];
   file.splice(oData.id,1)
   this.setData({
     [oData.status]:file
   })
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  
  uploadSjPics: function (e) { //这里是选取图片的方法
    var that = this;
    var detailPics = that.data.sjPics;
    if (detailPics.length >= that.data.count) {
      wx.showToast({
        title: '最多选择' + that.data.count + '张！',
      })
      return;
    }
    wx.chooseImage({
      count: that.data.count, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        let fileForm = that.data.sjPics
        res.tempFilePaths.forEach(item => {
          fileForm.push({
            file: item,
            fileType:'1',
            bizPath:'cashier',
            tableName:'t_cashier_account_flow',
            tableId:''
          })
        })
        that.setData({
          sjPics:fileForm
        })
      
      },
    })
  },
  uploadFpPics: function (e) { //这里是选取图片的方法
    var that = this;
    var pics = [];
    var detailPics = that.data.fpPics;
    if (detailPics.length >= that.data.count) {
      wx.showToast({
        title: '最多选择' + that.data.count + '张！',
      })
      return;
    }
    wx.chooseImage({
      count: that.data.count, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        let fileForm = that.data.fpPics
        res.tempFilePaths.forEach(item => {
          fileForm.push({
            file: item,
            fileType:'2',
            bizPath:'cashier',
            tableName:'t_cashier_account_flow',
            tableId:''
          })
        })
        that.setData({
          fpPics:fileForm
        })
      },
    })
  },
  uploadQtPics: function (e) { //这里是选取图片的方法
    var that = this;
    var pics = [];
    var detailPics = that.data.qtPics;
    if (detailPics.length >= that.data.count) {
      wx.showToast({
        title: '最多选择' + that.data.count + '张！',
      })
      return;
    }
    wx.chooseImage({
      count: that.data.count, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        let fileForm = that.data.qtPics
        res.tempFilePaths.forEach(item => {
          fileForm.push({
            file: item,
            fileType:'3',
            bizPath:'cashier',
            tableName:'t_cashier_account_flow',
            tableId:''
          })
        })
        that.setData({
          qtPics:fileForm
        })
      },
    })
  },

  swichAccounting:function(e){
    let codeStr = e.currentTarget.dataset.code;
    let formDataObj = this.data.formData;
    if(formDataObj.jieAmount==''){ //收入金额
      UTIL.showToastNoneIcon('请填写收入金额！');
      return false;
    }else if(formDataObj.accountName==''){  //存入账户
      UTIL.showToastNoneIcon('请选择存入账户！');
      return false;
    }else if(formDataObj.accountSummary==''){  //备注说明
      UTIL.showToastNoneIcon('请输入备注说明！');
      return false;
    }else if(formDataObj.incomeType == '2' && formDataObj.contractionId==''){
      UTIL.showToastNoneIcon('收入类型为发包收入，必须选择关联合同！');
      return false;
    }
    let data = this.data.formData;
    data.method = "POST";
    data.checkedStatus = codeStr;
    UTIL.httpRequest(API.URL_POST_GERFLOWADD,data,{
      success: (res) => {
       if(res.code == 200){
          let vouerId = res.data;
          // let vouerId = 1;
          let updataList = [...this.data.sjPics,...this.data.fpPics,...this.data.qtPics];
          for(let i=0; i<updataList.length; i++){
            let arrData=updataList[i];
            arrData.tableId = vouerId;
            wx.uploadFile({
              url: API.URL_GET_UPLOAD,
              filePath: arrData.file,
              name: 'file',
              header: {
                "Content-Type": "multipart/form-data",//记得设置
                "chartset":"utf-8",
                'Authorization':'Bearer '+getApp().globalData.userInfo.token
              },
              formData:arrData,
              success (response){
                console.log(response);
              },
              fail(res){
                console.log(response)
              }
            })
          }
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(function(){
            wx.redirectTo({
              url: '/pages/index/index'
            })
          },2000)
          
      }else{
        UTIL.showToastNoneIcon(res.msg);
      }
      }
    })
   
    },
    onChange(event){
      this.setData({
        [event.currentTarget.dataset.value]: event.detail,
      })
    },
    imgPreviewImage(e){
     
      let currentImgList = e.currentTarget.dataset;
      //获取当前附件列表
      let currentStatus = this.data[currentImgList.status];
      //当前选中图片index
      let currentIndex = currentImgList.id;
 
      let imgList = []
      for(let i = 0; i<currentStatus.length; i++){
        imgList.push(currentStatus[i].file)
      }
   
      wx.previewImage({
        current: imgList[currentIndex], // 当前显示图片的http链接
        urls: imgList // 需要预览的图片http链接列表
      })
      
    },
 

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

  },

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

  },

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

  },

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

  },

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

  }
})