// pages/apply/paymentTemplate/add/add.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,
    radio:'1',
    active:0,
    projectText:'',
    balance:0,
    capitalExpenditureTypeOptions:[],
    transferTypeOptions:[],
    projectOptions:[],
    projectFundTypeOptions:[],
    contractionOptions:[],
    accountOptions:[],
    moneyorderOptions:[],
    topInputTirme:false,
    form:{
      approvalItemTemplate:{
        approvalItems:'',//审批事项
        submitCompany:'',//提交单位
        submitDate:'',//提交日期
        submitter:'',//提交人
        telephone:'',//联系方式
        totalAmount:"0.00",//合计金额
        templateName:'',//模板名称 选择保存模板的时候添加
        dataType:'',//数据类型
      },
      transfers:[{//事项信息集合以下是List对象信息
        num:"一",
        amountReadonly:false,
        expenditureAmountTirme:false,
        remarkTirme:false,
        showCapitalExpenditureType:false,
        showApplyDate:false,
        showTransferType:false,
        showProject:false,
        showProjectFundType:false,
        showAccount:false,
        showDialog:false,
        showContraction:false,
        showMoneyOrder:false,
        cashForm:{
          payee:'',
          phone:'',
          unit:'',
          leader:'',
          remark:'',
        },
        SJimage:[],
        FPimage:[],
        QTimage:[],
        activeName:0,
        showTitle:true,
        collapseDis:false,
        capitalExpenditureType:'1',//资金支出类别
        capitalExpenditureTypeText:'结算类',//资金支出类别（展示用）
        succeedAmount:'',//成功支付金额
        payer:'',//付款方
        paymentPattern:'1',
        payerAccount:'',//付款方账户
        bankType:'',//所属银行
        bankTypeText:'',//所属银行（展示用）
        isPeers:'N',//是否同行
        operatorCode:'',//操作员代码
        enterpriseCode:'',//企业编码
        expenditureAmount:'',//支出总金额
        applyDate:'',//申请时间
        transferStatus:'',//转账状态
        auditStatus:'0',//审批状态
        paymentState:'',//支付状态
        approvalMode:'1',//审批模式
        paymentTime:'',//支付时间
        bankPriority:'',//银行处理优先级
        clientPriority:'',//客户处理优先级
        transferType:'1',//付款方式
        transferTypeText:'垫付报销：电子支付',//付款方式（展示用）
        requiredTransferTime:'',//要求转账时间
        remark:'',//付款事由
        startTime:'',//开票日期
        endTime:'',//到期日期
        orderType:'',//汇票类型
        bankAccountType:'2',//账户类别1 公户2私户
        villageAccountType:'',//账户分类
        payeeList:[{//收款方账户集合
          payeeId:'0',//收款方id
          payee:'',//收款方
          bankDeposit:'',//开户行
          incomeAmount:'',//收入金额
          bankType:'',//所属银行0其他银行1中国银行2农商行（山东省）3农业银行4建设银行5工商银行
          payeeAccount:'',//收款账户
        }],
        projectForm:{
          projectId:'',
          projectName:'',
          projectContractor:'',
          projectAmount:'',
          projectBillNum:'',
          projectFundType:'',
          outId:'',
          ynType:'1',
        },
        contractionForm:{
          contractionId:'',
          name:'',
          code:'',
          totalAmount:'',
        },
        moneyOrderForm:{
          orderNum:'',
          orderType:'',
          orderAmount:'',
          billPayUnit:'',
          billReceiveUnit:'',
          startTime:'',
          endTime:'',
          orderStatus:'',
          remark:'',
        }
      }],
    },
    
    accountForm:{},
    fileForm:[],
    isUpdate:false,
    SJimage: [],
    FPimage: [],
    QTimage: [],
    imgcount:0,
    activeNames: 0,
    applyDate:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    //所属银行
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'bank_type', {method:'GET'}, {
      success: (res) => {
        this.setData({
          bankTypeOptions:res.data
        });
      }
    })
    // 资金支出类别字典查询
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'capital_expenditure_type', {method:'GET'}, {
      success: (res) => {
        that.setData({
          capitalExpenditureTypeOptions:res.data,
        })
      }
    })
    // 汇票列表查询 
    UTIL.httpRequest(API.URL_GET_GETMONEYORDERLIST, {method:'GET'}, {
      success: (res) => {
        that.setData({
          moneyOrderOptions:res.rows,
        })
      }
    })
    // 付款方式类型字典查询 （2.0）
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'yn_pay_type', {method:'GET'}, {
      success: (res) => {
        that.setData({
          transferTypeOptions:res.data,
        })
      }
    })
    // 项目工程列表 
    UTIL.httpRequest(API.URL_GET_GETPROJECTLIST , {method:'GET'}, {
      success: (res) => {
        that.setData({
          projectOptions:res.rows,
        })
      }
    })
    // 工程款类型字典查询 
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'project_fund_type', {method:'GET'}, {
      success: (res) => {
        that.setData({
          projectFundTypeOptions:res.data,
        })
      }
    })
    // 获取合同信息列表
    UTIL.httpRequest(API.URL_GET_CONTRACTIONLIST , {method:'GET',contractionStatus:1}, {
      success: (res) => {
        that.setData({
          contractionOptions:res.rows,
        })
      }
    })
    if(options.type == 'template'){
      wx.showLoading({
        title: '正在加载模板',
        mask:true
      })
      let list = JSON.parse(options.option);
      that.setData({
        templateModel:JSON.parse(options.option),
        formType:options.type,
      })
      var perames = {
        pageNum:1,
        pageSize:999,
        accountType:'102',
        method:'POST',
        params: {
          "townAccountType":"0"
        }
      }
      // 付款方列表
      UTIL.httpRequest(API.URL_GET_SELECTACCOUNTLIST , perames, {
        success: (res) => {
          that.setData({
            accountOptions:res.rows,
            ["form.transfers[0].applyDate"]: UTIL.formatDate(new Date()),
            applyDate: UTIL.formatDate(new Date()),
          })
        }
      })
      // if(options.type == "template"){list.approvalItemTemplate.id=""}
      console.log(list);
      if(options.type == "template"){list.applyData.approvalItemTemplate.id=""}
      setTimeout(function(){
        for (let i = 0; i < list.applyData.transfers.length; i++) {
          list.applyData.transfers[i].payeeList.forEach((item2,index2)=>{
            list.applyData.transfers[i].payeeList[index2].incomeAmount = parseFloat(0).toFixed(2);
          })

          console.log(that.data.capitalExpenditureTypeOptions);
          list.applyData.transfers[i].capitalExpenditureTypeText = UTIL.getTransform(list.applyData.transfers[i].capitalExpenditureType,that.data.capitalExpenditureTypeOptions);

          list.applyData.transfers[i].transferTypeText = UTIL.getTransform(list.applyData.transfers[i].paymentPattern,that.data.transferTypeOptions);
    
          list.applyData.transfers[i].bankTypeText = UTIL.getTransform(list.applyData.transfers[i].bankType,that.data.bankTypeOptions);
    
          list.applyData.transfers[i].num = UTIL.convertToChinaNum(i+1);

          list.applyData.transfers[i].expenditureAmount = '';

          list.applyData.transfers[i].fileNum = 0;

          list.applyData.transfers[i].cashierType = list.applyData.transfers[i].cashierId != '' && list.applyData.transfers[i].cashierId != null && list.applyData.transfers[i].cashierId != null ? 'edit':'add' ;

          
          
          list.applyData.transfers[i].cashForm=[{
            payee:'',
            phone:'',
            unit:'',
            leader:'',
            remark:'',
          }];

          if(list.applyData.transfers[i].capitalExpenditureType == 2){
            let prames = {
              outId:list.applyData.transfers[i].id,
              ynType: list.applyData.transfers[i].transferType=='1'||list.applyData.transfers[i].transferType=='2'||list.applyData.transfers[i].transferType=='4'?'1':'2'
            }
            // 工程项目查询
            UTIL.httpRequest(API.URL_GET_GETPROJECTTO , prames, {
              success: (res) => {
                res.data.projectFundTypeText = UTIL.getTransform(res.data.projectFundType,that.data.projectFundTypeOptions);
                list.applyData.transfers[i].projectForm = res.data
              }
            })
          }

          if(list.applyData.transfers[i].capitalExpenditureType == 4){
            let prames = {
              transferId:list.applyData.transfers[i].id,
              
            }
            // 关联合同查询
            UTIL.httpRequest(API.URL_GET_GETSELECTINFOBYOUTID , prames, {
              success: (res) => {
                list.applyData.transfers[i].contractionForm = res.data
                console.log(list.applyData.transfers[i]);
              }
            })
          }

          if(list.applyData.transfers[i].transferType == '12'){
            list.applyData.transfers[i].moneyOrderForm = {
              billPayUnit : '',
              orderNum : '',
              id : '',
              startTime : '',
              endTime : '',
              orderType : '',
              orderAmount:''
            };
              list.applyData.transfers[i].amountReadonly = true;
            // 关联收票方查询
            UTIL.httpRequest(API.URL_GET_GETCASHLISTCASGBYID+list.applyData.transfers[i].id , {method:'get'}, {
              success: (res) => {
                list.applyData.transfers[i].cashForm = res.data
              }
            })
            list.applyData.transfers[i].payer = "";
          }
          
          let fileForm = [];

          // UTIL.httpRequest(
          //   API.URL_GET_FINDLIST, 
          //   {
          //     method:'GET',
          //     tableName:'t_yinnong_transfer',
          //     tableId:list.applyData.transfers[i].id,
          //     fileType:1
          //   }, 
          //   {
          //   success: (res) => {
              
          //     let list2 = [];
          //     res.data.forEach((item2,index2)=>{
          //       wx.downloadFile({
          //         url: URL_PREFIX+item2.fileUrl, //仅为示例，并非真实的资源
          //         success (response) {
          //           if (response.statusCode === 200) {
          //             fileForm.push({
          //               file: response.tempFilePath,
          //               fileType:'1',
          //               bizPath:'transfer',
          //               tableName:'t_yinnong_transfer',
          //               tableId:''
          //             })
          //             console.log("--------------fileForm2 start----------------");
          //             console.log(fileForm);
          //             console.log("--------------fileForm2 end----------------");
          //             list2.push({
          //               tempFilePath:response.tempFilePath,
          //               id:item2.id
          //             })
          //             list.applyData.transfers[i].SJimage =  list2;
          //           }
          //         }
          //       })
          //     })
              
          //   }
          // })
          // //发票
          // UTIL.httpRequest(
          //   API.URL_GET_FINDLIST, 
          //   {
          //     method:'GET',
          //     tableName:'t_yinnong_transfer',
          //     tableId:list.applyData.transfers[i].id,
          //     fileType:2
          //   }, 
          //   {
          //   success: (res) => {
          //     let list2 = [];
          //     res.data.forEach((item2,index2)=>{
                
          //       wx.downloadFile({
          //         url: URL_PREFIX+item2.fileUrl, //仅为示例，并非真实的资源
          //         success (response) {
          //           if (response.statusCode === 200) {
          //             fileForm.push({
          //               file: response.tempFilePath,
          //               fileType:'2',
          //               bizPath:'transfer',
          //               tableName:'t_yinnong_transfer',
          //               tableId:''
          //             })
          //             console.log("--------------fileForm2 start----------------");
          //             console.log(fileForm);
          //             console.log("--------------fileForm2 end----------------");
          //             list2.push({
          //               tempFilePath:response.tempFilePath,
          //               id:item2.id
          //             })
          //             list.applyData.transfers[i].FPimage =  list2;
          //           }
          //         }
          //       })
          //     })
          //   }
          // })
          // //其他
          // UTIL.httpRequest(
          //   API.URL_GET_FINDLIST, 
          //   {
          //     method:'GET',
          //     tableName:'t_yinnong_transfer',
          //     tableId:list.applyData.transfers[i].id,
          //     fileType:3
          //   }, 
          //   {
          //   success: (res) => {
          //     let list2 = [];
          //     res.data.forEach((item2,index2)=>{
                
          //       wx.downloadFile({
          //         url: URL_PREFIX+item2.fileUrl, //仅为示例，并非真实的资源
          //         success (response) {
          //           if (response.statusCode === 200) {
          //             fileForm.push({
          //               file: response.tempFilePath,
          //               fileType:'3',
          //               bizPath:'transfer',
          //               tableName:'t_yinnong_transfer',
          //               tableId:''
          //             })
          //             console.log("--------------fileForm2 start----------------");
          //             console.log(fileForm);
          //             console.log("--------------fileForm2 end----------------");
          //             list2.push({
          //               tempFilePath:response.tempFilePath,
          //               id:item2.id
          //             })
          //             list.applyData.transfers[i].QTimage =  list2;
                      
          //           }
          //         }
          //       })
          //     })
          //   }
          // })
          list.applyData.transfers[i].id = "";
          list.applyData.transfers[i].fileForm = fileForm;
        }
      },1000)
      var timer2 = setTimeout(function(){
        that.setData({
          form:list.applyData,
          activeNames:null,
          applyDate: UTIL.formatDate(new Date()),
          ["form.approvalItemTemplate.totalAmount"]:parseFloat(0).toFixed(2),
        })
        UTIL.httpRequest(API.URL_GET_GETINFO, {method:'GET'}, {
          success: (res) => {
            if (res.code == API.SUCCESS_CODE) {
              that.setData({
                ["form.approvalItemTemplate.submitCompany"]:res.user.bookName,
                ["form.approvalItemTemplate.submitDate"]:UTIL.js_date_time(new Date()),
                ["form.approvalItemTemplate.submitter"]:res.user.nickName,
                ["form.approvalItemTemplate.telephone"]:res.user.phonenumber,
              })
    
            }
          }
        })
        wx.hideLoading();
      },3000)
    }else if(options.id && options.type != 'template'){
      UTIL.showLoadingHaveMask();
      setTimeout(function(){
        UTIL.httpRequest(API.URL_GET_APPROVALITEMS+options.id, {method:'GET'}, {
          success: (res) => {
            if (res.code == API.SUCCESS_CODE) {
              console.log(that.data.capitalExpenditureTypeOptions);
              if(res.data.approvalItemTemplate == null){return;}
              res.data.approvalItemTemplate.totalAmount = parseFloat(res.data.approvalItemTemplate.totalAmount).toFixed(2)
              res.data.transfers.forEach( (item,index) => {

                that.setData({
                  applyDate: res.data.transfers[0].applyDate,
                })

                res.data.transfers[index].capitalExpenditureTypeText = UTIL.getTransform(item.capitalExpenditureType,that.data.capitalExpenditureTypeOptions);

                console.log(item.paymentPattern);
                console.log(that.data.transferTypeOptions);

                res.data.transfers[index].cashierType = res.data.transfers[index].cashierId != '' && res.data.transfers[index].cashierId != null && res.data.transfers[index].cashierId != null ? 'edit':'add' ;

                res.data.transfers[index].transferTypeText = UTIL.getTransform(item.paymentPattern,that.data.transferTypeOptions);

                res.data.transfers[index].bankTypeText = UTIL.getTransform(item.bankType,that.data.bankTypeOptions);

                res.data.transfers[index].num = UTIL.convertToChinaNum(index+1);
                
                res.data.transfers[index].collapseDis = true;

                res.data.transfers[index].expenditureAmount = parseFloat(res.data.transfers[index].expenditureAmount).toFixed(2);

                res.data.transfers[index].moneyOrderForm = [];

                // res.data.transfers[index].expenditureAmount = parseFloat(0).toFixed(2);

                res.data.transfers[index].payeeList.forEach( (response,i) => {

                  res.data.transfers[index].payeeList[i].bankTypeText = UTIL.getTransform(response.bankType,that.data.bankTypeOptions);

                })
                res.data.transfers[index].showTitle = false;
                if(res.data.transfers[index].capitalExpenditureType == 2){
                  let prames = {
                    outId:res.data.transfers[index].id,
                    ynType: res.data.transfers[index].transferType=='1'||res.data.transfers[index].transferType=='2'||res.data.transfers[index].transferType=='4'?'1':'2'
                  }
                  // 工程项目查询
                  UTIL.httpRequest(API.URL_GET_GETPROJECTTO , prames, {
                    success: (res) => {
                      res.data.projectFundTypeText = UTIL.getTransform(res.data.projectFundType,that.data.projectFundTypeOptions);
                      that.setData({
                        ["form.transfers["+index+"].projectForm"]:res.data,
                      })
                    }
                  })
                }

                if(res.data.transfers[index].capitalExpenditureType == 4){
                  let prames = {
                    transferId:res.data.transfers[index].id,
                  }
                  // 关联合同查询
                  UTIL.httpRequest(API.URL_GET_GETSELECTINFOBYOUTID , prames, {
                    success: (res) => {
                      that.setData({
                        ["form.transfers["+index+"].contractionForm"]:res.data,
                      })
                    }
                  })
                }

                if(res.data.transfers[index].transferType == '12'){
                  var transferTimer = setTimeout(function(){
                    that.setData({
                      ["form.transfers["+index+"].moneyOrderForm"]:{
                        billPayUnit : res.data.transfers[index].payer,
                        orderNum : res.data.transfers[index].payerAccount,
                        id : res.data.transfers[index].cashierId,
                        startTime : res.data.transfers[index].startTime,
                        endTime : res.data.transfers[index].endTime,
                        orderType : res.data.transfers[index].orderType,
                        orderAmount:res.data.transfers[index].expenditureAmount
                      },
                      ["form.transfers["+index+"].amountReadonly"]:true
                    })
                  },1000)
                }
                UTIL.httpRequest(
                  API.URL_GET_FINDLIST, 
                  {
                    method:'GET',
                    tableName:'t_yinnong_transfer',
                    tableId:item.id,
                    fileType:1
                  }, 
                  {
                  success: (res) => {
                    
                    let list = [];
                    
                    res.data.forEach((item2,index2)=>{
                      
                      let fileForm = item.fileForm?item.fileForm:[];
                      fileForm.push({
                        file: URL_PREFIX+item2.fileUrl,
                        fileType:'1',
                        bizPath:'transfer',
                        tableName:'t_yinnong_transfer',
                        tableId:''
                      })
                      list.push({
                        tempFilePath:URL_PREFIX+item2.fileUrl,
                        id:item2.id
                      })
                      that.setData({
                        ["form.transfers["+index+"].SJimage"]:list,
                        ["form.transfers["+index+"].fileForm"]:fileForm
                      });

                    })
                    
                  }
                })
                //发票
                UTIL.httpRequest(
                  API.URL_GET_FINDLIST, 
                  {
                    method:'GET',
                    tableName:'t_yinnong_transfer',
                    tableId:item.id,
                    fileType:2
                  }, 
                  {
                  success: (res) => {
                    let list = [];
                    res.data.forEach((item2,index2)=>{
                      let fileForm = item.fileForm?item.fileForm:[];
                      fileForm.push({
                        file: URL_PREFIX+item2.fileUrl,
                        fileType:'2',
                        bizPath:'transfer',
                        tableName:'t_yinnong_transfer',
                        tableId:item.id
                      })
                      list.push({
                        tempFilePath:URL_PREFIX+item2.fileUrl,
                        id:item2.id
                      })
                      that.setData({
                        ["form.transfers["+index+"].FPimage"]:list,
                        ["form.transfers["+index+"].fileForm"]:fileForm
                      });
                    })
                  }
                })
                //其他
                UTIL.httpRequest(
                  API.URL_GET_FINDLIST, 
                  {
                    method:'GET',
                    tableName:'t_yinnong_transfer',
                    tableId:item.id,
                    fileType:3
                  }, 
                  {
                  success: (res) => {
                    let list = [];
                    res.data.forEach((item2,index2)=>{
                      let fileForm = item.fileForm?item.fileForm:[];
                      fileForm.push({
                        file: URL_PREFIX+item2.fileUrl,
                        fileType:'3',
                        bizPath:'transfer',
                        tableName:'t_yinnong_transfer',
                        tableId:item.id
                      })
                      list.push({
                        tempFilePath:URL_PREFIX+item2.fileUrl,
                        id:item2.id
                      })
                      that.setData({
                        ["form.transfers["+index+"].QTimage"]:list,
                        ["form.transfers["+index+"].fileForm"]:fileForm
                      });
                    })
                  }
                })
              })
                that.setData({
                  form:res.data,
                  activeNames:null
                })
                UTIL.httpRequest(API.URL_GET_GETINFO, {method:'GET'}, {
                  success: (res) => {
                    if (res.code == API.SUCCESS_CODE) {
                      that.setData({
                        ["form.approvalItemTemplate.submitCompany"]:res.user.bookName,
                        ["form.approvalItemTemplate.submitDate"]:UTIL.js_date_time(new Date()),
                        ["form.approvalItemTemplate.submitter"]:res.user.nickName,
                        ["form.approvalItemTemplate.telephone"]:res.user.phonenumber,
                      })
            
                    }
                  }
                })
                UTIL.hideLoadingHaveMask();
              
            }
          }
        })
      },1000)
    }else{
      //村账户查询参数
      var perames = {
          pageNum:1,
          pageSize:999,
          accountType:'102',
          method:'post',
          params: {
            "townAccountType":"0"
          }
        }
        // 付款方列表
        UTIL.httpRequest(API.URL_GET_SELECTACCOUNTLIST , perames, {
          success: (res) => {
            that.setData({
              accountOptions:res.rows,
              ["form.transfers[0].applyDate"]: UTIL.formatDate(new Date()),
              applyDate: UTIL.formatDate(new Date()),
            })
          }
        })
        UTIL.httpRequest(API.URL_GET_GETINFO, {method:'GET'}, {
          success: (res) => {
            if (res.code == API.SUCCESS_CODE) {
              that.setData({
                ["form.approvalItemTemplate.submitCompany"]:res.user.bookName,
                ["form.approvalItemTemplate.submitDate"]:UTIL.js_date_time(new Date()),
                ["form.approvalItemTemplate.submitter"]:res.user.nickName,
                ["form.approvalItemTemplate.telephone"]:res.user.phonenumber,
              })
    
            }
          }
        })
    }
    
  },
  onChangeBox(event) {
    console.log(event);
    this.setData({
      activeNames: event.detail,
    });
  },
  onChangePayee(event) {
    console.log(event);
    this.setData({
      ["form.transfers["+event.currentTarget.dataset.index+"].activeName"]:event.detail
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },
  openBox(even){
    console.log(even.currentTarget.dataset.name);
    this.setData({
      [even.currentTarget.dataset.name]:true
    })
  },
  closeBox(even){
    console.log(even.currentTarget.dataset.name);
    this.setData({
      [even.currentTarget.dataset.name]:false
    })
  },
  onConfirm(event) {
    this.setData({
      [event.currentTarget.dataset.name]: false,
      [event.currentTarget.dataset.value]: UTIL.formatDate(event.detail),
    });
  },
  onConfirmPick(event) {
    console.log(event);
    this.setData({
      [event.currentTarget.dataset.name]: false,
      [event.currentTarget.dataset.value]: event.detail.value.dictValue,
      [event.currentTarget.dataset.value+'Text']: event.detail.value.dictLabel,
    });
  },
  onConfirmAccount(event) {
    console.log(event);
    var that = this;
    // 所属银行字典查询 
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'bank_type', {method:'GET'}, {
      success: (res) => {
        this.setData({
          [event.currentTarget.dataset.name]: false,
          [event.currentTarget.dataset.value+'.payer']: event.detail.value.accountName,
          [event.currentTarget.dataset.value+'.cashierId']: event.detail.value.id,
          [event.currentTarget.dataset.value+'.payerAccount']: event.detail.value.bankAccountNumber,
          [event.currentTarget.dataset.value+'.bankTypeText']: UTIL.getTransform(event.detail.value.bankType,that.data.bankTypeOptions),
          [event.currentTarget.dataset.value+'.bankType']: event.detail.value.bankType,
          [event.currentTarget.dataset.value+'.payerAccount']:event.detail.value.balance,
        });
      }
    })
  },
  onConfirmaTransfer(event) {
    console.log(event);
    var that = this;
    let perames = {};
    this.setData({
      [event.currentTarget.dataset.value+'.payer']: '',
      [event.currentTarget.dataset.value+'.payerAccount']: '',
      [event.currentTarget.dataset.value+'.bankTypeText']: '',
      [event.currentTarget.dataset.value+'.bankType']: '',
      [event.currentTarget.dataset.value+'.bankAccountType']: '2',  
      [event.currentTarget.dataset.value+'.isPeers']: '',  
      [event.currentTarget.dataset.value+'.paymentPattern']: event.detail.value.dictValue,  
      [event.currentTarget.dataset.value+'.amountReadonly']:false,
      [event.currentTarget.dataset.value+'.payeeList']:[{//收款方账户集合
        payeeId:'0',//收款方id
        payee:'',//收款方
        bankDeposit:'',//开户行
        incomeAmount:'',//收入金额
        bankType:'',//所属银行0其他银行1中国银行2农商行（山东省）3农业银行4建设银行5工商银行
        payeeAccount:'',//收款账户
      }],
      balance:0,
    });
    console.log(event.detail.value.dictValue);

    if(event.detail.value.dictValue == 1 || event.detail.value.dictValue == 2 || event.detail.value.dictValue == 4 || event.detail.value.dictValue == 6 || event.detail.value.dictValue == 7 ){event.detail.value.dictValue = 1 ;}
    else if(event.detail.value.dictValue == 3){event.detail.value.dictValue = 2 ;}
    else if(event.detail.value.dictValue == 5){event.detail.value.dictValue = 12 ;}
    else if(event.detail.value.dictValue == 8){event.detail.value.dictValue = 11 ;}

    if(event.detail.value.dictValue == 1){//村账户查询参数
      perames = {
        pageNum:1,
        pageSize:999,
        accountType:'102',
        method:'post',
        params: {
          "townAccountType":"0"
        }
      }
      // 付款方列表
      UTIL.httpRequest(API.URL_GET_SELECTACCOUNTLIST , perames, {
        success: (res) => {
          that.setData({
            accountOptions:res.rows,
          })
        }
      })
    }
    if(event.detail.value.dictValue == 2 || event.detail.value.dictValue == 10){//公务卡和现金提现查询参数
      perames = {
        pageNum:1,
        pageSize:999,
        accountType:'102',
        method:'GET',
        villageAccountType:''
      }
      // 付款方列表
      UTIL.httpRequest(API.URL_GET_ACCOUNTLIST , perames, {
        success: (res) => {
          that.setData({
            accountOptions:res.rows,
          })
        }
      })
    }
    if(event.detail.value.dictValue == 11){//现金使用查询参数
      perames = {
        pageNum:1,
        pageSize:999,
        accountType:'101',
        method:'GET'
      }
      // 付款方列表
      UTIL.httpRequest(API.URL_GET_ACCOUNTLIST , perames, {
        success: (res) => {
          that.setData({
            accountOptions:res.rows
          })
        }
      })
    }
    if(event.detail.value.dictValue == 4){//代管账户查询参数
      perames = {
        pageNum:1,
        pageSize:999,
        accountType:'102',
        method:'GET',
        villageAccountType:'1'
      }
      // 付款方列表
      UTIL.httpRequest(API.URL_GET_ACCOUNTLIST , perames, {
        success: (res) => {
          that.setData({
            accountOptions:res.rows,
          })
        }
      })
    }
    if(event.detail.value.dictValue == 12){//汇票支出查询参数
      perames = {
        pageNum:1,
        pageSize:999,
      }
      // 付款方列表
      UTIL.httpRequest(API.URL_GET_MONEYORDERLIST , perames, {
        success: (res) => {
          that.setData({
            moneyorderOptions:res.rows,
            [event.currentTarget.dataset.value+'.amountReadonly']:true
          })
        }
      })
    }
    this.setData({
      [event.currentTarget.dataset.name]: false,
      [event.currentTarget.dataset.value+'.transferType']: event.detail.value.dictValue,
      [event.currentTarget.dataset.value+'.transferTypeText']: event.detail.value.dictLabel,
    });
  },
  onConfirmProject(event) {
    console.log(event);
    this.setData({
      [event.currentTarget.dataset.name]: false,
      [event.currentTarget.dataset.value+'.projectName']: event.detail.value.projectName,
      [event.currentTarget.dataset.value+'.projectId']: event.detail.value.id,
      [event.currentTarget.dataset.value+'.projectContractor']: event.detail.value.projectContractor,
      [event.currentTarget.dataset.value+'.projectAmount']: event.detail.value.projectAmount,
    });
  },
  onConfirmContraction(event) {
    console.log(event);
    this.setData({
      [event.currentTarget.dataset.name]: false,
      [event.currentTarget.dataset.value+".name"]: event.detail.value.name,
      [event.currentTarget.dataset.value+'.code']: event.detail.value.code,
      [event.currentTarget.dataset.value+'.totalAmount']: event.detail.value.totalAmount,
      [event.currentTarget.dataset.value+'.contractionId']: event.detail.value.id,
    });
  },
  onConfirmMoneyOrder(event) {
    console.log(event);
    var that = this ;
    this.setData({
      [event.currentTarget.dataset.name]: false,
      [event.currentTarget.dataset.value+'.moneyOrderForm']: event.detail.value,
      [event.currentTarget.dataset.value+'.expenditureAmount']: event.detail.value.orderAmount,
      [event.currentTarget.dataset.value+".payeeList[0].incomeAmount"]: event.detail.value.orderAmount,
      [event.currentTarget.dataset.value+'.payer']:event.detail.value.billPayUnit,
      [event.currentTarget.dataset.value+'.payerAccount'] : event.detail.value.orderNum,
      [event.currentTarget.dataset.value+'.cashierId'] : event.detail.value.id,
      [event.currentTarget.dataset.value+'.startTime'] : event.detail.value.startTime,
      [event.currentTarget.dataset.value+'.endTime'] : event.detail.value.endTime,
      [event.currentTarget.dataset.value+'.orderType'] : event.detail.value.orderType
    });
    
    var moneyCount = 0 ;
    for (let i = 0; i < that.data.form.transfers.length; i++) {
      const element = that.data.form.transfers[i];
      for (let j = 0; j < element.payeeList.length; j++) {
        const element2 = element.payeeList[j];
        var allCount = 0 ;
        moneyCount = parseFloat(moneyCount)+parseFloat(element2.incomeAmount);
        // allCount = parseFloat(allCount)+parseFloat(element2.incomeAmount);
        // this.setData({
        //   ["form.transfers["+i+"].expenditureAmount"]:allCount,
        // })
      }
    }
    console.log(moneyCount.toFixed(2));
    this.setData({
       ["form.approvalItemTemplate.totalAmount"]:moneyCount.toFixed(2),
    })
  },
  goPayeeList(event){
    console.log(event.currentTarget.dataset.transfertype)
    if(event.currentTarget.dataset.payer == null || event.currentTarget.dataset.payer == ''){
      UTIL.showToastNoneIcon('请先选择付款方！');
      return;
    }
    if(this.data.form.transfers[event.currentTarget.dataset.index].payeeList.length>1){
      return;
    }
    if(event.currentTarget.dataset.accounttype == null ){
      event.currentTarget.dataset.accounttype = ''
    }
    // '/pages/payee/index?isPeers='+event.currentTarget.dataset.ispeers+'&bankType='+event.currentTarget.dataset.banktype+'&accountType='+event.currentTarget.dataset.accounttype+'&transferType='+event.currentTarget.dataset.transfertype + '&index='+event.currentTarget.dataset.index+'&money='+this.data.form.transfers
    wx.navigateTo({
      url: '/pages/payee/index?transferType='+event.currentTarget.dataset.transfertype+'&money='+this.data.form.transfers[event.currentTarget.dataset.index].expenditureAmount + '&index='+event.currentTarget.dataset.index,
    })
  },
  goPayee(event){
    wx.navigateTo({
      url: 'payeeList/payee?options='+JSON.stringify(event.currentTarget.dataset.option)
    })
  },
  onChange(event){
    console.log(event);
    this.setData({
      [event.currentTarget.dataset.value]: event.detail,
    })
  },
  onChangeTime(event){
    console.log(event);
    this.setData({
      applyDate: event.detail,
    })
  },
  onConfirmTime(event){
    this.setData({
      [event.currentTarget.dataset.name]: false,
      applyDate: UTIL.formatDate(event.detail),
    });
    for (let i = 0; i < this.data.form.transfers.length; i++) {
      this.setData({
        ["form.transfers["+i+"].applyDate"]:UTIL.formatDate(event.detail),
      })
    }
  },
  onChangeMoneyOut(event){
    console.log(event);
    var that = this;
    if( !(event.detail.value > -1)){ 
      this.setData({
        ["form.transfers["+event.currentTarget.dataset.index+"].expenditureAmount"]:'',
      })
      return;
    }

    if( event.detail.value.indexOf('.')>0 && event.detail.value.toString().split(".")[1].length>2){
      this.setData({
        ["form.transfers["+event.currentTarget.dataset.index+"].expenditureAmount"]:event.detail.value.toString().split(".")[0] + '.' + event.detail.value.toString().split(".")[1].substr(0,2),
      })
      return;
    }

    this.setData({
      // ["form.transfers["+event.currentTarget.dataset.index+"].payeeList["+event.currentTarget.dataset.childrenindex+"].incomeAmount"]: event.detail,
      ["form.transfers["+event.currentTarget.dataset.index+"].payeeList[0].incomeAmount"]: event.detail.value,
      ["form.transfers["+event.currentTarget.dataset.index+"].expenditureAmount"]:event.detail.value,
      // ["form.transfers["+event.currentTarget.dataset.index+"].expenditureAmount"]:event.detail,
    })
    if(event.detail.value == ''){
      that.data.form.transfers[event.currentTarget.dataset.index].payeeList[0].incomeAmount = parseFloat(0).toFixed(2);
      that.data.form.transfers[event.currentTarget.dataset.index].expenditureAmount = parseFloat(0).toFixed(2);
    }
    var moneyCount = 0 ;
    for (let i = 0; i < that.data.form.transfers.length; i++) {
      
      const element = that.data.form.transfers[i];
      for (let j = 0; j < element.payeeList.length; j++) {
        const element2 = element.payeeList[j];
        console.log(element2.incomeAmount);
        var allCount = 0 ;
        moneyCount = parseFloat(moneyCount) + parseFloat(element2.incomeAmount);
        
        // allCount = parseFloat(allCount)+parseFloat(element2.incomeAmount);
        // this.setData({
        //   ["form.transfers["+i+"].expenditureAmount"]:allCount,
        // })
      }
    }

    this.setData({
       ["form.approvalItemTemplate.totalAmount"]:moneyCount.toFixed(2),
    })
  },
  onChangeMoney(event){
    console.log(event);
    var that = this;
    if( !(event.detail > -1)){ 
      this.setData({
        ["form.transfers["+event.currentTarget.dataset.index+"].expenditureAmount"]:'',
      })
      return;
    }

    if( event.detail.indexOf('.')>0 && event.detail.toString().split(".")[1].length>2){
      this.setData({
        ["form.transfers["+event.currentTarget.dataset.index+"].expenditureAmount"]:event.detail.toString().split(".")[0] + '.' + event.detail.toString().split(".")[1].substr(0,2),
      })
      return;
    }
    this.setData({
      // ["form.transfers["+event.currentTarget.dataset.index+"].payeeList["+event.currentTarget.dataset.childrenindex+"].incomeAmount"]: event.detail,
      ["form.transfers["+event.currentTarget.dataset.index+"].payeeList[0].incomeAmount"]: event.detail,
      ["form.transfers["+event.currentTarget.dataset.index+"].expenditureAmount"]:event.detail,
      // ["form.transfers["+event.currentTarget.dataset.index+"].expenditureAmount"]:event.detail,
    })
    console.log(that.data.form);
    var moneyCount = 0 ;
    for (let i = 0; i < that.data.form.transfers.length; i++) {
      const element = that.data.form.transfers[i];
      for (let j = 0; j < element.payeeList.length; j++) {
        const element2 = element.payeeList[j];
        var allCount = 0 ;
        moneyCount = parseFloat(moneyCount)+parseFloat(element2.incomeAmount);
        // allCount = parseFloat(allCount)+parseFloat(element2.incomeAmount);
        // this.setData({
        //   ["form.transfers["+i+"].expenditureAmount"]:allCount,
        // })
      }
    }
    console.log(moneyCount.toFixed(2));
    this.setData({
       ["form.approvalItemTemplate.totalAmount"]:moneyCount.toFixed(2),
    })
    console.log(that.data.form);
    console.log(allCount.toFixed(2)); 
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  goSubmitMB(){
    this.setData({
      showDialog:true
    })
  },
  onClose(){
    this.setData({
      showDialog:false
    })
  },
  bindNameInput(even){
    this.setData({
      ["form.approvalItemTemplate.templateName"]:even.detail.value
    })
  },
  goSubmit(e){
    var that = this;
    console.log(that.data.form);
    var list = that.data.form,
    approvalItems = list.approvalItemTemplate.approvalItems;
    if(approvalItems == ''){
      UTIL.showToastNoneIcon('请填写审批事项名称！');
      that.setData({
        topInputTirme:true
      })
      return;
    }
    for (let i = 0; i < list.transfers.length; i++) {
      const element = list.transfers[i];
      if(element.applyDate == ''){
        UTIL.showToastNoneIcon('请选择事项'+UTIL.convertToChinaNum(i+1)+'的申请时间！');
        return;
      }
      if(element.remark == ''){

        UTIL.showToastNoneIcon('请填写事项'+UTIL.convertToChinaNum(i+1)+'的支出原因！');
        that.setData({
          ["form.transfers["+i+"].remarkTirme"]:true
        })
        return;
      }
      if(element.expenditureAmount == ''){
        UTIL.showToastNoneIcon('请填写事项'+UTIL.convertToChinaNum(i+1)+'的支出金额！');
        that.setData({
          ["form.transfers["+i+"].expenditureAmountTirme"]:true
        })
        return;
      }
      console.log(parseFloat(element.expenditureAmount).toFixed(2))
      console.log(parseFloat(element.payerAccount).toFixed(2))
      console.log(element.transferType);
      if((parseFloat(element.expenditureAmount).toFixed(2) - parseFloat(element.payerAccount).toFixed(2) >0) && element.transferType == 11){
        UTIL.showToastNoneIcon('事项'+UTIL.convertToChinaNum(i+1)+'的支出金额不能超过付款账户余额！');
        return;
      }
      if(element.payer == ''&&element.transferType != 12){
        UTIL.showToastNoneIcon('请选择事项'+UTIL.convertToChinaNum(i+1)+'的付款方！');
        return;
      }
      if(element.payeeList[0].payee == ''&&element.transferType!=12){
        UTIL.showToastNoneIcon('请选择事项'+UTIL.convertToChinaNum(i+1)+'的收款方！');
        return;
      }
      if((element.payeeList[0].incomeAmount == '' || element.payeeList[0].incomeAmount == undefined)&&element.transferType!=12){
        UTIL.showToastNoneIcon('请填写事项'+UTIL.convertToChinaNum(i+1)+'收款方的收入金额！');
        return;
      }

      if(element.transferType == '12'){
        list.transfers[i].payer = list.transfers[i].moneyOrderForm.billPayUnit;
        list.transfers[i].payerAccount = list.transfers[i].moneyOrderForm.orderNum;
        list.transfers[i].cashierId = list.transfers[i].moneyOrderForm.id;
        list.transfers[i].startTime = list.transfers[i].moneyOrderForm.startTime;
        list.transfers[i].endTime = list.transfers[i].moneyOrderForm.endTime;
        list.transfers[i].orderType = list.transfers[i].moneyOrderForm.orderType;
      }

    }
    if(e.currentTarget.dataset.type == 1){
      if(that.data.form.approvalItemTemplate.templateName == ''){
        UTIL.showToastNoneIcon('请输入模板名称！');
        return;
      }
    }
    if(e.currentTarget.dataset.type == 3){
      for (let i = 0; i < that.data.form.transfers.length; i++) {
       that.data.form.transfers[i].approvalMode = '2';
      }
       that.data.form.approvalItemTemplate.dataType = e.currentTarget.dataset.type
    }
    that.data.form.method = 'POST';
    that.data.form.approvalItemTemplate.dataType = e.currentTarget.dataset.type;

    console.log(that.data.form);
    UTIL.httpRequest(API.URL_GET_SAVE, that.data.form, {
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          for (let j = 0; j < res.data.transfers.length; j++) {
            if(that.data.form.transfers[j].capitalExpenditureType == 2){
              that.data.form.transfers[j].projectForm.ynType = res.data.transfers[j].transferType=='1'||res.data.transfers[j].transferType=='2'||res.data.transfers[j].transferType=='4'?'1':'2';
              that.data.form.transfers[j].projectForm.outId = res.data.transfers[j].id;
              that.data.form.transfers[j].projectForm.method = 'POST';
              // 工程项目提交
              UTIL.httpRequest(API.URL_GET_ADDPROJECTTO , that.data.form.transfers[j].projectForm, {
                success: (res) => {
                  
                }
              })
            }
            if(that.data.form.transfers[j].capitalExpenditureType == 4){
              
              that.data.form.transfers[j].contractionForm.transferId = res.data.transfers[j].id;
              that.data.form.transfers[j].contractionForm.id = '';
              that.data.form.transfers[j].contractionForm.method = 'POST';

              // 关联合同提交
              UTIL.httpRequest(API.URL_GET_GETRELATIONADD , that.data.form.transfers[j].contractionForm, {
                success: (res) => {
                  
                }
              })
            }

            // if(that.data.form.transfers[j].transferType == '12'){
              
            //   console.log(that.data.form.transfers[j].cashForm);
            //   that.data.form.transfers[j].cashForm.cashId = res.data.transfers[j].id;
            //   that.data.form.transfers[j].cashForm.method = 'POST';
            //   if(that.data.form.transfers[j].cashierType == 'edit'){
            //     // 收票方信息增加
            //     UTIL.httpRequest(API.URL_GET_GETCASHDETAILEDIT , that.data.form.transfers[j].cashForm, {
            //       success: (res) => {
                    
            //       }
            //     })
            //   }else{
            //     // 收票方信息修改
            //     UTIL.httpRequest(API.URL_GET_GETCASHDETAILADD , that.data.form.transfers[j].cashForm, {
            //       success: (res) => {
                    
            //       }
            //     })
            //   }
            // }
            
            if(that.data.form.transfers[j].fileForm == undefined){continue;}
            console.log(that.data.form.transfers[j].fileForm);
            for (let i = 0; i < that.data.form.transfers[j].fileForm.length; i++) {
              that.data.form.transfers[j].fileForm[i].tableId = res.data.transfers[j].id
              const element = that.data.form.transfers[j].fileForm[i];
              wx.uploadFile({
                url: API.URL_GET_UPLOAD,
                filePath: element.file,
                name: 'file',
                header: {
                  "Content-Type": "multipart/form-data",//记得设置
                  "chartset":"utf-8",
                  'Authorization':'Bearer '+getApp().globalData.userInfo.token
                },
                formData:element,
                success (response){
                  console.log(res);
                },
                fail(res){
                  console.log(res)
                }
              })
            }
          }
          if(e.currentTarget.dataset.type == 0){
            wx.navigateTo({
              url: '/pages/apply/approval/approval?id='+res.data.approvalItemTemplate.id+'&deptId='+res.data.approvalItemTemplate.deptId+'&form='+JSON.stringify(res.data)+'&type='+that.data.formType+'&applyOptions='+JSON.stringify(that.data.templateModel),
            })
          }
          if(e.currentTarget.dataset.type == 2){
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000,
            })
          }
          if(e.currentTarget.dataset.type == 1){
            console.log("aaa");
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000,
              complete(){
                setTimeout(function(){
                  that.back();
                },2000)
              }
            })
          }
          if(e.currentTarget.dataset.type == 3){
            UTIL.httpRequest(API.URL_GET_TOREVIEWSUBMIT+res.data.approvalItemTemplate.id , {method:'POST'}, {
              success: (res2) => {
                if (res2.code == API.SUCCESS_CODE) {
                  wx.showToast({
                    title: '操作成功',
                    icon: 'success',
                    duration: 2000,
                    complete(){
                      setTimeout(function(){
                        that.back();
                      },2000)
                    }
                  })
                }else{
                  wx.showToast({
                    title: '操作失败',
                    icon: 'error',
                    duration: 2000
                  })
                }
              }
            })
            
          }
        }
      }
    })
  },
  bindKeyInput(even){
    console.log(even);
    this.setData({
      ["form.approvalItemTemplate.approvalItems"]: even.detail,
    })
  },
  errorPd(e){
    console.log(e);
    this.setData({
      [e.currentTarget.dataset.formname+"Tirme"]:e.detail.value == '' ? true:false
    })
  },
  errorJE(e){
    console.log(e);
    this.setData({
      [e.currentTarget.dataset.formname+"Tirme"]:e.detail.value == '' ? true:false
    })
  },
  errorYY(e){
    console.log(e);
    this.setData({
      [e.currentTarget.dataset.formname+"Tirme"]:e.detail.value == '' ? true:false
    })
  },
  SJtakephoto(e){
    var that = this;
    let fileForm = that.data.form.transfers[e.currentTarget.dataset.index].fileForm?that.data.form.transfers[e.currentTarget.dataset.index].fileForm:[];
    wx.chooseMedia({
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success(res) {
        console.log(res);
        res.tempFiles.forEach(item => {
          fileForm.push({
            file: item.tempFilePath,
            fileType:'1',
            bizPath:'transfer',
            tableName:'t_yinnong_transfer',
            tableId:''
          })
        })
        console.log(fileForm);
        let tem = that.data.form.transfers[e.currentTarget.dataset.index].SJimage?that.data.form.transfers[e.currentTarget.dataset.index].SJimage:[];
        res.tempFiles.forEach(r=>{
          tem.push({
            tempFilePath:r.tempFilePath
          })
        })
        console.log(tem);
        that.setData({
          ["form.transfers["+e.currentTarget.dataset.index+"].SJimage"]:tem,
          ["form.transfers["+e.currentTarget.dataset.index+"].fileForm"]:fileForm,
        })
        let SJlength = that.data.form.transfers[e.currentTarget.dataset.index].SJimage == undefined ? 0:that.data.form.transfers[e.currentTarget.dataset.index].SJimage.length;
        let FPlength = that.data.form.transfers[e.currentTarget.dataset.index].FPimage == undefined ? 0:that.data.form.transfers[e.currentTarget.dataset.index].FPimage.length;
        let QTlength = that.data.form.transfers[e.currentTarget.dataset.index].QTimage == undefined ? 0:that.data.form.transfers[e.currentTarget.dataset.index].QTimage.length;
        let fileNum = parseInt( SJlength ) + parseInt( FPlength ) + parseInt( QTlength ) ;
        that.setData({
          ["form.transfers["+e.currentTarget.dataset.index+"].fileNum"]:fileNum,
        })
      },fail(err){
        console.log(err);
      }
    })
  },
  FPtakephoto(e){
    var that = this;
    let fileForm = that.data.form.transfers[e.currentTarget.dataset.index].fileForm?that.data.form.transfers[e.currentTarget.dataset.index].fileForm:[];
    console.log(fileForm);
    wx.chooseMedia({
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success(res) {
        console.log(res);
        res.tempFiles.forEach(item => {
          fileForm.push({
            file: item.tempFilePath,
            fileType:'2',
            bizPath:'transfer',
            tableName:'t_yinnong_transfer',
            tableId:''
          })
        })

        let tem = that.data.form.transfers[e.currentTarget.dataset.index].FPimage?that.data.form.transfers[e.currentTarget.dataset.index].FPimage:[];

        res.tempFiles.forEach(r=>{
          tem.push({
            tempFilePath:r.tempFilePath
          })
        })
        
        console.log(tem);
        that.setData({
          ["form.transfers["+e.currentTarget.dataset.index+"].FPimage"]:tem,
          ["form.transfers["+e.currentTarget.dataset.index+"].fileForm"]:fileForm
        })
        let SJlength = that.data.form.transfers[e.currentTarget.dataset.index].SJimage == undefined ? 0:that.data.form.transfers[e.currentTarget.dataset.index].SJimage.length;
        let FPlength = that.data.form.transfers[e.currentTarget.dataset.index].FPimage == undefined ? 0:that.data.form.transfers[e.currentTarget.dataset.index].FPimage.length;
        let QTlength = that.data.form.transfers[e.currentTarget.dataset.index].QTimage == undefined ? 0:that.data.form.transfers[e.currentTarget.dataset.index].QTimage.length;
        let fileNum = parseInt( SJlength ) + parseInt( FPlength ) + parseInt( QTlength ) ;
        that.setData({
          ["form.transfers["+e.currentTarget.dataset.index+"].fileNum"]:fileNum,
        })
      },fail(err){
        console.log(err);
      }
    })
  },
  QTtakephoto(e){
    var that = this;
    let fileForm = that.data.form.transfers[e.currentTarget.dataset.index].fileForm?that.data.form.transfers[e.currentTarget.dataset.index].fileForm:[];
    wx.chooseMedia({
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success(res) {
        console.log(res);
        res.tempFiles.forEach(item => {
          fileForm.push({
            file: item.tempFilePath,
            fileType:'3',
            bizPath:'transfer',
            tableName:'t_yinnong_transfer',
            tableId:''
          })
        })
        console.log(fileForm);
        let tem = that.data.form.transfers[e.currentTarget.dataset.index].QTimage?that.data.form.transfers[e.currentTarget.dataset.index].QTimage:[];

        res.tempFiles.forEach(r=>{
          tem.push({
            tempFilePath:r.tempFilePath
          })
        })
        that.setData({
          ["form.transfers["+e.currentTarget.dataset.index+"].QTimage"]:tem,
          ["form.transfers["+e.currentTarget.dataset.index+"].fileForm"]:fileForm
        })
        let SJlength = that.data.form.transfers[e.currentTarget.dataset.index].SJimage == undefined ? 0:that.data.form.transfers[e.currentTarget.dataset.index].SJimage.length;
        let FPlength = that.data.form.transfers[e.currentTarget.dataset.index].FPimage == undefined ? 0:that.data.form.transfers[e.currentTarget.dataset.index].FPimage.length;
        let QTlength = that.data.form.transfers[e.currentTarget.dataset.index].QTimage == undefined ? 0:that.data.form.transfers[e.currentTarget.dataset.index].QTimage.length;
        let fileNum = parseInt( SJlength ) + parseInt( FPlength ) + parseInt( QTlength ) ;
        that.setData({
          ["form.transfers["+e.currentTarget.dataset.index+"].fileNum"]:fileNum,
        })
      },fail(err){
        console.log(err);
      }
    })
  },
  addList(){
    var that = this;
    let transList = this.data.form.transfers;
    console.log(this.data.form);
    for (let i = 0; i < transList.length; i++) {
      const element = transList[i];
      if(element.applyDate == '' || element.remark == '' || element.expenditureAmount == '' || element.payer == '' || element.payeeList[0].payee == '' || element.payeeList[0].incomeAmount == '' || element.payeeList[0].incomeAmount == undefined){
        UTIL.showToastNoneIcon('事项'+UTIL.convertToChinaNum(i+1)+'的信息填写不完整，检查后重试！');
        return;
      }
    }
    transList.push({
      num:UTIL.convertToChinaNum(transList.length+1),
      expenditureAmountTirme:false,
      remarkTirme:false,
      showCapitalExpenditureType:false,
      showApplyDate:false,
      showTransferType:false,
      showProject:false,
      showProjectFundType:false,
      showAccount:false,
      showDialog:false,
      showContraction:false,
      SJimage:[],
      FPimage:[],
      QTimage:[],
      activeName:0,
      cashForm:{
        payee:'',
        phone:'',
        unit:'',
        leader:'',
        remark:'',
      },
      showTitle:true,
      capitalExpenditureType:'1',//资金支出类别
      capitalExpenditureTypeText:'结算类',//资金支出类别（展示用）
      succeedAmount:'',//成功支付金额
      payer:'',//付款方
      payerAccount:'',//付款方账户
      bankType:'',//所属银行
      bankTypeText:'',//所属银行（展示用）
      isPeers:'N',//是否同行
      operatorCode:'',//操作员代码
      enterpriseCode:'',//企业编码
      expenditureAmount:'',//支出总金额
      applyDate:that.data.applyDate,//申请时间
      transferStatus:'',//转账状态
      auditStatus:'0',//审批状态
      paymentState:'',//支付状态
      approvalMode:'1',//审批模式
      paymentTime:'',//支付时间
      bankPriority:'',//银行处理优先级
      clientPriority:'',//客户处理优先级
      paymentPattern:'1',
      transferType:'1',//付款方式
      transferTypeText:'垫付报销：电子支付',//付款方式（展示用）
      requiredTransferTime:'',//要求转账时间
      remark:'',//付款事由
      startTime:'',//开票日期
      endTime:'',//到期日期
      orderType:'',//汇票类型
      bankAccountType:'2',//账户类别1 公户2私户
      villageAccountType:'',//账户分类
      payeeList:[{//收款方账户集合
        payeeId:'0',//收款方id
        payee:'',//收款方
        bankDeposit:'',//开户行
        incomeAmount:'0.00',//收入金额
        bankType:'',//所属银行0其他银行1中国银行2农商行（山东省）3农业银行4建设银行5工商银行
        payeeAccount:'',//收款账户
      }],
      projectForm:{
        projectId:'',
        projectName:'',
        projectContractor:'',
        projectAmount:'',
        projectBillNum:'',
        projectFundType:'',
        outId:'',
        ynType:'1',
      },
      contractionForm:{
        contractionId:'',
        name:'',
        code:'',
        totalAmount:'',
      },
    });
    //村账户查询参数
    var perames = {
      pageNum:1,
      pageSize:999,
      accountType:'102',
      method:'post',
      params: {
          "townAccountType":"0"
      }
    }
    // 付款方列表
    UTIL.httpRequest(API.URL_GET_SELECTACCOUNTLIST , perames, {
      success: (res) => {
        that.setData({
          accountOptions:res.rows,
          ["form.transfers[0].applyDate"]: UTIL.formatDate(new Date()),
          applyDate: UTIL.formatDate(new Date()),
        })
      }
    })
    this.setData({
      ["form.transfers"] : transList,
      activeNames:transList.length-1
    })
    for (let i = 0; i < this.data.form.transfers.length; i++) {
      const element = this.data.form.transfers[i];
      this.setData({
        ["form.transfers["+i+"].showTitle"] : false,
      })
    }
    this.setData({
      ["form.transfers["+(transList.length-1)+"].showTitle"] : true,
    })
    console.log(this.data.form);
  },
  openPreview(e){
    let array = [];
    console.log(e);
    e.currentTarget.dataset.option.forEach(item=>{
      array.push(item.tempFilePath)
    })
    console.log(array);
    wx.previewImage({
      urls: array,
      showmenu:true,
      current:array[e.currentTarget.dataset.index]
    })
  },
  goKeep(){
    var that = this;
    let pages = getCurrentPages();
    let currentPage = null;   //当前页面
    let prevPage = null;  //上一个页面
    currentPage = pages[pages.length - 1]; //获取当前页面，将其赋值
    prevPage = pages[pages.length - 2]; //获取上一个页面，将其赋值
    console.log(that.data.form);
    if (prevPage) {
      prevPage.setData({         
        form : that.data.form,//将想要传的信息赋值给上一个页面data中的值
      })
      that.back()
    }
  },
  deleteTransfers(e){
    var that = this ;
    console.log(e.currentTarget.dataset.index);
    // that.data.form.transfers[e.currentTarget.dataset.index].collapseDis = true;
      that.setData({
        ["form.transfers["+e.currentTarget.dataset.index+"].collapseDis"]:true
      })
    if(that.data.form.transfers.length<2){
      UTIL.showToastNoneIcon('最少保留一条事项');
      return;
    }

    that.data.form.transfers[e.currentTarget.dataset.index].expenditureAmount = that.data.form.transfers[e.currentTarget.dataset.index].expenditureAmount == '' ? '0' : that.data.form.transfers[e.currentTarget.dataset.index].expenditureAmount;
    that.data.form.approvalItemTemplate.totalAmount =  parseFloat(parseFloat(that.data.form.approvalItemTemplate.totalAmount)- parseFloat(that.data.form.transfers[e.currentTarget.dataset.index].expenditureAmount)).toFixed(2);
    that.data.form.transfers.splice(e.currentTarget.dataset.index,1);

    for (let i = 0; i < that.data.form.transfers.length; i++) {
      that.data.form.transfers[i].num = UTIL.convertToChinaNum(i+1)
    }
    console.log(that.data.form);
    that.setData({
      form:that.data.form,
    })
  },
  disabledNone(e){
    console.log("b");
    var that = this ;
    that.setData({
      ["form.transfers["+e.currentTarget.dataset.index+"].collapseDis"]:true
    })
  },
  disabledBlock(e){
    console.log("a");
    var that = this ;
    that.setData({
      ["form.transfers["+e.currentTarget.dataset.index+"].collapseDis"]:false
    })
  },
  onOpen(e){
    var that = this ;
    console.log(that.data.activeNames);
    console.log(e);
    for (let i = 0; i < this.data.form.transfers.length; i++) {
      const element = this.data.form.transfers[i];
      this.setData({
        ["form.transfers["+i+"].showTitle"] : false,
      })
    }
    that.setData({
      ["form.transfers["+e.detail+"].showTitle"]:true
    })
  },
  onCloseSecond(e){
    var that = this ;
    console.log(e);
    that.setData({
      ["form.transfers["+e.detail+"].showTitle"]:false
    })
  },
  deleteimg(e){
    let options = e.currentTarget.dataset.options;
    console.log(options);
    let file = this.data.form.transfers[e.currentTarget.dataset.parentsindex].fileForm;
    for (let i = 0; i < file.length; i++) {
      const element = file[i];
      if(element.file == options[e.currentTarget.dataset.index].tempFilePath){
        file.splice(i,1);
      }
    }
    options.splice(e.currentTarget.dataset.index,1);
    let length = this.data.form.transfers[e.currentTarget.dataset.parentsindex].fileNum - 1;
    this.setData({
      [e.currentTarget.dataset.name]:options,
      ["form.transfers["+e.currentTarget.dataset.parentsindex+"].fileNum"]:length,
      ["form.transfers["+e.currentTarget.dataset.parentsindex+"].fileForm"]:file,
    })
    UTIL.httpRequest(API.URL_GET_GETFILEREMOVE+e.currentTarget.dataset.id , {method:'GET'}, {
      success: (res) => {
        wx.showToast({
          title: '删除成功！',
          icon: 'success',
          duration: 2000,
        })
      }
    })
  },
  uploadFile(e){
    var that = this;
    if(e.currentTarget.dataset.payer == null || e.currentTarget.dataset.payer == ''){
      UTIL.showToastNoneIcon('请先选择付款方！');
      return;
    }
    console.log(e);

    let moneyParents = e.currentTarget.dataset.totalamount == ''?'0.00':e.currentTarget.dataset.totalamount;
    let moneyChildren = e.currentTarget.dataset.expenditureamount == ''?'0.00':e.currentTarget.dataset.expenditureamount

    let totalAmount = parseFloat(moneyParents) - parseFloat(moneyChildren);
    console.log(moneyParents);
    console.log(moneyChildren);
    wx.navigateTo({
      url: 'upLoad/upLoad?bankType='+e.currentTarget.dataset.banktype+'&&index='+e.currentTarget.dataset.index+'&&totalAmount='+totalAmount
    })
    return;
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success (res) {
        console.log(res);
        // tempFilePath可以作为 img 标签的 src 属性显示图片
        const tempFilePaths = res.tempFiles
        wx.uploadFile({
          url: API.URL_GET_UPLOADFILE,
          filePath: tempFilePaths[0].path,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",//记得设置
            "chartset":"utf-8",
            'Authorization':'Bearer '+getApp().globalData.userInfo.token
          },
          formData:{
            bankType:'2',
            accountType:'1',
            isPeers:'Y'
          },
          success (response){
            console.log(response);
            let list = JSON.parse(response.data);
            console.log(list);
            that.setData({
              ['form.transfers[0].payeeList']:list.rows
            })
          },
          fail(res){
          }
        })
      }
    })
  },
  downLoad(){
    wx.downloadFile({
      url:  API.URL_GET_DOWNFILE, //仅为示例，并非真实的资源
      success (res) {
        console.log(res);
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          var fs = wx.getFileSystemManager();
          fs.saveFile({
            tempFilePath:res.tempFilePath,
            success:function(response){
              console.log(response);
            }
          })
          // wx.saveFile({
          //   tempFilePath: res.tempFilePath,
          //   success:function(response){
          //     console.log(response);
          //   }
          // })

          // wx.playVoice({
          //   filePath: res.tempFilePath
          // })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

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

  },

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

  },

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

  },

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

  }
})