// pages/handle/expenditureAudit/expenditureAudit.js
import * as UTIL from '../../../utils/util.js';
import * as API from '../../../utils/API.js';
let EVN_CONFIG = require('../../../env/env');

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIPX: app.globalData.isIPX,
    active:0,
    spsxOptions:[],
    paymentPatternOptions:[],
    transferStatusOptions:[],
    nickName:'',
    comment:'',
    activeNames: 0,
    transferTypeOption:[
      {
        dictLabel:'银行转账',
        dictValue:'1'
      },
      {
        dictLabel:'信用卡转账',
        dictValue:'2'
      }
    ],
    showSteps:false,
    activeStepsNames:''
  },
  showS(){
    this.setData({
      showSteps:!this.data.showSteps,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      taskId:options.taskId,
      pageType:options.type
    })
    wx.showLoading({
      title: '正在加载模板',
      mask:true
    })
    //所属银行
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'bank_type', {method:'GET'}, {
      success: (res) => {
        this.setData({
          bankTypeOptions:res.data
        });
      }
    })
    //所属银行
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'transfer_status', {method:'GET'}, {
      success: (res) => {
        this.setData({
          transferStatusOptions:res.data
        });
      }
    })
    //所属银行
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'audit_status', {method:'GET'}, {
      success: (res) => {
      }
    })
    // 资金支出类别字典查询
    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,
        })
      }
    })
    let templateQueryParams = {
      // 分页
      method:'GET',
      pageNum: 1,
      pageSize: 999,
      type:'1'
    };
    // 审批流程列表
    UTIL.httpRequest(API.URL_GET_TEMPLATELIST , templateQueryParams, {
      success: (res) => {
        that.setData({
          approvalTemplateNameOptions:res.rows,
          ["form.approvalTemplateId"]:res.rows[0].id,
          ["form.approvalTemplateName"]:res.rows[0].name,
        })
        
      }
    })

    UTIL.showLoadingHaveMask();
    var perames = {
      pageNum:1,
      pageSize:999,
      accountType:'102',
      method:'POST'
    }
    // 付款方列表
    UTIL.httpRequest(API.URL_GET_SELECTACCOUNTLIST , perames, {
      success: (res) => {
        console.log(res);
        that.setData({
          accountOptions:res.rows,
          
        })
      }
    })
    setTimeout(function(){
      UTIL.httpRequest(API.URL_GET_APPROVALITEMS+options.id, {method:'GET'}, {
        success: (res) => {
          if (res.code == API.SUCCESS_CODE) {
            
            // 审批模板
            UTIL.httpRequest(API.URL_GET_selectApprovalByTemplateId+res.data.approvalTemplateId, {method:'GET'}, {
              success: (rres) => {
                that.setData({
                  steps:rres.approvalDetails
                })
              }
            })

            res.data.capitalExpenditureTypeText = UTIL.getTransform(res.data.capitalExpenditureType,that.data.capitalExpenditureTypeOptions);

            res.data.transferTypeText = UTIL.getTransform(res.data.transferType,that.data.transferTypeOption);
            
            if(res.data.capitalExpenditureType == 2){
              let prames = {
                outId:res.data.id,
                ynType: res.data.transferType=='1'||res.data.transferType=='2'||res.data.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.projectForm"]:res.data,
                  })
                }
              })
            }

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

            that.setData({
              ["form.fileNum"]:0,
            })
            UTIL.httpRequest(
              API.URL_GET_FINDLIST, 
              {
                method:'GET',
                tableName:'t_yinnong_transfer',
                tableId:res.data.id,
                fileType:1
              }, 
              {
              success: (res) => {
                
                let list = [];
                
                res.data.forEach((item2,index2)=>{
                  
                  let fileForm = res.data.fileForm?res.data.fileForm:[];
                  fileForm.push({
                    file: wx.getStorageSync('dressCode')+item2.fileUrl,
                    fileType:'1',
                    bizPath:'transfer',
                    tableName:'t_yinnong_transfer',
                    tableId:''
                  })
                  list.push({
                    tempFilePath:wx.getStorageSync('dressCode')+item2.fileUrl,
                    id:item2.id
                  })
                  that.setData({
                    ["form.fileNum"]:that.data.form.fileNum+1,
                    ["form.SJimage"]:list,
                    ["form.fileForm"]:fileForm
                  });

                })
                
              }
            })
            //发票
            UTIL.httpRequest(
              API.URL_GET_FINDLIST, 
              {
                method:'GET',
                tableName:'t_yinnong_transfer',
                tableId:res.data.id,
                fileType:2
              }, 
              {
              success: (res) => {
                let list = [];
                res.data.forEach((item2,index2)=>{
                  let fileForm = res.data.fileForm?res.data.fileForm:[];
                  fileForm.push({
                    file: wx.getStorageSync('dressCode')+item2.fileUrl,
                    fileType:'2',
                    bizPath:'transfer',
                    tableName:'t_yinnong_transfer',
                    tableId:res.data.id
                  })
                  list.push({
                    tempFilePath:wx.getStorageSync('dressCode')+item2.fileUrl,
                    id:item2.id
                  })
                  that.setData({
                    ["form.fileNum"]:that.data.form.fileNum+1,
                    ["form.FPimage"]:list,
                    ["form.fileForm"]:fileForm
                  });
                })
              }
            })
            //其他
            UTIL.httpRequest(
              API.URL_GET_FINDLIST, 
              {
                method:'GET',
                tableName:'t_yinnong_transfer',
                tableId:res.data.id,
                fileType:3
              }, 
              {
              success: (res) => {
                let list = [];
                res.data.forEach((item2,index2)=>{
                  let fileForm = res.data.fileForm?res.data.fileForm:[];
                  fileForm.push({
                    file: wx.getStorageSync('dressCode')+item2.fileUrl,
                    fileType:'3',
                    bizPath:'transfer',
                    tableName:'t_yinnong_transfer',
                    tableId:res.data.id
                  })
                  list.push({
                    tempFilePath:wx.getStorageSync('dressCode')+item2.fileUrl,
                    id:item2.id
                  })
                  that.setData({
                    ["form.fileNum"]:that.data.form.fileNum+1,
                    ["form.QTimage"]:list,
                    ["form.fileForm"]:fileForm
                  });
                })
              }
            })
            //四议两公开
            UTIL.httpRequest(
              API.URL_GET_FINDLIST, 
              {
                method:'GET',
                tableName:'t_yinnong_transfer',
                tableId:res.data.id,
                fileType:4
              }, 
              {
              success: (res) => {
                let list = [];
                res.data.forEach((item2,index2)=>{
                  let fileForm = res.data.fileForm?res.data.fileForm:[];
                  fileForm.push({
                    file: wx.getStorageSync('dressCode')+item2.fileUrl,
                    fileType:'4',
                    bizPath:'transfer',
                    tableName:'t_yinnong_transfer',
                    tableId:res.data.id
                  })
                  list.push({
                    tempFilePath:wx.getStorageSync('dressCode')+item2.fileUrl,
                    id:item2.id
                  })
                  that.setData({
                    ["form.fileNum"]:that.data.form.fileNum+1,
                    ["form.SYLGKimage"]:list,
                    ["form.fileForm"]:fileForm
                  });
                })
              }
            })

            let query = {
              method:'GET',
              // accountType:res.data.accountType,
              // status:"0",
              // orderByColumn: "id",
              // isAsc: "desc",
            }
            UTIL.httpRequest(API.URL_GET_TRANSFERINFOS+options.id, query, {
              success: (response) => {
                if (res.code == API.SUCCESS_CODE) {
                  for(let i = 0 ; i < response.rows.length ; i++){
                    response.rows[i].bankTypeText = UTIL.getTransform(response.rows[i].bankType,that.data.bankTypeOptions);
                    response.rows[i].transferStatusText = UTIL.getTransform(response.rows[i].transferStatus,that.data.transferStatusOptions);
                  }
                  that.setData({
                    ["form.payeeList"]:response.rows
                  })
                }
              }
            })

              that.setData({
                form:res.data,
                isUpdate:true,
                showFile:true,
                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.httpRequest(API.URL_GET_GETPROCESSNEW+options.id , {method:'GET'}, {
              success: (res) => {
                console.log(res);
                for (let i = 0; i < res.data.length; i++) {
                  const element = res.data.processSchedule.审批事项[i];
                  if (element.electronicSignature!=null) {
                    element.electronicSignature = wx.getStorageSync('dressCode')+element.electronicSignature;
                  }
                }

                const arr = [];
                for (let key in res.data) {  
                  if (res.data.hasOwnProperty(key)) {  // 确保键在对象自身上，而不是从原型链继承  
                    for (let i = 0; i < res.data[key].length; i++) {
                      const element = res.data[key][i];
                      console.log(`Key: ${key}, Value: ${res.data[key][i].electronicSignature}`);
                      if (element.electronicSignature!=null) {
                        element.electronicSignature = wx.getStorageSync('dressCode')+element.electronicSignature;
                      }
                    }
                    arr.push([key,res.data[key]])
                    // that.setData({instanceId:res.data.instanceId})
                  }  
                }
                that.setData({spsxOptions:arr})


                // if(options.business == 'xj'){
                //   console.log(that.data.instanceId)
                //   // 查询现金审批事项流转进度
                //   UTIL.httpRequest(API.URL_GET_REVIEWPROCESS+that.data.instanceId , {method:'GET'}, {
                //     success: (res) => {
                //       console.log(res);
                //       if(res.data.processSchedule.审批事项){
                //         that.setData({spsxOptions:res.data.processSchedule.审批事项})
                //       }
                //       that.setData({instanceId:res.data.instanceId})
                //     }
                //   })
                // }
              }
            })
              UTIL.hideLoadingHaveMask();
          }
        }
      })
    },1000)
    



    
   
  },
  onChangePayee(event) {
    console.log(event);
    this.setData({
      ["form.transfers["+event.currentTarget.dataset.index+"].activeName"]:event.detail
    });
  },
  onClosePayee(event){
    console.log("aaa");
    this.setData({
      ["form.transfers["+event.currentTarget.dataset.index+"].activeName"]:''
    });
    console.log(this.data.form.transfers[event.currentTarget.dataset.index]);
  },
  goDis(){
    var that = this ;
    console.log()
    let data = {
      taskId:that.data.taskId,
      instanceId:that.data.instanceId,
      variables:JSON.stringify({
        comment:that.data.comment == '' ? '驳回':that.data.comment,
        pass:false,
      }),
      method:'POST'
    };
    UTIL.httpRequest(API.URL_GET_PROCESSCOMPLETE , data, {
      success: (res) => {
        console.log(res);
        if (res.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
          })
        }
        
      }
    })
  },
  goAgree(){
    var that = this ;
    let data = {
      taskId:that.data.taskId,
      instanceId:that.data.instanceId,
      variables:JSON.stringify({
        "comment":that.data.comment == '' ? '同意':that.data.comment,
        "pass":true,
      }),
      method:'POST'
    };
    UTIL.httpRequest(API.URL_GET_PROCESSCOMPLETE ,data, {
      success: (res) => {
        console.log(res);
        if (res.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
          })
        }
      }
    })
  },
  goAgreeNew(){//2024-7-15审批功能修改 字段名称、接口地址、请求参数格式发生变动
    var that = this ;
    let data = {
      taskId:that.data.taskId,
      auditbatchNo:that.data.form.auditbatchNo,
      pass:true,
      remark:that.data.comment == '' ? '同意':that.data.comment,
      deptId:JSON.parse(wx.getStorageSync('user')).deptId,
      method:'POST'
    };
    console.log(data);
    UTIL.httpRequest(API.A_audit ,data, {
      success: (res) => {
        console.log(res);
        if (res.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
          })
        }
      }
    })
  },
  goDisNew(){//2024-7-15审批功能修改 字段名称、接口地址、请求参数格式发生变动
    var that = this ;
    let data = {
      taskId:that.data.taskId,
      auditbatchNo:that.data.form.auditbatchNo,
      pass:false,
      remark:that.data.comment == '' ? '驳回':that.data.comment,
      deptId:JSON.parse(wx.getStorageSync('user')).deptId,
      method:'POST'
    };
    console.log(data);
    UTIL.httpRequest(API.A_audit ,data, {
      success: (res) => {
        console.log(res);
        if (res.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
          })
        }
      }
    })
  },
  commentInput(e){
    console.log(e);
    var that = this;
    that.setData({
      comment:e.detail.value
    })
  },
  onChangeBox(event) {
    console.log(event);
    this.setData({
      activeNames: event.detail,
    });
  },
  onCloseSecond(e){
    var that = this ;
    console.log(e);
    that.setData({
      ["form.showTitle"]:false
    })
  },
  onChangeSteps(event) {
    console.log(event);
    this.setData({
      activeStepsNames:event.detail
    });
  },
  onCloseSteps(event){
    console.log("aaa");
    this.setData({
      activeStepsNames:''
    });
  },
  onOpen(e){
    var that = this ;
    that.setData({
      ["form.showTitle"]:true
    })
  },
  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]
    })
  },
  goPayee(event){
    wx.navigateTo({
      url: '/pages/pay/payee/payee?options='+JSON.stringify(event.currentTarget.dataset.option)
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

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

  },

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

  },

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

  }
})