// pages/apply/paymentTemplate/paymentTemplate.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,
    show: false,
    countMoney:0,
    form:{},
    SJimage: [],
    FPimage: [],
    QTimage: [],
    fileForm:[],
    activeNames: ['1'],
  },
  showPopup() {
    this.setData({ show: true });
  },
  bindNameInput(even){
    this.setData({
      ["form.approvalItemTemplate.templateName"]:even.detail.value
    })
  },
  goSubmit(e){
    var that = this;
    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;
    that.data.form.approvalItemTemplate.id = null;
    for (let i = 0; i < that.data.form.transfers.length; i++) {
      that.data.form.transfers[i].id = null;
    }
    console.log(that.data.form);
    UTIL.httpRequest(API.URL_GET_SAVE, that.data.form, {
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          console.log(that.data.form);
          for (let j = 0; j < res.data.transfers.length; j++) {
            if(that.data.form.transfers[j].fileForm == undefined){continue;}
            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,
            })
          }
          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: 'success',
                    duration: 2000
                  })
                }
              }
            })
            
          }
        }
      }
    })
  },
  onClose() {
    this.setData({ show: false });
  },

  goApproval(){
    wx.navigateTo({
      url: '../approval/approval',
    })
  },
  goSee(){
    let array = JSON.stringify(this.data.form)
    wx.navigateTo({
      url: 'see/see?array='+array+"&index="+e.currentTarget.dataset.index,
    })
  },
  goUpdate(e){
    let array = JSON.stringify(this.data.form)
    wx.navigateTo({
      url: 'add/add?type=update&array='+array+'&add='+e.currentTarget.dataset.add,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  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_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_CONTRACTIONLIST , {method:'GET'}, {
      success: (res) => {
        that.setData({
          contractionOptions:res.rows,
        })
      }
    })
    UTIL.httpRequest(API.URL_GET_APPROVALITEMS + options.id, {method:'GET'}, {
      success: (res) => {
        let transList = res.data.transfers;
        transList.forEach((item,index) => {
          item.num = UTIL.convertToChinaNum(index+1)
          
          transList[index].capitalExpenditureTypeText = UTIL.getTransform(item.capitalExpenditureType,that.data.capitalExpenditureTypeOptions);

          transList[index].transferTypeText = UTIL.getTransform(item.transferType,that.data.transferTypeOptions);

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

          transList[index].payeeList.forEach( (response,i) => {
            transList[index].payeeList[i].bankTypeText = UTIL.getTransform(response.bankType,that.data.bankTypeOptions);
          })

          if(item.capitalExpenditureType == 2){
            let prames = {
              outId:item.id,
              ynType: item.transferType=='1'||item.transferType=='2'||item.transferType=='4'?'1':'2'
            }
            // 工程项目查询
            UTIL.httpRequest(API.URL_GET_GETPROJECTTO , prames, {
              success: (res) => {
                res.data.projectFundTypeText = UTIL.getTransform(res.data.projectFundType,that.data.projectFundTypeOptions);
                array.transfers[index].projectForm = res.data;
              }
            })
          }
          //收据附件
          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)=>{
                
                wx.downloadFile({
                  url: URL_PREFIX+item2.fileUrl, //仅为示例，并非真实的资源
                  success (response) {
                    if (response.statusCode === 200) {
                      let fileForm = item.fileForm?item.fileForm:[];
                      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----------------");
                      list.push({
                        tempFilePath:response.tempFilePath
                      })
                      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)=>{
                wx.downloadFile({
                  url: URL_PREFIX+item2.fileUrl, //仅为示例，并非真实的资源
                  success (response) {
                    if (response.statusCode === 200) {
                      let fileForm = item.fileForm?item.fileForm:[];
                      fileForm.push({
                        file: response.tempFilePath,
                        fileType:'2',
                        bizPath:'transfer',
                        tableName:'t_yinnong_transfer',
                        tableId:item.id
                      })
                      list.push({
                        tempFilePath:response.tempFilePath
                      })
                      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 = [];
              let fileForm = item.fileForm?item.fileForm:[];
              res.data.forEach((item2,index2)=>{
                wx.downloadFile({
                  url: URL_PREFIX+item2.fileUrl, //仅为示例，并非真实的资源
                  success (response) {
                    if (response.statusCode === 200) {
                      let fileForm = item.fileForm?item.fileForm:[];
                      fileForm.push({
                        file: response.tempFilePath,
                        fileType:'3',
                        bizPath:'transfer',
                        tableName:'t_yinnong_transfer',
                        tableId:item.id
                      })
                      list.push({
                        tempFilePath:response.tempFilePath
                      })
                      that.setData({
                        ["form.transfers["+index+"].QTimage"]:list,
                        ["form.transfers["+index+"].fileForm"]:fileForm
                      });
                    }
                  }
                })
              })
            }
          })
        });
        res.data.transfers = transList
        
        that.setData({
          form:res.data,
        });
        
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  goDelete(e){
    var that = this;
    if(that.data.form.transfers.length<2){
      UTIL.showToastNoneIcon('最少保留一条事项');
      return;
    }
    let countMoney = that.data.form.approvalItemTemplate.totalAmount;
    console.log(that.data.form);
    countMoney -=  parseInt(that.data.form.transfers[e.currentTarget.dataset.index].expenditureAmount);
    that.data.form.transfers.splice(e.currentTarget.dataset.index, 1); 
    that.setData({
      form : that.data.form,
      ["that.data.form.approvalItemTemplate.totalAmount"]:countMoney
    })
    UTIL.showToastNoneIcon('删除成功！');
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})