// pages/apply/index.js
import * as UTIL from '../../../utils/util.js';
import * as API from '../../../utils/API.js';
let EVN_CONFIG = require('../../../env/env');
const DISTRIBUTE_ENVIROMENT = 'IMGURL';
let {
  URL_PREFIX,
} = EVN_CONFIG[DISTRIBUTE_ENVIROMENT];
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIPX: app.globalData.isIPX,
    bookName:'', //付款单位
    formData:{
      accountType:'', //账户类型
      accountDate:'', //收入时间
      jieAmount:'', //收入金额
      accountName:'', //存入账户
      incomeType:'', //收入类型
      billNum:'', //单据编码
      accountSummary:'', //备注说明
      contractionId:'', //合同编码
      incomeExpensesType:1, //收支类别
      isBill:0
    },
    incomeTypeOptions:[],  //收入类型选项
    incomeTypeText:'222', //收入类型显示文字
    contractionOptions:[], //付款人合同信息列表接口
    showHt:false,
    payerText:'', //付款人
    sjPics:[], //收据图片列表数据
    fpPics:[], //发票图片列表数据
    qtPics:[],  //其他图片列表数据
    //收入时间弹窗显隐
    srShow:false,
    minDate: new Date(2021, 6, 1).getTime(),
    maxDate: new Date(2023, 0, 31).getTime(),
    crzhShow:false,
    accountListOptions:[], //存入账户类型选项
    crlxShow:false, //收入类型弹窗显隐
    subjectOptions:[],//科目类型
    showKm:false,
    fileForm:[],//上传文件列表
    fileNum:0,//附件总数
  },
  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){
    let data = this.getNewDate(new Date(e.detail));
    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 () {
    
  },
   /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      tableId:options.id
    })
    //获取附件字典
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'bookkeeping_type', {method:'GET'}, {//查询附件字典
      success: (res) => {
        if(res.data.length>0){
          this.setData({
            uploadOptions:res.data,
          })
          let uploadList = res.data
          uploadList.map( (item,index) => {
            console.log(index);
            let oData = {
              tableId: options.id,
              fileType:index+1,
              bizPath:'transfer',
              tableName:'t_cashier_account_flow',
              method:'GET'
            }
            UTIL.httpRequest( API.URL_GET_FINDLIST, oData ,{//查询每个附件字典下的附件
              success: (res2) => {
                console.log(res2);
                let list = [];
                let fileForm = that.data.fileForm?that.data.fileForm:[];
                res2.data.forEach((item2,index2)=>{
                  fileForm.push({
                    file: URL_PREFIX+item2.fileUrl,
                    fileType:index+1,
                    bizPath:'transfer',
                    tableName:'t_cashier_account_flow',
                    tableId:''
                  })
                  list.push({
                    tempFilePath:URL_PREFIX+item2.fileUrl,
                    id:item2.id
                  })
                })
                that.setData({
                  ["uploadOptions["+index+"].Pics"]:list,
                  fileForm:fileForm,
                  fileNum:fileForm.length
                });
                console.log(that.data)
              }
            })
          })
        }
      }
    })
    
    //查询收入详情
    UTIL.httpRequest(API.URL_GET_FLOWGET + options.id , {method:'GET'}, {
      success: (res) => {
        if(res.data.incomeType == 2){
          UTIL.httpRequest(API.URL_GET_INFOGET + res.data.contractionId , {method:'GET'}, {
            success: (res3) => {
              that.setData({
                contractionIdID:res3.data.code,
                payerText:res3.data.name,
              })
            }
          })
        }

        //获取收入类型状态
        UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'income_type', {method:'GET'}, {
          success: (res2) => {
            if(res2.data.length>0){
              that.setData({
                incomeTypeOptions:res2.data,
              })
              that.setData({
                formData:res.data,
                contractionIdID:res.data.code,
                incomeTypeText:UTIL.getTransform(res.data.incomeType,res2.data)
              })
            }
          }
        })
        console.log(res);
      }
    })
    
    UTIL.httpRequest(API.URL_GET_SUBJECTLIST , {method:'GET'}, {
      success: (res2) => {
        if(res2.rows.length>0){
          that.setData({
            subjectOptions:res2.rows,
          })
        }
      }
    })
  },

   /**
   * 生命周期函数--监听页面显示
   */
  onReady: function () {
    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_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,
        })
      }
    })
  },
  
  deleteimg:function(e){
    var that = this ;
    let oData = e.currentTarget.dataset;
    let index = oData.index
    let file = that.data.fileForm;
    console.log(that.data.uploadOptions[index].Pics);
    for (let i = 0; i < file.length; i++) {
      const element = file[i];
      if(element.file == that.data.uploadOptions[index].Pics[oData.id].tempFilePath){
        file.splice(i,1);
      }
    }
    that.data.uploadOptions[index].Pics.splice(oData.id,1);
    // let length = this.data.form.transfers[e.currentTarget.dataset.parentsindex].fileNum - 1;
    this.setData({
      // ["form.transfers["+e.currentTarget.dataset.parentsindex+"].fileNum"]:length,
      [oData.status]:that.data.uploadOptions[index],
      fileForm:file,
      fileNum:that.data.fileNum-1
    })
    UTIL.httpRequest(API.URL_GET_GETFILEREMOVE+e.currentTarget.dataset.imgid , {method:'GET'}, {
      success: (res) => {
        wx.showToast({
          title: '删除成功！',
          icon: 'success',
          duration: 2000,
        })
      }
    })
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  
  uploadSjPics: function (e) { //这里是选取图片的方法
    var that = this;
    var detailPics = that.data.uploadOptions[e.currentTarget.dataset.index].Pics;
    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) {
        console.log(res)
        let fileForm = that.data.fileForm;
        let tem = that.data.uploadOptions[e.currentTarget.dataset.index].Pics?that.data.uploadOptions[e.currentTarget.dataset.index].Pics:[];
        res.tempFilePaths.forEach(item => {
          fileForm.push({
            file: item,
            fileType:e.currentTarget.dataset.index+1,
            bizPath:'cashier',
            tableName:'t_cashier_account_flow',
            tableId:''
          })
          tem.push({
            tempFilePath:item
          })
        })
        that.setData({
          ['uploadOptions['+e.currentTarget.dataset.index+'].Pics']:tem,
          fileForm:fileForm,
          fileNum:fileForm.length
        })
      
      },
    })
  },
  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){
    var that = this;
    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;
    console.log(data);
    UTIL.httpRequest(API.URL_POST_GERFLOWEDIT,data,{
      success: (res) => {
       if(res.code == 200){
        let vouerId = that.data.tableId;
          // let vouerId = 1;
          // let updataList = [...this.data.sjPics,...this.data.fpPics,...this.data.qtPics];
          let updataList = that.data.fileForm;
          console.log(updataList);
          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.navigateBack({
              delta: 1
            })
          },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 () {

  }
})