<template>
	<view class="login-container">
	<view class="login-title">
		<view class="title">欢迎登录丹阳安全，</view>
		<view class="p">企业安全</view>
		<view class="p" style="margin-top: 0;">生产主体责任落实管理平台</view>
	</view>
		<view class="login-main">
			<view class="input-item">
				<view class="lable">手机号码</view>
				<view class="m-input-view">
					<input @input="userNameinp" class="m-input" placeholder-style="color: #999;font-size: 34upx;" placeholder="请输入手机号..." />
				</view>
			</view>
			<view class="input-item">
				<view class="lable">密码</view>
				<view class="m-input-view">
					<input @input="userPwdinp" class="m-input" placeholder-style="color: #999;font-size: 34upx;" password type="text" placeholder="请输入密码..." />
				</view>

			</view>
			<view class="btn-row">
				<button class="cu-btn" @click="$noMultipleClicks(login)">登 录</button>
			</view>
      <view class="tips">
        本平台为互联网非涉密平台，严禁处理、传输国家秘密和工作秘密
      </view>
		</view>
	</view>
</template>

<script>
  import { decryptAes } from "@/common/aesUtil";
	import {
		basePath,
		setloginUserId,
		setCorpinfoId,
		setloginUser,
		setDeptId,
		setDeptLevel,
		adminPath,
		corpinfoId,
		setBasePath,
		setIsRest,
		isRest,
		loginUser,
    setPremission,
    publicKey
	} from '@/common/tool.js';
  import JSEncrypt from '../../static/js/jsencrypt.min'
	export default {
		data() {
			return {
				noClick:true,
				userName : '',
				userPwd: '',
        push_clientid:'',
        radio:'1'
			}
		},
		async onLoad() {
      /*uni.getPushClientId({
        success: (res) => {
          console.log('res', res)
          this.push_clientid = res.cid
          this.getLoginUser()
          console.log('客户端推送标识:',res.cid)
        },
        fail(err) {
          uni.showToast({
            icon: 'none',
            title: "获取用户标识失败,请重新登录",
            duration: 2000
          });
        }
      });*/
      this.getLoginUser()
			//this.getUrlVersion();
		},
		methods: {
		  getLoginUser(){
        uni.getStorage({
          key: 'USER',
          success: (res) => {
            if(res.data && res.data.USER_ID){

              setloginUserId(res.data.USER_ID);
              setCorpinfoId(res.data.CORPINFO_ID);
              setDeptId(res.data.DEPARTMENT_ID);
              setDeptLevel(res.data.DEPARTMENT_LEVEL);

              setloginUser(res.data);
              // 查看是否离岗
              uni.request({
                url: basePath+'/app/offduty/isRest',
                method: 'POST',
                dataType: 'json',
                header:{
                  'Content-type':'application/x-www-form-urlencoded'
                },
                data: {
                  CORPINFO_ID:corpinfoId,
                  USER_ID:loginUser.USER_ID,
                },
                success: (res1) => {
                  res1.data = decryptAes(res1.data);
                  this.updatePushCid(res.data.USER_ID,this.push_clientid )
                  if (res1.data.ISREST != null) {
                    setIsRest(res1.data.ISREST);
                  } else {
                    setIsRest(res.data.ISREST);
                  }


                },
                fail: (res2) => {
                  uni.showToast({
                    icon: 'none',
                    title: "服务器正在升级，请稍后再试。",
                    duration: 2000
                  });
                }
              });
              uni.navigateTo({
                url: '/pages/index/index',
              });
            }
          }
        });
      },

      radioChange(){
        if(this.radio) this.radio = ''
        else this.radio = '1'
      },

			userNameinp(e) {
				this.userName = e.detail.value
			},
			userPwdinp(e) {
				this.userPwd = e.detail.value
			},
			login() {
        if(this.radio !== '1'){
          uni.showToast({
            title:'请先阅读并同意《服务协议》和《隐私政策》',
            icon:'none'
          })
          return;
        }
				var _this = this;
				var userName = _this.userName;
				var userPwd = _this.userPwd;
        var jsencrypt = new JSEncrypt()
        jsencrypt.setPublicKey(publicKey)
        const keydataVal = jsencrypt.encrypt('zcloudchina' + userName + ',zy,' + userPwd)
				// var keydataVal = 'zcloudchina' + userName + ',zy,' + userPwd;


				var myreg = /^(((13[0-9]{1})|159)+\d{8})$/;

				if (userName == '') {
					uni.showToast({
						icon: 'none',
						title: '请输入用户名',
						duration: 2000
					});
					return;
				} else if(userName.length != 11 && !myreg.test(userName)){
					uni.showToast({
						icon: 'none',
						title: '手机号格式不正确',
						duration: 2000
					});
					return;
				}
				if (userPwd == '') {
					uni.showToast({
						title: '密码不能为空',
						icon: 'none',
						duration: 2000
					});
					return;
				}


				uni.showLoading({
					mask:true,
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/admin/check',
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						KEYDATA: keydataVal,
						SOURCE: '2',
						tm: new Date().getTime(),
					},
					success: (res) => {
            res.data = decryptAes(res.data);
						var result = res.data.result;
						if ("success" == result) {
							setloginUserId(res.data.USER_ID);
							setCorpinfoId(res.data.CORPINFO_ID);
							setDeptId(res.data.DEPARTMENT_ID);
							setDeptLevel(res.data.DEPARTMENT_LEVEL);
							setIsRest(res.data.ISREST);
							setloginUser(res.data);
							uni.setStorage({key: 'USER',data: res.data});
							this.getMenu()

              this.updatePushCid(res.data.USER_ID,this.push_clientid )
						} else if ("usererror" == result) {
							uni.showToast({
								icon: 'none',
								title: "用户名或密码有误",
								duration: 2000
							});
						} else if ("errorMsg" == result) {
							uni.showToast({
								icon: 'none',
								title: res.data.msg || "账号已被冻结，请联系管理员",
								duration: 2000
							});
						} else if ("error" == result) {
              uni.showToast({
                icon: 'none',
                title: "缺少参数",
                duration: 2000
              });
            } else if ("invalid" == result) {
							uni.showToast({
								icon: 'none',
								title: "账号已被冻结，请联系管理员",
								duration: 2000
							});
						} else if ("exception" == result) {
							uni.showToast({
								icon: 'none',
								title:  res.data.exception,
								duration: 2000
							});
						}

					},
					fail: (res) => {
						uni.showToast({
							icon: 'none',
							title: "服务器正在升级，请稍后再试。",
							duration: 2000
						});
					}
				})
			},
      getMenu(){
        var _this = this;
        uni.showLoading({
          title: '请稍候'
        })
        uni.request({
          url: basePath + '/app/main/index',
          method: 'POST',
          dataType: 'json',
          header: {
            'Content-type':'application/x-www-form-urlencoded'
          },
          data: {
            USER_ID:loginUser.USER_ID,
          },
          success: (res) => {
            res.data = decryptAes(res.data);
            if("success" == res.data.result){

              var menuList = res.data.menuList
              var premissionList = new Map()

              menuList.map(item=>{
                if(item.menu_NAME == '安全承诺' && item.hasMenu){
                  premissionList.set('commitment',true)
                  if(item.subMenu && item.subMenu.length>0){
                    item.subMenu.map(child=>{
                      if(child.menu_NAME == '公司级承诺公告' && child.hasMenu){
                        premissionList.set('commitment-company',true)
                      }
                      if(child.menu_NAME == '车间级承诺公告' && child.hasMenu){
                        premissionList.set('commitment-workshop',true)
                      }
                      if(child.menu_NAME == '班组级承诺公告' && child.hasMenu){
                        premissionList.set('commitment-team',true)
                      }
                    })
                  }
                }

                if (item.menu_NAME == '受限空间作业管理' && item.hasMenu) {
                  premissionList.set('eightWork', true)
                  premissionList.set('confinedspace', true)
                }
                if (item.menu_NAME == '动火作业管理' && item.hasMenu) {
                  premissionList.set('eightWork', true)
                  premissionList.set('hotwork', true)
                }
                if (item.menu_NAME == '高处作业管理' && item.hasMenu) {
                  premissionList.set('eightWork', true)
                  premissionList.set('high-work', true)
                }
                if (item.menu_NAME == '吊装作业管理' && item.hasMenu) {
                  premissionList.set('eightWork', true)
                  premissionList.set('hoisting', true)
                }
                if (item.menu_NAME == '盲板抽堵作业管理' && item.hasMenu) {
                  premissionList.set('eightWork', true)
                  premissionList.set('blind-board', true)
                }
                if (item.menu_NAME == '动土作业管理' && item.hasMenu) {
                  premissionList.set('eightWork', true)
                  premissionList.set('break-ground', true)
                }
                if (item.menu_NAME == '临时用电作业管理' && item.hasMenu) {
                  premissionList.set('eightWork', true)
                  premissionList.set('electricity', true)
                }
                if (item.menu_NAME == '断路作业管理' && item.hasMenu) {
                  premissionList.set('eightWork', true)
                  premissionList.set('open-circuit', true)
                }
                if (item.menu_NAME == '在线学习与考试' && item.hasMenu) {
                  premissionList.set('education', true)
                }

                if(item.menu_NAME == '设备设施管理' && item.hasMenu){
                  premissionList.set('speEquip',true)
                }
              })
              setPremission(Object.fromEntries(premissionList));
              uni.hideLoading();
              uni.showToast({
                title: "登录成功",
                duration: 1000
              });
              uni.redirectTo({
                url: '/pages/index/index'
              });
            } else {
              uni.showToast({
                title: res.data.message,
                duration: 2000
              });
            }
          },
          fail: (res) => {
            uni.showToast({
              icon: 'none',
              title: "服务器正在升级，请稍后再试。",
              duration: 2000
            });
          }
        });
      },
			getUrlVersion(){
				plus.runtime.getProperty(plus.runtime.appid, function (inf) {
					var _this = this;
					//  路径
					uni.request({
						url: basePath + '/app/versionurl/goUrlByVersion',
						method: 'POST',
						dataType: 'json',
						header:{
							'Content-type':'application/x-www-form-urlencoded'
						},
						data: {
							VERSION: inf.version,
						},
						success: (res) => {
              res.data = decryptAes(res.data);
							if (res.data.pd != null) {
								console.info(inf.version);
								setBasePath(res.data.pd.URL);
							}
						},
						fail: (res) => {
							uni.showToast({
								icon: 'none',
								title: "服务器正在升级，请稍后再试。",
								duration: 2000
							});
						}
					});
				});
			},
      updatePushCid(userId,pushCid){
        uni.request({
          url: basePath + '/app/user/updatePushCid',
          method: 'POST',
          dataType: 'json',
          header: {
            'Content-type':'application/x-www-form-urlencoded'
          },
          data: {
            USER_ID:userId,
            PUSH_CID:pushCid
          },
        });
      }
		}
	}
</script>

<style>
	.m-input-view .m-input {
		height: 100upx;
		line-height: 1;
		font-size: 36upx;
		border-bottom: 1upx solid #eee;
	}

	.login-container{
		width: 100%;
		height: 100vh;
		background:#ffffff url(../../static/login-bg.png) no-repeat top center;
		background-size: 100%;
	}
	.login-title{ padding: 50upx; color: #fff; font-size: 48upx; padding-top: 200upx;}
	.login-title .p{
		font-size: 36upx;
		margin-top: 20upx;
	}
	.login-main{
		width: 100%;
		background: #fff;
		padding: 50upx;
		box-sizing: border-box;
		border-radius: 50upx 50upx 0 0;
	}

	.input-item{
		width: 100%;
		margin-top: 40upx;
	}
	.input-item .lable{
		font-size: 40upx;
	}
	.btn-row{ width: 100%; margin-top: 40upx;}
	.btn-row .cu-btn{
		width: 100%;
		height: 90upx;
		background: #1082ff;
		color: #fff;
	}
  .tips{
    margin-top: 10px;
    font-size: 26upx;
    color: #ff0000;
    text-indent: 2em;
  }
</style>
