// pages/regular/index.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,
    option1: [],
    option2: [],
    option3: [],
    list: [],
    value1: '',
    value2: '',
    value3: '',
    showPopup:false,
    result1:'',
    result2:'',
    result3:'',
    beginApplyDate:'' , //申请开始时间
    endApplyDate: '' ,  //申请结束时间
    txnamtMin: '' , //金额范围 最小
    xnamtMax: '' , //金额范围最大
    showDialog:false,
    beforeClose(action) {
      return new Promise((resolve) => {
        setTimeout(() => {
          if (action === 'confirm') {
            // 拦截确认操作
             resolve(false);
          } else {
            resolve(true);
          }
        }, 0);
      });
    },
    projectId:'',
    projectValue:'',
    pageNums:1,
    params:{
      actacn:'' , //付款账户
      payeeActacn: '' , //收款账号
      payeeToname:'' ,  //收款人
      transtype:'' ,//  业务类型 数据字典：trans_type  
      direction:'' ,// 来往账标识 数据字典：direction  
      pageSize:'10',
      pageNum:1,
      method:'POST',
    },
    recordform: {},
    formSms: {},
    recordopen4: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    let qu = wx.createSelectorQuery()
    qu.select("#top_view").boundingClientRect()
    qu.select("#top_ban").boundingClientRect()
    qu.select("#top_view1").boundingClientRect()
    qu.select("#top_view2").boundingClientRect()
    qu.exec(res => {
      console.log(res);
      that.setData({
        scrollHeight:wx.getWindowInfo().windowHeight-res[3].top
      })
    })
    // 对账状态字典查询
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'check_status', {method:'GET'}, {
      success: (res) => {
        that.setData({
          checkStatusOptions:res.data,
        })
      }
    })
    // 业务类型字典查询
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'trans_type', {method:'GET'}, {
      success: (res) => {
        let option2 = [{
          text: '业务类型', value: ''
        }];
        res.data.map(rr=>{
          option2.push({
            text: rr.dictLabel, value: rr.dictValue
          })
        })
        that.setData({
          option2:option2,
          transTypeOptions:res.data,
        })
      }
    })
    // 来往账标识字典查询
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'direction', {method:'GET'}, {
      success: (res) => {
        let option3 = [];
        res.data.map(rr=>{
          option3.push({
            text: rr.dictLabel, value: rr.dictValue
          })
        })
        option3[0].text = '来往账标识';
        that.setData({
          option3:option3,
          value3:res.data[0].dictValue,
          result3:res.data[0].dictValue,
          directionOptions:res.data,
        })
      }
    })
    var sendData = {
      pageNum:'1',
      pageSize:'100',
      accountName:'',
      bankAccountNumber:'',
      status:'N',
      method:'GET',
      accountType:102
    }
    UTIL.httpRequest(API.URL_GET_ACCOUNTLIST, sendData,{
      success: (res) => {
          console.log(res.rows)
          let option1 = [];
          res.rows.map(rr=>{
            console.log(rr);
            option1.push({
              text: rr.accountName, value: rr.bankAccountNumber
            })
          })
          that.setData({
            option1:option1,
            value1:res.rows[0].bankAccountNumber,
            result1:res.rows[0].bankAccountNumber,
            accountList:res.rows
          })
          console.log(res.rows[0].bankAccountNumber);
          let actacnName = (that.data.option1).filter(function (e) { return e.value == that.data.result1; });
          that.setData({
            actacnName:actacnName[0].text,
            ["params.actacn"]:res.rows[0].bankAccountNumber
          })
          that.getData();
      }
    })
  },
  getData(){
    var that = this;
    let data = that.data.list;
    //交易明细列表
    UTIL.httpRequest(API.URL_GET_GETRECORDETAILLIST , this.data.params, {
      success: (res) => {
        console.log(res);
        console.log(res.total +'---------------------'+ data.length);
        if(res.total <= data.length){
          return;
        }else{
          res.rows.map(rrr=>{
            rrr.directionText = UTIL.getTransform(rrr.direction,that.data.directionOptions);
            data.push(rrr);
          })
          that.setData({
            list:data
          })
        }
        
      }
    })
  },
  paging(){
    this.setData({
      pageNums:this.data.pageNums+1,
    })
    this.getData();
  },
  goSubmit(){
    var that = this ;
    let form = {
      actacn:that.data.result1 , //付款账户
      payeeActacn: '' , //收款账号
      payeeToname:'' ,  //收款人
      transtype:that.data.result2 ,//  业务类型 数据字典：trans_type  
      direction:that.data.result3 ,// 来往账标识 数据字典：direction  
      params:{
        beginTxnDate:that.data.beginApplyDate,
        endTxnDate:that.data.endApplyDate,
        txnamtMin:that.data.txnamtMin,
        txnamtMax:that.data.xnamtMax,
      },
      pageSize:'10',
      method:'POST',
    }
    console.log(form);
    UTIL.httpRequest(API.URL_GET_GETRECORDETAILLIST , form, {
      success: (res) => {
        res.rows.map(rrr=>{
          rrr.directionText = UTIL.getTransform(rrr.direction,that.data.directionOptions);
        })
        let actacnName = (that.data.option1).filter(function (e) { return e.value == that.data.result1; });
        that.setData({
          value1:that.data.result1,
          value2:that.data.result2,
          value3:that.data.result3,
          actacnName:actacnName[0].text,
          list:res.rows,
          showPopup:false
        })
      }
    })
  },
  bindDateBeginChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['params.params.beginApplyDate']:e.detail.value,
    })
  },
  bindDateEndChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      ['params.params.endApplyDate']:e.detail.value,
    })
  },
  reset(){
    this.setData({
      result2:'',
      txnamtMin:'',
      xnamtMax:'',
      beginApplyDate:'',
      endApplyDate:''
    })
    this.onLoad();
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  showPopup(){
    var that = this;
    that.setData({
      showPopup:true
    })
  },
  onClose() {
    this.setData({ 
      showPopup: false,
      recordopen4: false
    });
  },
  onChangeZH(event) {
    console.log(event.detail);
    this.setData({
      result1: event.detail,
    });
  },
  onChangeLX(event) {
    console.log(event.detail);
    this.setData({
      result2: event.detail,
    });
  },
  onChangeBS(event) {
    console.log(event.detail);
    this.setData({
      result3: event.detail,
    });
  },
  changeTab1(event){
    var that = this ;
    let actacnName = (that.data.option1).filter(function (e) { return e.value == event.detail; });
    this.setData({
      result1: event.detail,
      value1: event.detail,
      actacnName:actacnName[0].text,
      ['params.actacn']:event.detail,
      ['params.pageNum']:1,
      list:[]
    });
    this.getData();
  },
  changeTab2(event){
    this.setData({
      result2: event.detail,
      value2: event.detail,
      ['params.transtype']:event.detail,
      ['params.pageNum']:1,
      list:[]
    });
    this.getData();
  },
  changeTab3(event){
    this.setData({
      result3: event.detail,
      value3: event.detail,
      ['params.direction']:event.detail,
      ['params.pageNum']:1,
      list:[]
    });
    this.getData();
  },
  minInput(e){
    var that = this ;
    that.setData({
      ['params.params.txnamtMin']:e.detail.value,
    })
  },
  maxInput(e){
    var that = this ;
    that.setData({
      ['params.params.xnamtMax']:e.detail.value,
    })
  },
  openDZ(e){
    var that = this;
    that.setData({
      projectId:'',
      projectValue:''
    })
    var id = e.currentTarget.dataset.id;
    that.setData({
      showDialog:true,
      projectId:id
    })
  },
  goDZ(e){
    var that = this ;
    var form = {
      manualRemark:that.data.projectValue,
      id:that.data.projectId,
      method:'POST'
    }
    console.log(form);
    UTIL.httpRequest(API.URL_GET_GETTRANSFEREDIT , form, {
      success: (res) => {
        that.setData({
          showDialog:false
        })
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000,
        })
      }
    })
  },
  bindNameInput(e){
    var that = this;
    var value = e.detail.value;
    that.setData({
      projectValue:value
    })
  },
  toPayDetail(e){
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: 'transactionDetail/transactionDetail?id='+id,
    })
  },
  goHD(e){
    let url = e.currentTarget.dataset.url;
    let alternateField1 = e.currentTarget.dataset.field1;
    let alternateField4 = e.currentTarget.dataset.field4;
    let alternateField9 = e.currentTarget.dataset.field9;
    let id = e.currentTarget.dataset.id;
    console.log(alternateField1);
    console.log(alternateField4);
    console.log(alternateField9);
    if (alternateField1=='3') {
      if (url==null) {
        UTIL.httpRequest(API.URL_GET_GETDIANZIHUIDAN1 + id , {method:'GET'}, {
          success: (res) => {
            console.log(res);
            url = res.data.alternateField2;
            wx.navigateTo({
              url: 'receipt/receipt?url='+url,
            })
          }
        })
      }else if(url.indexOf('失败')>-1){
        UTIL.showToastNoneIcon(url);
      }else{
        wx.navigateTo({
          url: 'receipt/receipt?url='+url,
        })
      }
    }
    if (alternateField4!=null) {
      console.log('aaa');
      if (url==null) {
        UTIL.httpRequest(API.URL_GET_GETDIANZIHUIDAN2 + id , {method:'GET'}, {
          success: (res) => {
            console.log(res);
            url = res.data.alternateField2;
            wx.navigateTo({
              url: 'receipt/receipt?url='+url,
            })
          }
        })
      }else if(url.indexOf('失败')>-1){
        UTIL.showToastNoneIcon(url);
      }else{
        wx.navigateTo({
          url: 'receipt/receipt?url='+url,
        })
      }
    }
    if (alternateField1=='2' && alternateField9!='' && alternateField9!=null) {
      if (url==null) {
        UTIL.httpRequest(API.URL_GET_GETDIANZIHUIDAN3 + id , {method:'GET'}, {
          success: (res) => {
            console.log(res);
            url = res.data.alternateField2;
            wx.navigateTo({
              url: 'receipt/receipt?url='+url,
            })
          }
        })
      }else if(url.indexOf('失败')>-1){
        UTIL.showToastNoneIcon(url);
      }else{
        wx.navigateTo({
          url: 'receipt/receipt?url='+url,
        })
      }
    }
  },
  showTransactionDialog(){
    wx.navigateTo({
      url: 'receipt/receipt',
    })
  },
  goSearch(e){
    console.log(e);
    var that = this;
    let form = {
      payeeToname:e.detail ,  //收款人
      params:{
        beginTxnDate:that.data.beginApplyDate,
        endTxnDate:that.data.endApplyDate,
        txnamtMin:that.data.txnamtMin,
        txnamtMax:that.data.xnamtMax,
      },
    }
    this.setData({
      list:[],
      ['params.payeeToname']:e.detail
    });
    this.getData();
    // UTIL.httpRequest(API.URL_GET_GETRECORDETAILLIST , form, {
    //   success: (res) => {
    //     res.rows.map(rrr=>{
    //       rrr.directionText = UTIL.getTransform(rrr.direction,that.data.directionOptions);
    //     })
    //     that.setData({
    //       list:res.rows,
    //       showPopup:false
    //     })
    //   }
    // })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  handleHuidan(rows) {
    console.log(rows);
    this.data.recordform.id = rows.currentTarget.dataset.row.id;
    this.data.recordform.method = 'GET';
    this.data.recordListOpen = false;
    UTIL.httpRequest(API.transactionDetailsQuery2OnlyQuery , this.data.recordform, {
      success: (response) => {
        this.setData({
          tYinnongTradingRecordDetailList: response.data,
          recordListOpen: true,
          title: "查看回单列表数据"
        })
      }
    })
  },
  handleView1(rows){
    let dataRow = rows.currentTarget.dataset.row;
    if(dataRow.alternateField2 != null && dataRow.alternateField2 != "" && dataRow.alternateField2.indexOf('失败') == -1){
      this.showfileFunction(dataRow.alternateField2);
    } else{
      UTIL.showToastNoneIcon("暂无回单，请到村账户模块查询电子回单！");
    }
  },
  handleView2(rows){
    this.checkId = rows.currentTarget.dataset.row.id;
    this.yinnongTransfersIndexOpen = false;
    this.tYinnongTransferDetaiList = [];
    const baseURL = wx.getStorageSync('dressCode');
    //console.info(baseURL);
    const id = rows.currentTarget.dataset.row.id || this.ids
    if(rows.currentTarget.dataset.row.alternateField2 != null && rows.currentTarget.dataset.row.alternateField2 != "" && rows.currentTarget.dataset.row.alternateField2.indexOf('失败') == -1){
      this.receiptUrl = baseURL+rows.currentTarget.dataset.row.alternateField2;
      this.recordopen = true;
      if(rows.currentTarget.dataset.row.transferId != null){
        this.yinnongTransfersListOpen = true;
        this.yinnongTransfersIndexApplyOpen = false;
        this.tYinnongTransferDetaiList=[];
        queryTransferDetail(rows.currentTarget.dataset.row.transferId).then((res) => {
          this.yinnongTransfersIndexOpen = true;
          for (let i = 0 ; i < res.rows.length; i++){
            res.rows[i].transferStatus = this.transferStatusFormat(res.rows[i])
            this.tYinnongTransferDetaiList.push(res.rows[i])
          }
        });
      }else{
        this.yinnongTransfersListOpen = false;
      }
    } else {
      bankReceiptPhoto(rows.currentTarget.dataset.row.id).then((response) => {
        //console.info(response);
        if (response.code === 200) {
          this.receiptUrl =baseURL+ response.msg;
          this.recordopen = true;
          this.getList();
        }
      });
    }
  },
  handleView3(rows){
    const id = rows.currentTarget.dataset.row.id;
    let dataRow = rows.currentTarget.dataset.row;
    if(dataRow.alternateField2 != null && dataRow.alternateField2 != "" && dataRow.alternateField2.indexOf('失败') == -1){
      this.showfileFunction(dataRow.alternateField2);
    } else{
      UTIL.httpRequest(API.getDianzihuidan + id , {method: 'GET'}, {
        success: (response) => {
          if(response.data.alternateField2 != null && response.data.alternateField2 != "" && response.data.alternateField2.indexOf('失败') ==-1){
            this.showfileFunction(response.data.alternateField2);
          } else{
            UTIL.showToastNoneIcon(response.data.alternateField2);
          }
        }
      })
    }
  },
  handleView4(rows){
    let row = rows.currentTarget.dataset.row;
    if(row.alternateField2 != null && row.alternateField2 != "" && row.alternateField2.indexOf('失败') == -1){
      this.showfileFunction(row.alternateField2);
    } else {
      UTIL.httpRequest(API.queryReceiptPhoto4 + row.id , {method: 'GET'}, {
        success: (response) => {
          this.setData({
            recordopen4: true
          })
        }
      })
    }
  },
  handleView5(rows){
    let dataRow = rows.currentTarget.dataset.row;
    if(dataRow.alternateField2 != null && dataRow.alternateField2 != "" && dataRow.alternateField2.indexOf('失败') == -1){
      this.showfileFunction(dataRow.alternateField2);
    } else {
      UTIL.httpRequest(API.queryReceiptPhoto5 + dataRow.id , {method: 'GET'}, {
        success: (response) => {
          if (response.code === 200) {
            this.showfileFunction(response.msg);
          }else{
            UTIL.showToastNoneIcon(response.msg);
          }
        }
      })
    }
  },
  handleView6(rows){
    let dataRow = rows.currentTarget.dataset.row;
    if(dataRow.alternateField2 != null && dataRow.alternateField2 != "" && dataRow.alternateField2.indexOf('失败') == -1){
      const filenames = dataRow.alternateField2.split("|");
      if(filenames.length == 1){
        this.showfileFunction(filenames[0]);
      }else{
        for (var i=0;i<filenames.length;i++){
          this.showfileFunction(filenames[i]);
        }
      }
    } else {
      UTIL.httpRequest(API.queryReceiptPhoto6 + dataRow.id , {method: 'GET'}, {
        success: (response) => {
          if (response.code === 200) {
            const filenames = response.msg.split("|");
            if(filenames.length == 1){
              this.showfileFunction(filenames[0]);
            }else{
              for (var i=0;i<filenames.length;i++){
                this.showfileFunction(filenames[i]);
              }
            }
          }else{
            UTIL.showToastNoneIcon(response.msg);
          }
        }
      })
    }
  },
  handleView8(rows){
    let dataRow = rows.currentTarget.dataset.row;
    if(dataRow.alternateField2 != null && dataRow.alternateField2 != "" && dataRow.alternateField2.indexOf('失败') == -1){
      const filenames = dataRow.alternateField2.split("|");
      if(filenames.length == 1){
        this.showfileFunction(filenames[0]);
      }else{
        for (var i=0;i<filenames.length;i++){
          this.showfileFunction(filenames[i]);
        }
      }
    } else {
      UTIL.httpRequest(API.queryReceiptPhoto8 + dataRow.id , {method: 'GET'}, {
        success: (response) => {
          if (response.code === 200) {
            const filenames = response.msg.split("|");
            if(filenames.length == 1){
              this.showfileFunction(filenames[0]);
            }else{
              for (var i=0;i<filenames.length;i++){
                this.showfileFunction(filenames[i]);
              }
            }
          }else{
            UTIL.showToastNoneIcon(response.msg);
          }
        }
      })
    }
  },
  handleView18(rows){
    let dataRow = rows.currentTarget.dataset.row;
    if(dataRow.alternateField2 != null && dataRow.alternateField2 != "" && dataRow.alternateField2.indexOf('失败') == -1){
        this.showfileFunction(dataRow.alternateField2);
    } else{
      UTIL.httpRequest(API.queryReceiptPhoto18 + dataRow.id , {method: 'GET'}, {
        success: (response) => {
          if (response.code === 200) {
            if(response.data.alternateField2 != null && response.data.alternateField2 != "" && response.data.alternateField2.indexOf('失败') ==-1){
              this.showfileFunction(response.data.alternateField2);
            } else{
              UTIL.showToastNoneIcon(response.msg);
            }
          }else{
            UTIL.showToastNoneIcon(response.msg);
          }
        }
      })
    }
  },
  handleView10(rows){
    let dataRow = rows.currentTarget.dataset.row;
    if(dataRow.alternateField2 != null && dataRow.alternateField2 != "" && dataRow.alternateField2.indexOf('失败') == -1){
        this.showfileFunction(dataRow.alternateField2);
    } else{
      UTIL.httpRequest(API.queryReceiptPhoto10 + dataRow.id , {method: 'GET'}, {
        success: (response) => {
          if (response.code === 200) {
            if(response.msg != null && response.msg != "" && response.msg.indexOf('失败') ==-1){
              this.showfileFunction(response.msg);
            } else{
              UTIL.showToastNoneIcon(response.msg);
            }
          }else{
            UTIL.showToastNoneIcon(response.msg);
          }
        }
      })
    }
  },
  /** 绑定手机号操作 */
  smsSubmitForm() {
    this.formSms.method = 'GET';
    UTIL.httpRequest(API.bankReceiptPhoto4sms , this.formSms, {
      success: (response) => {
        if (response.code === 200) {
          this.setData({
            recordopen4: false
          })
          this.showfileFunction(response.msg);
        }else{
          UTIL.showToastNoneIcon(response.msg);
        }
      }
    })
  },

  showfileFunction(url){
    const baseURL = wx.getStorageSync('dressCode');
    if(url.indexOf('pdf') < 0){
      wx.previewImage({
        current: baseURL+ url, // 当前显示图片的http链接
        urls: [baseURL+ url] // 需要预览的图片http链接列表
      })
    }else{
      wx.downloadFile({
        // 示例 url，并非真实存在
        url: baseURL+url,
        success: function (res) {
          const filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            fileType: 'pdf', // 注意这里需要指定文件类型为'pdf'
            success: function (res) {
              console.log('打开文档成功');
            },
            fail: function (err) {
              UTIL.showToastNoneIcon('打开文档失败');
            }
          });
        },
        fail: function (err) {
          UTIL.showToastNoneIcon('下载文件失败');
        }
      });
    }
  }

})