// pages/apply/approval/approval.js
import * as UTIL from '../../../utils/util.js';
import * as API from '../../../utils/API.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIPX: app.globalData.isIPX,
    //事务总表对象
    item:{},
    detpId:"",
    itemId:"",
    active:0,
    result:[],
    show:false,
    showPopup:false,
    showPopup2:false,
    templateList:[],
    templateDetailList:[],
    groups:[],
    villages:[],
    towns:[],
    temName:"",
    temId:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    this.setData({
      itemId:options.id,
      deptId:options.deptId,
      form:JSON.parse(options.form)
    });
    console.log(JSON.parse(options.form));
    if(options.type == 'template'){
      let list = [];
      let array =  JSON.parse(options.applyOptions).approvalTemplateDetailList;
      let indexList ;
      UTIL.httpRequest(API.URL_GET_GETINFO, {method:'GET'}, {
        success: (res2) => {
          JSON.parse(options.applyOptions).approvalTemplateDetailList.map((rr,index )=> {
            if(rr.nickName == res2.user.nickName){
              indexList = index ;
            }else{
              list.push(rr.userId+"")
            }
          })

          

          console.log(array);
          array.map((rrr,index)=>{
            if(rrr.nickName == res2.user.nickName){
              array.splice(indexList,1)
            }
            rrr.name = index+1
          })
          this.setData({
            templateDetailList:array,
            result:list
          })
        }
      })
    }else{
      // this.townList();
      // this.villageList();
      this.getApprovalItemsById();
    }
    this.groupList();
    //this.getApprovalItemList();JSON.parse(options.array)
  },
  getApprovalItemsById(){
    let _this = this
    let url = API.URL_GET_APPROVALITEMSBYID+this.data.itemId
    wx.request({
      url,
      method:"GET",
      timeout: 60000,
      header: {
        'Authorization':'Bearer '+getApp().globalData.userInfo.token
      },
      success: function (response) {
        _this.setData({item:response.data.data})
        if(_this.data.item.templateId!=""&&_this.data.item.templateId!=null){
          _this.setData({item:response.data.data,temId:_this.data.itemId})
          let d = {
            method:"GET"
          }
          console.log(_this.data.itemId);
          UTIL.httpRequest(API.URL_GET_TEMPLATEDETAIL + _this.data.itemId, d, {
            success: (r) => {
              console.log(r);
              if (r.code == API.SUCCESS_CODE) {
                _this.setData({templateDetailList:r.rows});
                let list = []
                  r.rows.map(rr => {
                    list.push(rr.userId+"")
                  })
                  _this.setData({result:list})
              }
            }
          })
        }else {
          _this.getApprovalItemList()
        }
      }
    })
  },
  inputTem:function(e){
    console.log(e)
      this.setData({temName:e.detail.value})
  },
  inputTem2:function(e){
      this.setData({temName2:e.detail.value})
  },
  confirmTemNew(e){
    var that = this;
    let data={
      approvalTemplate:{
        name:that.data.temName2,
        type:1,
        dataType:0
      },
      approvalTemplateDetailList:that.data.templateDetailList,
      applyData:that.data.form
    }
    let dataList = {
      templateName:that.data.temName2,
      templateContent:JSON.stringify(data),
      method:"POST"
    }
    UTIL.httpRequest(API.URL_GET_GETTEMPLATEADD,dataList,{
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          wx.showToast({
            title: "保存成功！",
            duration: 2000,
            icon:"success"
          })
          setTimeout(function(){ 
            that.setData({showPopup2:false,temName2:''})
          },2000)
        }
      }
    })

  },
  confirmTem:function(e){
    if(this.data.result.length == 0){
      wx.showToast({
        title: "请选择审批人",
        duration: 2000,
        icon:"error"
      })
      return;
    }
    let data={
      approvalTemplate:{
        name:this.data.temName,
        type:1,
        dataType:0
      },
      approvalTemplateDetailList:this.data.templateDetailList,
      method:"POST"
    }
    UTIL.httpRequest(API.URL_POST_MOBILEADD,data,{
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          let list = this.data.templateList 
          list.push(res.data)
          wx.showToast({
            title: "保存成功！",
            duration: 2000,
            icon:"success"
          })
          this.setData({
            temId:res.data.id,
            templateList:list,
            temName:"",
            showPopup:false
          });
        }
      }
    })
  },
  cancelTem:function(e){
    this.setData({temName:"",showPopup:false});
  },
  cancelTemNew:function(e){
    this.setData({temName2:"",showPopup2:false});
  },
  upItem:function(e){
    let index = e.currentTarget.dataset.id
    let item = this.data.templateDetailList[index]
    let list = this.data.templateDetailList
    if(index>0&&index<=list.length){
      list.splice(index,1)
      list.splice(index-1,0,item)
      for(let i = 0;i< list.length;i++){
        list[i].name = i+1
      }
      this.setData({templateDetailList:list});
    }    
  },
  downItem:function(e){
    let index = e.currentTarget.dataset.id
    let item = this.data.templateDetailList[index]
    let list = this.data.templateDetailList
    if(index>=0&&index<list.length){
      list.splice(index,1)
      list.splice(index+1,0,item)
      for(let i = 0;i< list.length;i++){
        list[i].name = i+1
      }
      this.setData({templateDetailList:list});
    }  
  },
  getApprovalItemList:function(){
    let data={
        method:"GET"
    }
    UTIL.httpRequest(API.URL_GET_TEMPLATEDETAIL+this.data.itemId,data, {
      success: (r) => {
        if (r.code == API.SUCCESS_CODE) {
          this.setData({templateDetailList:r.data});
          let list = []
          r.data.map(rr => {
            list.push(rr.userId+"")
          })
          this.setData({result:list})
        }
      }
    })
  },
  chooseTemplate:function(e){
    var that = this ;
    let data = {
      method:"GET"
    }
    UTIL.httpRequest(API.URL_GET_GETINFO, {method:'GET'}, {
      success: (res2) => {
        if (res2.code == API.SUCCESS_CODE) {
          that.setData({
            username:res2.user.nickName,
          })
          UTIL.httpRequest(API.URL_GET_GETAPPROVALBYID+e.currentTarget.dataset.id, data, {
            success: (res) => {
              if (res.code == API.SUCCESS_CODE) {
                let list = [];
                console.log(res);
                let indexList ;
                for (let i = 0; i < res.data.length; i++) {
                  const element = res.data[i];
                  if(element.nickName == res2.user.nickName){
                    // res.data.splice(i,1);
                    indexList = i ;
                  }else{
                    list.push(element.userId+"")
                  }
                }
                res.data.map((rrr,index)=>{
                  
                  if(rrr.nickName == res2.user.nickName){
                    
                    res.data.splice(indexList,1)
                  }
                  rrr.name = index+1
                })
                console.log(list);
                this.setData({templateDetailList:res.data,result:list});
                this.closeBox();
              }
            }
          })
        }
      }
    })
    
  },
  deleteTemplate:function(e){
    let ids =e.currentTarget.dataset.id;
    let data = {
      id:ids,
      status:"1"
    }
    let url = API.URL_GET_MOBILEREMOVE
    let _this = this
    wx.request({
      url,
      method:"POST",
      timeout: 60000,
      data:data,
      header: {
        'Authorization':'Bearer '+getApp().globalData.userInfo.token
      },
      success: function (response) {
        console.log(e);
        console.log(response)
        _this.data.templateList.splice(e.currentTarget.dataset.index, 1); 
        wx.showToast({
          title: '禁用成功！',
          icon: 'success',
          duration: 2000
        })
        _this.setData({
          templateList : _this.data.templateList,
        })
        _this.getApprovalItemList()
      }
    })
  },
  townList:function(){
    let _this = this
    let url = API.URL_GET_TOWNINFOBYDEPTID+0
    wx.request({
      url,
      method:"GET",
      timeout: 60000,
      header: {
        'Authorization':'Bearer '+getApp().globalData.userInfo.token
      },
      success: function (response) {
        let d = {
          deptId:response.data.data.deptId,
          deptLevel:3,
          method:"GET"
        }
        UTIL.httpRequest(API.URL_GET_USERLIST,d,{
          success: (res) => {
            if (res.code == API.SUCCESS_CODE) {
              res.rows.map(rr => {
                rr.approvalLevel = 3
                rr.approvalType = 1
                rr.approvalOrder = 0
              })
              _this.setData({towns:res.rows});
            }
          }
        })
      }
    })
  },
  groupList:function(){
      let data = {
        method:"GET"
      }
    UTIL.httpRequest(API.URL_GET_USERLIST,data ,{
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          res.rows.map(rr => {
            rr.approvalLevel = 2
            rr.approvalType = 1
            rr.approvalOrder = 0
          })
          this.setData({groups:res.rows});
        }
      }
    })
    let parmes = {
      pageNum:'1',
      pageSize:'999',
      status:"0"
    }
    UTIL.httpRequest(API.URL_GET_TEMPLATELIST,parmes ,{
      success: (res) => {
        if (res.code == API.SUCCESS_CODE) {
          this.setData({templateList:res.rows});
        }
      }
    })
 
  },
  villageList:function(){
    let data = {
      deptId : this.data.deptId,
      deptLevel:2,
      method:"GET"
    }
  UTIL.httpRequest(API.URL_GET_USERLIST,data ,{
    success: (res) => {
      if (res.code == API.SUCCESS_CODE) {
        res.rows.map(rr => {
          rr.approvalLevel = 1
          rr.approvalType = 1
          rr.approvalOrder = 0
        })
        this.setData({villages:res.rows});
      }
    }
  })
},
  onChange(event) {
    let _this = this
    console.log(event);
    this.setData({result:event.detail})
    this.setData({templateDetailList:[]})
      let list = _this.data.templateDetailList
       for (let j in event.detail){
         let str = event.detail[j]
         for(let i in _this.data.groups){
          if(_this.data.groups[i].userId == str){
            let sin = _this.data.groups[i]
            list.push(sin)
            _this.setData({templateDetailList:list})
          }
        }
          for(let i in _this.data.villages){
            if(_this.data.villages[i].userId == str){
              let sin = _this.data.villages[i]
              list.push(sin)
              _this.setData({templateDetailList:list})
            }
        }
          for(let i in _this.data.towns){
            if(_this.data.towns[i].userId == str){
              let sin = _this.data.towns[i]
              list.push(sin)
              _this.setData({templateDetailList:list})
            }
        }
      
       }
       let li = this.data.templateDetailList
       
       console.log(li);
        li = li.filter(function(e,i,s){
          s[i].name = i+1
          s[i].approvalOrder = i+1
            return true
        })
      this.setData({templateDetailList:li})
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  save:function(){
    let _this = this
    let list = this.data.templateDetailList
    list = list.filter(function(e,i,s){
      s[i].name = i+1
        return true
    })
    for (let index = 0; index < list.length; index++) {
      list[index].approvalTemplateId = _this.data.itemId;
    }
    let url = API.URL_GET_GETAPPROVALPROCESSADD
    wx.request({
      url,
      data: list,
      method:"POST",
      timeout: 60000,
      header: {
        'Authorization':'Bearer '+getApp().globalData.userInfo.token
      },
      success: function (response) {
        wx.showToast({
          title: "保存成功！",
          duration: 2000,
          icon:"success"
        })
        setTimeout(function(){
          wx.reLaunch({
            url: '/pages/index/index'
          })
        },2000)
      },
    })
  },
  submit:function(){
    let _this = this
    if(this.data.templateDetailList.length==0){
      wx.showToast({
        title: "请选择审批人",
        duration: 2000,
        icon:"error"
      })
      return;
    }
      let data={
        approvalTemplate:{
          name:this.data.temName,
          type:1,
          dataType:1
        },
        approvalTemplateDetailList:this.data.templateDetailList,
        method:"POST"
      }
      let list = this.data.templateDetailList
      list = list.filter(function(e,i,s){
        s[i].name = i+1
          return true
      })
      for (let index = 0; index < list.length; index++) {
        list[index].approvalTemplateId = _this.data.itemId;
      }

      let url = API.URL_GET_GETAPPROVALPROCESSADD
      wx.request({
        url,
        data: _this.data.templateDetailList,
        method:"POST",
        timeout: 60000,
        header: {
          'Authorization':'Bearer '+getApp().globalData.userInfo.token
        },
        success: function (response) {
         _this.requestSubmit()
        },
      })
      // UTIL.httpRequest(API.URL_GET_GETAPPROVALPROCESSADD,this.data.templateDetailList,{
      //   success: (res) => {
      //     if (res.code == API.SUCCESS_CODE) {
      //       let list = this.data.templateList 
      //       list.push(res.data)
      //       this.setData({
      //         temId:res.data.id,
      //         templateList:list,
      //         temName:""
      //       });
      //       let item_ = this.data.item
      //       item_.templateId = res.data.id
      //       item_.method = "POST"
      //       _this.requestSubmit()
      //       // UTIL.httpRequest(API.URL_POST_APPROVALITEMSEDIT,item_,{
      //       //   success: (res) => {
      //       //     if (res.code == API.SUCCESS_CODE) {
                 
      //       //     }
      //       //   }
      //       // })
      //     }
      //   }
      // })
  },
  requestSubmit:function(){
    let url = API.URL_POST_APPROVALITEMSSUBMIT+this.data.itemId
      wx.request({
        url,
        method:"POST",
        timeout: 60000,
        header: {
          'Authorization':'Bearer '+getApp().globalData.userInfo.token
        },
        success: function (r) {
          if (r.data.code == API.SUCCESS_CODE) {
            wx.showToast({
              title: "提交成功！",
              duration: 2000,
              icon:"success"
            })
            setTimeout(function(){
              wx.reLaunch({
                url: '/pages/index/index'
              })
            },2000)
          }else{
            wx.showToast({
              title: "操作失败！",
              duration: 2000,
              icon:"error"
            })
          }
        },
      })
  },
  openBox:function(){
    var that = this ;
    that.setData({
      show: true,
    })
  },
  closeBox:function(){
    var that = this ;
    that.setData({
      show: false
    })
  },
  showPopup() {
    this.setData({ 
      showPopup: true,
      temName:""
     });
  },
  showPopupNew() {
    this.setData({ 
      showPopup2: true,
      temName:""
     });
  },

  onClose() {
    this.setData({ showPopup: false});
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})