// 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 DISTRIBUTE_ENVIROMENT = 'IMGURL';
let {
    URL_PREFIX,
} = EVN_CONFIG[DISTRIBUTE_ENVIROMENT];
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIPX: app.globalData.isIPX,
    active:0,
    spsxOptions:[],
    paymentPatternOptions:[],
    nickName:'',
    comment:'',
    activeNames: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  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 + 'capital_expenditure_type', {method:'GET'}, {
      success: (res) => {
        that.setData({
          capitalExpenditureTypeOptions:res.data,
        })
      }
    })
    // 付款方式类型字典查询 
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'transfer_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_GETDICTTYPE + 'yn_pay_type', {method:'GET'}, {
      success: (res) => {
        that.setData({
          paymentPatternOptions:res.data,
        })
      }
    })
    // 转账状态
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'transfer_status', {method:'GET'}, {
      success: (res) => {
        that.setData({
          transferStatusOptions:res.data,
        })
      }
    })
    // 获取合同信息列表
    UTIL.httpRequest(API.URL_GET_CONTRACTIONLIST , {method:'GET'}, {
      success: (res) => {
        that.setData({
          contractionOptions:res.rows,
        })
      }
    })
    UTIL.httpRequest(API.URL_GET_GETINFO, {method:'GET'}, {
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          that.setData({
            nickName:res.user.nickName
          })
        }
      }
    })
    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 = res.data.transfers.filter(function (e) { return e.id == options.ids; });
            console.log(options.ids);
            console.log(res.data.transfers.filter(function (e) { return e.id == options.ids; }));

            res.data.transfers.forEach( (item,index) => {
              res.data.transfers[index].capitalExpenditureTypeText = UTIL.getTransform(item.capitalExpenditureType,that.data.capitalExpenditureTypeOptions);
              res.data.transfers[index].transferTypeText = UTIL.getTransform(item.transferType,that.data.transferTypeOptions);
  
              res.data.transfers[index].bankTypeText = UTIL.getTransform(item.bankType,that.data.bankTypeOptions);
  
              res.data.transfers[index].paymentPatternText = UTIL.getTransform(item.paymentPattern,that.data.paymentPatternOptions);
  
              res.data.transfers[index].num = UTIL.convertToChinaNum(index+1),
              res.data.transfers[index].expenditureAmount = parseFloat(res.data.transfers[index].expenditureAmount).toFixed(2)
              res.data.transfers[index].showTitle = false;
              res.data.transfers[index].activeName = '';
              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].payeeList[i].transferStatusText = UTIL.getTransform(response.transferStatus,that.data.transferStatusOptions);
              })
              console.log(res.data.transfers[index].capitalExpenditureType);
              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)=>{
                    list.push({
                      tempFilePath:URL_PREFIX+item2.fileUrl
                    })
                    that.setData({
                      ["form.transfers["+index+"].SJimage"]:list,
                    });
                  })
                }
              })
              //发票
              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)=>{
  
                    list.push({
                      tempFilePath:URL_PREFIX+item2.fileUrl
                    })
                    that.setData({
                      ["form.transfers["+index+"].FPimage"]:list,
                    });
                  })
                }
              })
              //其他
              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)=>{
                    list.push({
                      tempFilePath:URL_PREFIX+item2.fileUrl
                    })
                    that.setData({
                      ["form.transfers["+index+"].QTimage"]:list,
                    });
                  })
                }
              })
            })
            that.setData({
              form:res.data,
              activeNames:null
            })
            wx.hideLoading();
          }
        }
      })

      // 查询审批事项流转进度
      // UTIL.httpRequest(API.URL_GET_GETPROCESS+options.id , {method:'GET'}, {
      //   success: (res) => {
      //     console.log(res);
      //     if(res.data.processSchedule != null){
      //       that.setData({spsxOptions:res.data.processSchedule.spsx})
      //     }
      //     that.setData({instanceId:res.data.instanceId})

      //     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.spsx){
      //             that.setData({spsxOptions:res.data.processSchedule.spsx})
      //           }
      //           that.setData({instanceId:res.data.instanceId})
      //         }
      //       })
      //     }
      //   }
      // })

    },1000)
    



    
   
  },
  onChangePayee(event) {
    console.log(event);
    this.setData({
      ["form.transfers["+event.currentTarget.dataset.index+"].activeName"]:event.detail
    });
  },
  goPayee(event){
    wx.navigateTo({
      url: 'payee/payee?options='+JSON.stringify(event.currentTarget.dataset.option)
    })
  },
  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
          })
        }
      }
    })
  },
  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.transfers["+e.detail+"].showTitle"]: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
    })
  },
  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]
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

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

  },

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

  },

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

  },

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

  },

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

  }
})