// pages/paymentManager/paymentManager.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,
    list:[],
    isLoading:false,
    pageNums:1,
    scrollHeight:"",
    name:"",
    showUpload:false,
    uploadOptions:[],
    fileList:[],
    showPopup:false,
    fileEvent:{},
    itemId:"",
    assetTypeOptions:[],
    option1: [
      { text: '支付状态', value: '' },
      { text: '待支付', value: '1' },
      { text: '银行受理', value: '3' },
      { text: '支付失败', value: '4' },
      { text: '部分失败', value: '5' },
    ],
    option2: [
      { text: '支出类别', value: '' },
      { text: '结算类', value: '1' },
      { text: '工程项目类', value: '2' },
      { text: '合同类', value: '4' },
      { text: '其他', value: '5' },
    ],
    option3: [
      { text: '申请类别', value: '' },
      { text: '银行卡转账', value: '1' },
      { text: '信用卡还款', value: '2' },
    ],
    value1: '',
    value2: '',
    value3: '',
  },
  goAdd(){
    wx.navigateTo({
      url: 'add/add',
    })
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  assetTypeDict(val){
    this.data.assetTypeOptions.map(res => {
      if(res.dictValue == val){
        return res.dictLabel
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    let qu = wx.createSelectorQuery()
    qu.select("#top_view1").boundingClientRect()
    qu.select("#top_ban").boundingClientRect()
    qu.exec(res => {
      that.setData({
        scrollHeight:wx.getSystemInfoSync().windowHeight-res[0].height-res[0].top
      })
    })

    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    //获取附件字典
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'bookkeeping_type', {method:'GET'}, {
      success: (res) => {
        if(res.data.length>0){
          this.setData({
            uploadOptions:res.data,
          })
        }
      }
    })
    
  },
  getList:function(){
    let params = {
      pageNum:this.data.pageNums,
      pageSize:10,
      name:this.data.name,
      paymentState:this.data.value1,
      capitalExpenditureType:this.data.value2,
      transferType:this.data.value3
    }
    UTIL.httpRequest(API.URL_GET_TRANSFERPAYLIST,params,{
      success: (res) => {
        let _this = this
        if(res.code == 200){
          if(this.data.pageNums!=1&&this.data.list.length<res.total){
            let lists = []
            res.rows.map((rr,index) => {
              rr.expenditureAmount =   Number(rr.expenditureAmount ).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
                return $1 + ","; }).replace(/\.$/, "") 
                if(index==(res.rows.length-1)){
                  lists = _this.data.list.concat(res.rows)
                }
            })
            
            //获取资产类别
            UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'asset_type', {method:'GET'}, {
              success: (r) => {
                if(r.data.length>0){
                  let li = lists.map( res => {
                    r.data.map(rr => {
                      if(res.assetType == rr.dictValue){
                        res.assetType = rr.dictLabel
                      }
                    })
                    return  res
                  })
                  _this.setData({list:li})
                }else{
                  _this.setData({list:lists})
                }
              }
            })
          }else if(this.data.pageNums==1){
            //获取资产类别
            UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'asset_type', {method:'GET'}, {
              success: (r) => {
                if(r.data.length>0){
                  let li = res.rows.map( ress => {
                    ress.originalValue =   Number(ress.originalValue ).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
                      return $1 + ","; }).replace(/\.$/, "") 
                    r.data.map(rr => {
                      if(ress.assetType == rr.dictValue){
                        ress.assetType = rr.dictLabel
                      }
                    })
                    return  ress
                  })
                  _this.setData({list:li})
                }else{
                  _this.setData({list:res.rows})
                }
              }
            })
          }
        }else{
          UTIL.showToastNoneIcon(res.msg);
        }
      }
    })
  },
  paging(){
    this.setData({
      pageNums:this.data.pageNums+1,
    })
    this.getList();
  },
  goSearch(e){
    this.setData({name:e.detail});
    this.setData({pageNums:1});
    this.getList();
  },
  toPay(e){
    wx.navigateTo({
      url: '/pages/pay/detail?id='+e.currentTarget.dataset.id+'&&ids='+e.currentTarget.dataset.ids,
    })
  },
  scrap(e){
    console.log(e.currentTarget.dataset.data.id,e.currentTarget.dataset.data.index);
    if(e.currentTarget.dataset.data.assetStatus != 1){
      UTIL.showToastNoneIcon('只允许修改资产状态为正常的资产!');
      return false;
    }else if(e.currentTarget.dataset.data.useType == 3){
      UTIL.showToastNoneIcon('使用状态为出租或出借不允许操作!');
      return false;
    }else{
      UTIL.httpRequest(API.URL_GET_UPDATERSCRAP + e.currentTarget.dataset.data.id , {method:'GET'}, {
        success: (res) => {
          if(res.code==200){
            let new_list = this.data.list
            new_list.splice(e.currentTarget.dataset.data.index,1)
            this.setData({'list':new_list})
            UTIL.showToastNoneIcon('报废成功！');
          }else{
            UTIL.showToastNoneIcon('报废失败！：'+res.msg);
          }
        }
      })
    }
  },
  sell(e){
    console.log(e.currentTarget.dataset.data.id,e.currentTarget.dataset.data.index);
    if(e.currentTarget.dataset.data.assetStatus != 1){
      UTIL.showToastNoneIcon('只允许修改资产状态为正常的资产!');
      return false;
    }else if(e.currentTarget.dataset.data.useType == 3){
      UTIL.showToastNoneIcon('使用状态为出租或出借不允许操作!');
      return false;
    }else{
      UTIL.httpRequest(API.URL_GET_UPDATERSALE + e.currentTarget.dataset.data.id , {method:'GET'}, {
        success: (res) => {
          if(res.code==200){
            let new_list = this.data.list
            new_list.splice(e.currentTarget.dataset.data.index,1)
            this.setData({'list':new_list})
            UTIL.showToastNoneIcon('出售成功！');
          }else{
            UTIL.showToastNoneIcon('出售失败！：'+res.msg);
          }
        }
      })
    }
  },
  change(e){
    var that = this ;
    that.setData({value:e.detail,pageNum:1})
    this.getList()
  },
  changeTab(e){
    var that = this ;
    that.setData({value1:e.detail,pageNum:1})
    this.getList()
  },
  changeTab2(e){
    var that = this ;
    that.setData({value2:e.detail,pageNum:1})
    this.getList()
  },

  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 _this = this
    uploadList.map( (res,idx) => {
      res.list=[]
      console.log(res);
      let oData = {
        tableId: id,
        tableName: "t_yinnong_transfer", //上传表
        bizPath: "transfer",
        fileType: res.dictValue, //附件类型  1原始发票 2会议纪要 3会议照片 4 参会人员签字
        method:'GET'
      }
      UTIL.httpRequest(API.URL_GET_ATTACHMENTLIST, oData, {
        success: (rr) => {
          if(rr.rows.length>0){
            rr.rows.map((rrr,index) => {
              rrr.url = URL_PREFIX + rrr.fileUrl
              rrr.name = rrr.fileName
              if(index==rr.rows.length-1){
                res.list = rr.rows
                let lis = uploadList
                lis[idx] = res
                _this.setData({"fileList":lis});
                _this.setData({"showUpload":true})
              }
            })
          }
          else{
            _this.setData({"showUpload":true})
          }
        }
      })
    })

  },
  closeBox(){
    this.setData({"showUpload":false})
  },
  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],
              "name":fName[fLength-1],
              "fileType": "0",
              "fileUrl":res.data.fileUrl ,
              "id": res.data.id,
              "tableId": 6,
              "url":URL_PREFIX+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_transfer", //上传表
      bizPath: "transfer",
      tableId:_this.data.itemId
    }
    this.uploadFile(fileForm,event)
  },
  lookDown(e){
    let file =e
    // 获取指定字符串最后一次出现的位置，返回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){
            }
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({'pageNums':1})
    this.getList();
  },

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

  },

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

  },

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

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

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

  }
})