// pages/bankDraft/bankDraft.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: [
      { text: '汇票类型', value: '' },
      { text: '银行承兑', value: '1' },
      { text: '商业承兑', value: '2' },
    ],
    option2: [
      { text: '汇票状态', value: '' },
      { text: '在库', value: '1' },
      { text: '转付中', value: '2' },
      { text: '转付', value: '3' },
      { text: '承兑', value: '4' },
    ],
    value1: '',
    value2: '',
    moneyorderList:[],
    value:'',
    pageNums:1,
    showUpload:false,
    showPopupDel:false,
    uploadOptions:[],
    fileList:[],
    itemId:"",
    itemIndex:"",
    list:[],
    fileEvent:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var _this = 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 => {
      _this.setData({
        scrollHeight:wx.getSystemInfoSync().windowHeight-res[3].top
      })
    })
     //获取附件字典
     UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'common_attach', {method:'GET'}, {
      success: (res) => {
        this.setData({
          uploadOptions:res.data,
        })
      }
    })
  },
  goAdd(){
    wx.navigateTo({
      url: 'add/add',
    })
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
   
  },
  goUpdate(e){
    wx.navigateTo({
      url: 'add/add?id='+ e.currentTarget.dataset.id,
    })
  },
  goSearch(e){
    this.setData({'value':e.detail})
    this.onShow();
  },
  paging(){
    this.setData({
      pageNums:this.data.pageNums+1,
    })
    this.onShow();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'order_type', {method:'GET'}, {
      success: (res) => {
        this.setData({
          orderTypeOptions:res.data
        });
        let param = {
          'orderType':that.data.value1,
          'orderStatus':that.data.value2,
         'billPayUnit' : this.data.value,
         pageNum:this.data.pageNums,
        pageSize:10,
        }
        UTIL.httpRequest(API.URL_GET_GETMONEYORDERLIST, param,{
          success: (response) => {
            if (response.code == API.SUCCESS_CODE) {
              for (let i = 0; i < response.rows.length; i++) {
                response.rows[i].orderTypeText = UTIL.getTransform(response.rows[i].orderType,res.data);
                response.rows[i].orderAmount =   Number(response.rows[i].orderAmount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
              return $1 + ","; }).replace(/\.$/, "") 
              }
              that.setData({
                moneyorderList:response.rows
              })
            }
          }
        })
      }
    })
  },
  delete(e){
    this.setData({
      'itemId':e.currentTarget.dataset.id,
      'itemIndex':e.currentTarget.dataset.index,
      "showPopupDel":true
    });
  },
  cancelTemDel:function(e){
    this.setData({
      "itemId":"",
      "itemIndex":"",
      "showPopupDel":false
    });
  },
  confirmTemDel:function(e){
    this.setData({
      "showPopupDel":false
    });
    UTIL.httpRequest(API.URL_GET_MONEYORDERDELETE + this.data.itemId , {method:'GET'}, {
      success: (res) => {
        if(res.code==200){
          let new_list = this.data.moneyorderList
          new_list.splice(this.data.index,1)
          this.setData({'moneyorderList':new_list})
          UTIL.showToastNoneIcon('删除成功！');
        }else{
          UTIL.showToastNoneIcon('删除失败！');
        }
      }
    })
  },
  changeTab(e){
    var that = this ;
    that.setData({value1:e.detail})

    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'order_type', {method:'GET'}, {
      success: (res) => {
        UTIL.httpRequest(API.URL_GET_GETMONEYORDERLIST, {method:'GET',orderType:that.data.value1,orderStatus:that.data.value2},{
          success: (response) => {
            if (response.code == API.SUCCESS_CODE) {
    
              for (let i = 0; i < response.rows.length; i++) {
                response.rows[i].orderTypeText = UTIL.getTransform(response.rows[i].orderType,res.data);
                response.rows[i].startTime = response.rows[i].startTime.replace(/-/g,".");
                response.rows[i].endTime = response.rows[i].endTime.replace(/-/g,".");
                response.rows[i].orderAmount =  parseFloat(response.rows[i].orderAmount).toFixed(2);
              }
    
              that.setData({
                moneyorderList:response.rows
              })
            }
          }
        })
      }
    })


  },
  changeTab2(e){
    var that = this ;
    that.setData({value2:e.detail})

    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'order_type', {method:'GET'}, {
      success: (res) => {
        UTIL.httpRequest(API.URL_GET_GETMONEYORDERLIST, {method:'GET',orderType:that.data.value1,orderStatus:that.data.value2},{
          success: (response) => {
            if (response.code == API.SUCCESS_CODE) {
    
              for (let i = 0; i < response.rows.length; i++) {
                response.rows[i].orderTypeText = UTIL.getTransform(response.rows[i].orderType,res.data);
                response.rows[i].startTime = response.rows[i].startTime.replace(/-/g,".");
                response.rows[i].endTime = response.rows[i].endTime.replace(/-/g,".");
                response.rows[i].orderAmount =  parseFloat(response.rows[i].orderAmount).toFixed(2);
              }
    
              that.setData({
                moneyorderList:response.rows
              })
            }
          }
        })
      }
    })


  },
  upload(e){

    this.setData({itemId:e.currentTarget.dataset.id});
    this.asyncFun(e.currentTarget.dataset.id)
  },
  asyncFun(id){
    this.setData({"fileList":[]})
    let uploadList = this.data.uploadOptions
    let newList = []
    let _this = this
    uploadList.map( res => {
      let oData = {
        tableId: id,
        tableName: "t_yinnong_moneyorder", //上传表
        bizPath: "yinnong",
        fileType: res.dictValue, //附件类型  1原始发票 2会议纪要 3会议照片 4 参会人员签字
        method:'GET'
      }
      UTIL.httpRequest(API.URL_GET_ATTACHMENTLIST, oData, {
        success: (rr) => {
          if(rr.code==200&&rr.rows.length>0){
            rr.rows.map((rrr,index) => {
              rrr.url = wx.getStorageSync('dressCode') + rrr.fileUrl
              if(index==rr.rows.length-1){
                newList.push(Object.assign({},res,{"list":rr.rows}))
                _this.setData({"fileList":_this.data.fileList.concat(newList)});
                _this.setData({"showUpload":true})
              }
            })
          }else{
            let newuploadList = uploadList
            newuploadList.map(rd => {
              rd.list = newList
            })
            _this.setData({"fileList":newuploadList});
            _this.setData({"showUpload":true})
          }
        },
        fail:(rr) =>{

        },
        complete:(rr) => {

        }
      })
    })
  },
  closeBox(){
    this.setData({"showUpload":false})
  },
  deleteImg(event){
    this.setData({"fileEvent":event})
    this.setData({"showPopup":true});
  },
  cancelTem:function(e){
    this.setData({"fileEvent":"{}"});
    this.setData({"showPopup":false});
  },
  confirmTem:function(e){
    let event = this.data.fileEvent
    UTIL.httpRequest(API.URL_GET_GETFILEREMOVE+event.detail.file.id , {method:'GET'}, {
      success: (res) => {
        if(res.code==200){
          let ll = this.data.fileList
          var jsonlist = ll[event.target.dataset.idx].list;
          jsonlist.splice(event.detail.index, 1)
          ll[event.target.dataset.idx].list = jsonlist
          this.setData({"fileList":ll})
          this.setData({showPopup:false});
          wx.showToast({
            title: '删除成功！',
            icon: 'success',
            duration: 2000,
          })
        }
      }
    })
  },
  uploadFile(uploadFile,event) {
    let _this = this
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: API.URL_GET_UPLOAD,
        filePath: uploadFile.file.file.url,
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data",//记得设置
          "chartset":"utf-8",
          'Authorization':'Bearer '+getApp().globalData.userInfo.token
        },
        formData:uploadFile,
        success: (res) => {
          res.data = JSON.parse(res.data);
          if(res.statusCode == 200){
            let files = _this.data.fileList
            let fName = res.data.fileUrl.split('/')
            let fLength = fName.length
            files[event.currentTarget.dataset.idx].list.push({
              "fileName": fName[fLength-1],
              "fileType": "0",
              "fileUrl":res.data.fileUrl ,
              "id": res.data.id,
              "tableId": 6,
              "url":wx.getStorageSync('dressCode')+res.data.fileUrl
            })
            _this.setData({"fileList":files})
            wx.hideLoading()
          }
        },
        fail: (err) => {
          //上传失败：修改pedding为reject
          reject(err)
        }
      });
    })
  },
  afterRead(event) {
    let _this = this
    wx.showLoading({
      title: '上传中...'
    })
    let fileForm={
      file: event.detail,
      fileType:event.currentTarget.dataset.idx,
      tableName: "t_yinnong_moneyorder", //上传表
        bizPath: "yinnong",
      tableId:_this.data.itemId
    }
    this.uploadFile(fileForm,event)
  },
  lookDown(file,detail){
    // 获取指定字符串最后一次出现的位置，返回index
    var index1 = file.detail.url.lastIndexOf('.');
    // substr(start, length) 抽取从start下标开始的length个字符，返回新的字符串;
    var style = file.detail.url.substr(index1 + 1)
    //判断图片类型，不需要下载，不做处理
    if(style=='png'||style=='jpg'||style=='jpeg'||style=='bmp'||style=='gif'||style=='webp'||style=='psd'||style== 'svg'||style=='tiff'){
      //判断非图片类型
    }else{
      wx.downloadFile({
        url: file.detail.url,
        success(data){
          wx.openDocument({
            filePath: data.tempFilePath,
            fileType: style,
            showMenu:true,
            success(res){
            }
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

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

  },

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

  },

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

  },

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

  }
})