const app = getApp();
Page({
  data: {
    isAuth: false,
    showAuthWin: false,
    showChaType: false,
    isPrem:false,
    device:false,
    modalHidden:true,
    region: [],
    systemMenu:[],
    isIcon:'N',
    seleteType:[{transportStatus:'00',transportStatusName:'入库'},{transportStatus:'10',transportStatusName:'出库'},{transportStatus:'20',transportStatusName:'结束'}],
    showDialog: false,// 详情弹窗
    showDialogChild: false,// 选择扫描 or 输入弹窗
    tableCoin: [{
        name: 'X201',
        img: '../../img/work_icon11.png',
        status: true,
        type: 'lableX201'
      },
      {
        name: 'X202',
        img: '../../img/X202.png',
        status: true,
        type: 'lableX202'
      },
      {
        name: 'X203',
        img: '../../img/work_icon11.png',
        status: true,
        type: 'lableX203'
      },
      {
        name: 'X101',
        img: '../../img/x1.png',
        status: true,
        type: 'lableX101'
      },
      {
        name: 'X102',
        img: '../../img/x102.png',
        status: true,
        type: 'lableX102'
      },
      {
        name: 'X103',
        img: '../../img/x2.png',
        status: true,
        type: 'lableX103'
      },
      {
        name: 'X104',
        img: '../../img/x1.png',
        status: true,
        type: 'lableX104'
      },
      {
        name: 'X105',
        img: '../../img/rfid.png',
        status: true,
        type: 'lableX105'
      },
      {
        name: 'X106',
        img: '../../img/x1.png',
        status: true,
        type: 'lableX106'
      },
      {
        name: 'X107',
        img: '../../img/x2.png',
        status: true,
        type: 'lableX107'
      },
    ],
  },
  onShow: function () {
    var that = this;
    //判断token，若有则假设已经登录
    if (wx.getStorageSync('token')) {
      wx.removeStorageSync('userInfo');
      app.requestP({
        url: "/user/getUserInfo",
      }).then(function(res){
        wx.setStorageSync('userInfo',res.data.data)
        that.setData({
          user : res.data.data
        })
        //获取菜单列表
        that.getMenu();
      }).catch(err=>{
        app.showToptip(that,'error',err.data.msg)
      })
      this.getUserDefaultMenuList();
    }else{
      //获取菜单列表
      that.getMenu();
    }
    //移除之前缓存的用户信息，确保拿到用户最新数据
    var tabarData = app.globalData.tabarData;
    if(Object.keys(tabarData).length !=0 ){
      const {loginRole, ifOverFlow, status, path} = tabarData;
      this.matchPage(loginRole,ifOverFlow,status,path);
    }
    var coinStatus = JSON.parse(wx.getStorageSync('labelStatus'));
    console.log(coinStatus)
    var tableCoin = this.data.tableCoin;
    var temp = '';
    tableCoin.map((coinType, index) => {
      Object.keys(coinStatus).forEach(key => {
        if (key == coinType.type) {
          temp = 'tableCoin[' + index + '].status'
          this.setData({
            [temp]: coinStatus[key]
          })
        }
      })
    })
  },
    /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    app.globalData.tabarData = {};
  },
  tapMenu(e) {
    let type = e.currentTarget.dataset.type
    let path = e.currentTarget.dataset.path
    //判断token，若有则假设已经登录
    if (!wx.getStorageSync('token')) {
      wx.redirectTo({
        url: '/pages/login/login',
      })
      return;
    }
    //获取用户信息，判断userInfo是否过期
    let userInfo = wx.getStorageSync('userInfo');
    /**
     * status: 用户角色审核状态
     *        0  没有选择任何角色也没做任何认证
     *        10 审核中
     *        20 审核通过
     * ifOverFlow:是否通过验证
     *            N 没有选择角色
     *            Y 已选择角色
     *            非register时，如果是Y说明已经处于认证状态
     *            admin创建企业，personnel选择了企业
     * loginRole:用户权限
     *          admin 管理员
     *          doctor 医生
     *          register 自由注册  可申请为操作员
     *          personnel 操作员  已选择企业未认证
     *          
     */
    const {loginRole,ifOverFlow,status} = userInfo;
    this.matchPage(loginRole,ifOverFlow,status,path);
  },
  matchPage(loginRole,ifOverFlow,status,path) {
    if(path == 'localSetting'){ //本地设置无任何权限
      wx.navigateTo({
        url: '/pages/setting/localSetting/localSetting',
      })
      return;
    }else if(path == 'scanSetting'){//扫描设置无任何权限
      wx.navigateTo({
        url: '/pages/setting/scanSetting/scanSetting',
      })
      return;
    }
    //判断是否选择角色
    if(loginRole == 'personnel' || loginRole == 'admin'){
      this.setData({path,loginRole});
      if(ifOverFlow == 'Y' && loginRole!='register'){
        if(status == 20){
          this.isAuth(path,loginRole);
        }else if(status == 10){
          app.showToptip(this,'worning','身份审核中，审核通过可以使用该功能');
        }else if(status == 0){
          app.showToptip(this,'worning','您还没有选择身份，请选择您的身份并提交认证');
          wx.navigateTo({
            url: '/pages/userAuth/chooseRole',
          })
        }
      }else if(ifOverFlow == 'N' && loginRole != 'register'){
        // this.isAuth(path);
        if(loginRole == 'personnel' && path != 'workerManager'){
          this.showModel('/pages/userAuth/workerSelect');
        }else if(loginRole == 'doctor' && path == 'find' || path == 'companyInfo'){
          this.showModel('/pages/userAuth/doctorInfo');
        }else if(loginRole == 'admin'){
          this.showModel('/pages/userAuth/adminInfo');
        }else{
          app.showToptip(this,'worning','您当前身份暂无权限');
        }
      }
    }else{
      this.setData({path,loginRole});
      app.showToptip(this,'worning','您还没有选择身份，请选择您的身份');
      wx.navigateTo({
        url: '/pages/userAuth/chooseRole',
      })
    }
  },
  isAuth(path,loginRole){
    //判断用户点击了哪个按钮
    if (loginRole == 'admin' || loginRole =='personnel'){
      if (path == "find") {
        //查一查
        this.showChaWin();
      } else if(path == 'orderList'){
        //订单列表
        wx.navigateTo({
          url: '/pages/workbench/orderList/orderList'
        })
      }else if (path == 'warningconfig') {
        //预警配置
        wx.navigateTo({
          url: '/pages/workbench/warningconfig/warningconfig'
        })
      } else if (path == 'coldChain') {
        //冷链管理
        wx.navigateTo({
          url: '/pages/workbench/tempList/tempList',
        })
      } else if (path == 'productManager') {
        //产品管理
        wx.navigateTo({
          url: '/pages/workbench/product/product'
        })
      } else if (path == 'commandSend') {
        //指令下发
        this.setData({
          isPrem: true
        });
      } else if (path == 'factorycheck') {
        //出厂检测
        this.device();
      } else if (path == 'iodep') {
        //出库入库
        this.showChaWin();
      } else if (path == 'companyInfo') {
        // 企业信息
        wx.navigateTo({
          url: '/pages/companyManager/companyInfo/companyInfo',
        })
      } else if (path == 'workerManager' && loginRole == 'admin') {
        //员工管理
        wx.navigateTo({
          url: '/pages/companyManager/companyUser/companyUser',
        })
      }else if(path == 'zyShop'){
        //中义商城
        wx.navigateTo({
          url: '/pages/zyShop/zyShop',
        })
      }else if(path == 'onAndOff'){
        // 激活锁闭
        app.showToptip(this,'worning','小程序暂不支持此功能，请移动到APP操作！');
      }else {
        app.showToptip(this,'worning','您当前身份暂无权限');
      }
    }else if(loginRole == 'doctor'){
      if (path == "find") {
        //查一查
        this.showChaWin();
      }else if (path == 'companyInfo') {
        // 企业信息
        wx.navigateTo({
          url: '/pages/companyManager/companyInfo/companyInfo',
        })
      } else{
        app.showToptip(this,'worning','您当前身份暂无权限');
      }
    }
  },
  getMenu() {
    const that = this;
    //如果有token,则去拉取菜单列表，相反则只显示界面
    var loginRole = '';
    if(wx.getStorageSync('token')){
      var user = this.data.user;
      console.log(user);
      loginRole = user.loginRole
    }
    app.requestP({
      needToken: false,
      url: "/query/listMenu",
      data:{
        roleKey:loginRole || '',
      }
    }).then(function (res) {
      that.setData({
        menuList: res.data.data
      })
    }).catch(err=>{
      app.showToptip(that,'error',err.data.msg)
    })
  },
  myevent(e){
    var that = this;
    var systemMenu = this.data.systemMenu;
    var arr = [];
    let userInfo = wx.getStorageSync('userInfo');
    systemMenu.map(item=>{
      arr.push(item.menuId)
    })
    this.setData({
      isIcon:e.detail.flag
    })
    if(e.detail.flag == 'N'){
      app.requestP({
        url:'/userDeaultMenu/add',
        method:'post',
        data:{
          userId:userInfo.userId,
          menuIds:arr
        }
      }).then(res=>{
        app.showToptip(that,'success',res.data.msg)
      }).catch(err=>{
        app.showToptip(that,'error',err.data.msg)
      })
    }
  },
  getUserDefaultMenuList(){
    var that = this;
    app.requestP({
      url:'/userDeaultMenu/list',
      method:'post',
    }).then(res=>{
      that.setData({
        systemMenu:res.data.data
      })
    }).catch(err=>{
      app.showToptip(that,'error',err.data.msg)
    })
  },
  iconJian(e){
    var that = this;
    var menuId = e.currentTarget.dataset.menuId;
    var index = e.currentTarget.dataset.index;
    var systemMenu = this.data.systemMenu;
    var arr = systemMenu;
    arr.splice(index,1);
    this.setData({
      systemMenu:arr
    })

  },
  iconJia(e){
    var that = this;
    var systemMenu = this.data.systemMenu;
    var menu = e.currentTarget.dataset.menu;
    if(systemMenu.length >= 4){
      app.showToptip(this,'error','常用功能按钮最多为4个')
    }else{
      for(var i=0;i<systemMenu.length;i++){
        if(systemMenu[i].menuId == menu.id){
          app.showToptip(that,'error','已经有该按钮，请勿重复选择')
          return;
        }
      }
      var arr = systemMenu;
      arr.push({...menu,menuName:menu.label,menuId:menu.id,});
      this.setData({
        systemMenu:arr
      })
    }
    console.log(systemMenu);
  },
  getUser() {
    const that = this
    //去拉取用户数据
    app.requestP({
      url: "/user/getUserInfo",
    }).then(function (res) {
      wx.setStorageSync('userInfo', res.data.data)
      that.setData({
        user: res.data.data
      })
    })
  },
  //权限弹窗控制
  showAuthWin() {
    this.setData({
      showAuthWin: true
    })
  },
  closeAuthWin() {
    this.setData({
      showAuthWin: false
    })
  },
  //查一查弹框控制
  showChaWin() {
    this.setData({
      showChaType: true
    })
  },
  closeChaWin() {
    this.setData({
      showChaType: false,
      device:false
    })
  },
  device(){
    this.setData({
      device: true
    })
  },
  //开启扫码系统
  goScan(e) {
    var type = e.currentTarget.dataset.item;
    var that = this;
    var {path,devicetype} = that.data;
    wx.scanCode({
      success: function (res) {
        var {result} = res;
        if(result.indexOf('imei=') != -1){
          result = result.slice(result.indexOf('imei=')+5,result.length)
        }
        if(path == 'find'){
          if(that.data.loginRole == 'doctor'){
            wx.navigateTo({
              url: '/pages/workbench/scanningType/scanningType?inoculatorId='+result+'&path='+path,
            })
          }else{
            that.searchChainCheckBind(result).then(res=>{
              var id = res.data.msg;
              that.closeChaWin()
              that.setData({
                showDialog:!that.data.showDialog,
                detailId:id,
                showDialogChild:!that.data.showDialogChild,
                deviceCode:result //867992041247453
              })
            })
          }
        }else if(path == 'factorycheck'){
          wx.navigateTo({
            url: '/pages/device/info?imei='+result+'&devicetype='+devicetype,
          })
        }else if(path == 'iodep'){
          that.searchChainCheckBind(result).then(res=>{
            const {transportStatus,id,code} = res.data.chain;
            that.setData({
              transportStatus,
              iodepId:id,
              modalHidden:!that.data.modalHidden,
              showDialogChild:!that.data.showDialogChild,
              seleteType:that.setSeleteType(transportStatus),
            });
          })
        }
      },
      fail:function(err){
        app.showToptip(that, 'error', '二维码无效');
      }
    })
  },
  // 查询当前冷链是否绑定
  searchChainCheckBind(result){
    var that = this;
    return new Promise((resolve,reject)=>{
      app.requestP({
        url:'/chainBound/checkBind',
        method:'post',
        data:{
          deviceCode:result,
        }
      }).then(res=>{
        if(res.data.data != 1){
          app.showToptip(that,'error',res.data.msg);
          return;
        }
        app.requestP({
          url:'/chain/scan',
          method:'post',
          contentType:' application/json',
          data:{
            inoculatorId:'',
            payload:result,
            type:that.data.devicetype,
          }
        }).then(res=>{
          resolve(res)
        }).catch(err=>{
          reject()
          app.showToptip(that,'error',err.data.msg);
        })
      }).catch(err=>{
        reject()
        app.showToptip(that,'error',err.data.msg);
      })
    })
  },
  setTransportStatus(transportStatus){
    var seleteType = this.data.seleteType;
    var deptType;
    for(var i=0;i<seleteType.length;i++){
      if(seleteType[i].transportStatus == transportStatus){
        deptType = i;
        break;
      }
    }
    return deptType;
  },
  setSeleteType(transportStatus){
    var seleteType = this.data.seleteType;
    var type;
    for(var i=0;i<seleteType.length;i++){
      if(seleteType[i].transportStatus == transportStatus){
        seleteType.splice(i,1);
        break;
      }
    }
    this.setTransportStatus(transportStatus);
    return seleteType;
  },
  closePremWin(){
    this.setData({
      isPrem:false,
      iptValue:''
    })
  },
  setValue:function (e){
    const that = this;
    var iptValue = e.detail.value.substr(0,6)
    this.setData({
      iptValue
    })
    if(iptValue.length>=6){
      app.requestP({
        url:'/commandAuth/checkPremise',
        method:'post',
        data:{
          password:iptValue
        }
      }).then(res=>{
        this.setData({
          isPrem:false,
          iptValue:''
        })
        wx.navigateTo({
          url: '/pages/instruct/instruct',
        })
      }).catch(err=>{
        this.setData({
          isPrem:false,
          iptValue:''
        })
        app.showToptip(that, "error",err.data.msg);
      })
    }
  },
  setModalVal(e){
    this.setData({
      modalVal:e.detail.value
    })
  },
  modalBindaconfirm(){  //二型保存地址
    var that = this;
    var {region,modalVal,transportStatus,iodepId,seleteType,deptType} = that.data;
    var addr = region.join('')+modalVal;
    if(region.join('') && modalVal && seleteType[deptType].transportStatus){
      app.requestP({
        url:'/chain/editTransport',
        // contentType:' application/json',
        method:'post',
        data:{
          addr,
          chainId:iodepId,  
          transportStatus:seleteType[deptType].transportStatus, // 00 已入库 //10 已出库 //20 已结束
        }
      }).then(res=>{
        that.setData({
          modalHidden:!that.data.modalHidden,
          region:[],
          modalVal:'',
          iodepId:'',
          deptType:'',
          seleteType:[{transportStatus:'00',transportStatusName:'入库'},{transportStatus:'10',transportStatusName:'出库'},{transportStatus:'20',transportStatusName:'结束'}],
        })
        app.showToptip(that,'success',res.data.msg);
      }).catch(err=>{
        app.showToptip(that,'error',err.data.msg);
      })
    }else{
      app.showToptip(that,'error','地址和运输状态不能为空');
    }
  },
  //取消按钮点击事件
  modalBindcancel:function(){
    this.setData({
      modalHidden:!this.data.modalHidden,
      region:[],
      modalVal:'',
      iodepId:'',
      deptType:'',
      seleteType:[{transportStatus:'00',transportStatusName:'入库'},{transportStatus:'10',transportStatusName:'出库'},{transportStatus:'20',transportStatusName:'结束'}],
    })
  },
  regionChange: function(e) {
    this.setData({
      region: e.detail.value
    })
  },
  showModel(url){ //提示弹框
    wx.showModal({
      title: '您还未认证，暂无权限',
      // content: '确定要删除该图片？',
      showCancel: true, //是否显示取消按钮
      cancelText: "取消", //默认是“取消”
      cancelColor: '#000', //取消文字的颜色
      confirmText: "去认证", //默认是“确定”
      confirmColor: '#2D59E6', //确定文字的颜色
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          //点击去认证
          wx.navigateTo({
            url: url,
          })
        }
      },
      fail: function (res) {}, //接口调用失败的回调函数
      complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  setType(e){
    var value = e.detail.value;
    var that = this;
    that.setData({
      deptType:value
    })
  },
  toggleDialog() { //详情弹窗
    this.setData({
      showDialog: !this.data.showDialog,
      devicetype:''
    });
  },
  goDetail(){
    var detailId = this.data.detailId;
    var deviceCode = this.data.deviceCode;
    wx.navigateTo({
      url: '/pages/workbench/hierarchy/hierarchy?id='+detailId+'&deviceCode='+deviceCode,
    })
    this.setData({
      showDialog:!this.data.showDialog,
      devicetype:''
    })
  },
  clearBind(){
    var that = this;
    var detailId = that.data.detailId;
    var deviceCode = that.data.deviceCode;
    app.requestP({
      url:'/chainBound/unbind',
      method:'post',
      contentType:' application/json',
      data:{
        chainId:detailId,
        deviceCode,
      }
    }).then(res=>{
      that.setData({
        detailId:'',
        showDialog:!that.data.showDialog,
      })
      app.showToptip(that,'success',res.data.msg)
    }).catch(err=>{
      app.showToptip(that,'error',err.data.msg)
    })
  },
  isScan(){
    //goScan
    this.setData({
      showDialogChild:!this.data.showDialogChild
    })
  },
  inputBind(){
    var that = this;
    var {path,devicetype} = that.data;
    wx.showModal({
      title: '请输入标签编号',
      editable:true,
      success (res) {
        if (res.confirm) {
          var numreg = /^[0-9]*$/;
          if(res.content){
            if(!numreg.test(res.content)){
              app.showToptip(that, "error", "标签编号只能为数字！");
              that.inputBind()
              return;
            }
            if(path == 'factorycheck'){
              wx.navigateTo({
                url: '/pages/device/info?imei='+res.content+'&devicetype='+devicetype,
              })
            }else if(path == 'iodep'){
              that.searchChainCheckBind(res.content).then(result=>{
                const {transportStatus,id,code} = result.data.chain;
                that.setData({
                  transportStatus,
                  iodepId:id,
                  modalHidden:!that.data.modalHidden,
                  showDialogChild:!that.data.showDialogChild,
                  seleteType:that.setSeleteType(transportStatus),
                });
              })
            }else if(path == 'find'){
              that.searchChainCheckBind(res.content).then(result=>{
                var id = result.data.msg;
                that.closeChaWin()
                that.setData({
                  showDialog:!that.data.showDialog,
                  detailId:id,
                  showDialogChild:!that.data.showDialogChild,
                  deviceCode:res.content //867992041247453
                })
              })
            }
          }else{
            app.showToptip(that, "error",'标签编号不能为空！')
            that.inputBind()
          }
        }else{
          //pass
        }
      }
    })
  },
  downDialog() { //弹窗关闭
    this.setData({
      showDialogChild: !this.data.showDialogChild,
      devicetype:''
    });
  },
  goScanSetting(e) {
    var type = e.currentTarget.dataset.type
    var uris = type?"?from="+type:""
    wx.navigateTo({
      url: '/pages/setting/scanSetting/scanSetting'+uris,
    })
  },
  addChain(e) {
    const type = e.currentTarget.dataset.type;
    const path = this.data.path;
    const noAdd = ['lableX101', 'lableX102', 'lableX103', 'lableX105', 'lableX106', 'lableX107','NFC'];
    if (noAdd.indexOf(type) != -1) {
      app.showToptip(this, 'error', '该标签暂不支持在小程序操作，请移动到APP操作！')
      return;
    }
    // 104 一型无源
    switch (type) {
      case 'lableX104':
        wx.navigateTo({
          url: '/pages/nfc/zhuisu2?path='+path+'&type=X104&loginRole='+this.data.loginRole,
        })
        break;
      default:
        this.setData({
          showDialogChild:!this.data.showDialogChild,
          devicetype:type.substr(5)
        })
        break;
    }
  },
  toggleDialog() { //弹窗关闭
    this.setData({
      showDialog: !this.data.showDialog,
      devicetype:''
    });
  },
})