// pages/fixedAssets/fixedAssets.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:[]
  },
  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_view").boundingClientRect()
    qu.select("#top_ban").boundingClientRect()
    qu.exec(res => {
      that.setData({
        scrollHeight:wx.getSystemInfoSync().windowHeight-res[0].height-res[0].top
      })
    })
    //获取附件字典
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'common_attach', {method:'GET'}, {
      success: (res) => {
        if(res.data.length>0){
          this.setData({
            uploadOptions:res.data,
          })
        }
      }
    })
    this.getList();
  },

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

    
  },
  getList:function(){
    let params = {
      pageNum:this.data.pageNums,
      pageSize:10,
      name:this.data.name
    }
    UTIL.httpRequest(API.URL_GET_PERMANENTLIST,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.originalValue =   Number(rr.originalValue ).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();
  },
  goUpdate(e){
    wx.navigateTo({
      url: '/pages/fixedAssets/add/add?id='+e.currentTarget.dataset.id,
    })
  },
  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){
    wx.navigateTo({
      url: '/pages/fixedAssets/change/change?id='+e.currentTarget.dataset.id,
    })
  },
  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_PERMANENTDELETE + this.data.itemId , {method:'GET'}, {
      success: (res) => {
        if(res.code==200){
          let new_list = this.data.list
          new_list.splice(this.data.index,1)
          this.setData({'list':new_list})
          UTIL.showToastNoneIcon('删除成功！');
        }else{
          UTIL.showToastNoneIcon('删除失败！');
        }
      }
    })
  },
  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_asset_permanent", //上传表
        bizPath: "asset",
        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
              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})
  },
  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_asset_permanent", //上传表
      bizPath: "asset",
      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() {
    this.setData({'pageNums':1})
    this.getList();
  },

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

  },

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

  },

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

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

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

  }
})