// pages/bank/bank.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,
    showPopupDel:false,
    showRelevance:false,
    relevanceList:[],
    fileEvent:{},
    itemId:"",
    contractionId:""
  },
  goAdd(){
    wx.navigateTo({
      url: 'add/add',
    })
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    let qu = wx.createSelectorQuery()
    qu.select("#top_view").boundingClientRect()
    qu.select("#top_ban").boundingClientRect()
    qu.exec(res => {
      that.setData({
        scrollHeight:wx.getSystemInfoSync().windowHeight-res[0].height-res[0].top
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getList();
    //获取附件字典
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'common_attach', {method:'GET'}, {
      success: (res) => {
        if(res.data.length>0){
          this.setData({
            uploadOptions:res.data,
          })
        }
      }
    })
  },
  getList:function(){
    let _this = this
    let params = {
      pageNum:this.data.pageNums,
      pageSize:10,
      name:this.data.name
    }
    UTIL.httpRequest(API.URL_GET_CONTRACTLIST,params,{
      success: (res) => {
        if(res.code == 200){
          if(this.data.pageNums!=1&&this.data.list.length<res.total){
            res.rows.map((rr,index) => {
              rr.totalAmount =   Number(rr.totalAmount ).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
                return $1 + ","; }).replace(/\.$/, "") 
                if(index==(res.rows.length-1)){
                  let lists = this.data.list.concat(res.rows)
                  _this.setData({list:lists})
                }
            })
          }else if(this.data.pageNums==1){
            res.rows.map((rr,index) => {
              rr.totalAmount =   Number(rr.totalAmount ).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
                return $1 + ","; }).replace(/\.$/, "") 
                if(index==(res.rows.length-1)){
                  _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.getList();
  },
  goUpdate(e){
    this.setData({
      "itemId":"",
      "itemIndex":"",
      "contractionId":""
    });
    wx.navigateTo({
      url: '/pages/contract/add/add?id='+e.currentTarget.dataset.id,
    })
  },
  addAssets(e){
    wx.navigateTo({
      url: '/pages/contractAssets/fixedAssets?id='+this.data.contractionId,
    })
  },
  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_CONTRACTDELETE+this.data.itemId , {method:'GET'}, {
      success: (res) => {
        if(res.code==200){
          let new_list = this.data.list
          new_list.splice(this.data.itemIndex,1)
          this.setData({'list':new_list})
          UTIL.showToastNoneIcon('删除成功！');
        }else{
          UTIL.showToastNoneIcon('删除失败！');
        }
      }
    })
  },
  relevanceBack(){
    let params = {
      contractionId:this.data.contractionId
    }
    UTIL.httpRequest(API.URL_GET_ASSETLIST, params, {
      success: (rr) => {
        this.setData({
          'revelanceList':rr.rows,
          'showRelevance':true
        })
      },
    })
  },
  terminate(e){
    UTIL.httpRequest(API.URL_GET_TERMINATEINFO+ e.currentTarget.dataset.id, {method:'GET'}, {
      success: (res) => {
        if(res.code==200){
          let list = this.data.list
          list[e.currentTarget.dataset.index].contractionStatus = '3'
          this.setData({'list':list})
          UTIL.showToastNoneIcon('终止成功！');
        }else{
          UTIL.showToastNoneIcon('终止失败！: '+res.msg);
        }
      }
    })
},
  cancel(e){
    UTIL.httpRequest(API.URL_GET_CANCELINFO+ e.currentTarget.dataset.id, {method:'GET'}, {
    success: (res) => {
      if(res.code==200){
        let list = this.data.list
        list[e.currentTarget.dataset.index].contractionStatus = '2'
        this.setData({'list':list})
        UTIL.showToastNoneIcon('撤销成功！');
      }else{
        UTIL.showToastNoneIcon('撤销失败！: '+res.msg);
      }
    }
  })
},
  relevanceDelete(e){
      UTIL.httpRequest(API.URL_GET_ASSETREMOVE+ e.currentTarget.dataset.id, {method:'GET'}, {
        success: (res) => {
          if(res.code==200){
            let new_list = this.data.revelanceList
            new_list.splice(e.currentTarget.dataset.index,1)
            this.setData({'revelanceList':new_list})
            UTIL.showToastNoneIcon('删除成功！');
          }else{
            UTIL.showToastNoneIcon('删除失败！');
          }
        }
      })
  },
  relevance(e){
    let params = {
      contractionId:e.currentTarget.dataset.id
    }
    UTIL.httpRequest(API.URL_GET_ASSETLIST, params, {
      success: (rr) => {
        this.setData({
          'revelanceList':rr.rows,
          'showRelevance':true,
          'contractionId':e.currentTarget.dataset.id
        })
      }
    })
  },
  upload(e){
    this.setData({itemId:e.currentTarget.dataset.id});
    this.asyncFun(e.currentTarget.dataset.id)
    this.setData({"fileList":[]})
  },
  asyncFun(id){
    let uploadList = this.data.uploadOptions
    let newList = []
    let _this = this
    uploadList.map( res => {
      let oData = {
        tableId: id,
        tableName: "t_contraction_info", //上传表
        bizPath: "contraction",
        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 = URL_PREFIX + 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})
          }
        }
      })
    })

  },
  closeBox(){
    this.setData({"showUpload":false})
    this.setData({"showRelevance":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":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_contraction_info", //上传表
      bizPath: "contraction", //上传目录
      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){
            }
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(this.data.contractionId!=""&&this.data.contractionId!=null){
      this.relevanceBack()
    }else{
      let _this = this
    let params = {
      pageNum:1,
      pageSize:10,
      name:this.data.name
    }
    UTIL.httpRequest(API.URL_GET_CONTRACTLIST,params,{
      success: (res) => {
        if(res.code == 200){
          res.rows.map((rr,index) => {
            rr.totalAmount =   Number(rr.totalAmount ).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
              return $1 + ","; }).replace(/\.$/, "") 
              if(index==(res.rows.length-1)){
                _this.setData({list:res.rows})  
              }
          })
        }else{
          UTIL.showToastNoneIcon(res.msg);
        }
      }
    })
    }
  },

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

  },

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

  },

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

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

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

  }
})