
<style rel="stylesheet/scss" lang="scss" scoped>
.title {
  margin: 30px auto 30px auto;
  text-align: center;
  width: 100%;
  line-height: 20px;
  height: 20px;
  font-size: 0.47222rem;
  font-family: Source Han Sans CN ,sans-serif;
  font-weight: 500;
  color: #006953d6;
}

.login {
  width: 100%;
  height: 1280px;
  position: absolute;
  top: 0;
  background-color: rgb(237, 237, 237);
  overflow: hidden;
}
::v-deep.van-cell {
  background-color: rgb(237, 237, 237);
}

.images {
  margin-top: 197px;
  margin-bottom: 100px;
  margin-left: 134px;
  margin-right: 133px;
  width: 453px;
  height: 149px;
}
.from_one {
  margin-top: 190px;
  background-color: rgb(237, 237, 237);
  width: 620px;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 130px;
}
.one_a {
  border-bottom: 1px solid #999;
  font-size: 30px;
  font-weight: 400;
  line-height: 30px;
  color: #919191;
}
.one_b {
  border-bottom: 1px solid #999;
  margin-top: 40px;
  font-size: 30px;
  line-height: 30px;
  font-weight: 400;
  color: #919191;
}
.a{
  background-color: #fff;
}
.btn {
  margin: 60px auto 0px;
  background-color: #04a175;
  height: 80px;
  width: 620px;
  border-radius: 41px;
  font-size: 28px;
  color: rgb(255, 255, 255);
}
</style>

<template>
  <div class="login" style="text-align: center">
    <div>
    <van-image
      position="left:50% right:50%"
      src="assets/logo.png"
      class="images"
      @click="gopage()"
    />
      <h1 class="title">{{title}}</h1>
    </div>
    <van-form @submit="onSubmit">
      <van-cell-group inset class="from_one">
        <van-field
          v-model="loginForm.username"
          name="用户名"
          placeholder="请输入用户名"
          :rules="rules.username"
          class="one_a"
        />

        <van-field
          v-model="loginForm.password"
          type="password"
          name="密码"
          placeholder="请输入密码"
          :rules="rules.password"
          class="one_b"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button block class="btn" :disabled="flag"  native-type="submit">
          登 录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { encrypt, decrypt } from "src/utils/jsencrypt";
// import { token } from "../../../api/requestfun/token";
import {Form, Field, Button, CellGroup, Cell, Image, Dialog, Notify} from "vant";
import {mapState, useStore} from "vuex";
import OpenDataWap from "@/common/nativeJSdk/OperData";
import {listSubsystem, updateSubsystem} from "@/api/qrcode/device/subsystem/subsystem";
import config from "../../../package.json";
import {uploadControlunit} from "@/api/qrcode/device/controlunit/controlunit";
import {getConfigByConfigKey} from "@/api/system/config";
import NativeQRCode from "@/common/nativeJSdk/native";
import request from "@/utils/request";
import sysRequest from "@/utils/sysRequest";
import {getToken} from "@/utils/auth";
import ScanOverlay from "@/components/overlay/scanOverlay/ScanOverlay";

export default {
  name: "Login",
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Image.name]: Image,
    [Dialog.name]: Dialog,
  },
  setup() {
    // 规则
    const rules = {
      username: [
        {
          required: true,
          message: "请输入用户名",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入密码",
        },
      ],
    };
    const title = import.meta.env.VITE_APP_TITLE
    return {
      title,
      rules
    };
  },
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        version: config.version,
        rememberMe: false,
        code: "",
        uuid: "",
      },
      flag :false,
      loading: false,
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      redirect: undefined,
    };
  },
  computed: {
    ...mapState("sysConf", ["runMode"]),
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    // 获取cookies
    this.getCookie();
    this.$nativeQRCode.setStatusBarColor("#ededed", "black");
  },
  methods: {
    // 用户登录
    userLogin(val) {
      this.$store
          .dispatch("Login", this.loginForm)
          .then(() => {
            // 更新人员信息
            this.$store.dispatch("GetInfo");
            this.flag = false
            // console.log(this.runMode)
            if (val == 1){
              this.$router.push({ name: this.runMode }).catch(() => {});
            }
            // this.$router.replace({name: this.runMode}).catch(() =>{})
            // this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
          })
          .catch((error) => {
            this.loading = false;
            this.flag = false
            Dialog.alert({
              title: "登录失败",
              // message: error + "",
              message:'账号或密码错误，请重新输入',
              confirmButtonColor: "rgba(0, 0, 0, 1)",
            }).then(() => {
              // on close
            });
          });
    },
    // 获取cookies
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");

      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        version: config.version,
      };
    },
    // 版本比较
    compareVersion(systemVersion, minVersion) {
      const systemParts = systemVersion.split('.').map(Number);
      const minParts = minVersion.split('.').map(Number);

      for (let i = 0; i < Math.max(systemParts.length, minParts.length); i++) {
        const sysNum = systemParts[i] || 0;
        const minNum = minParts[i] || 0;

        if (sysNum > minNum) {
          return true;
        } else if (sysNum < minNum) {
          return false;
        }
      }

      // 版本号前几位相同，比较长度
      return systemParts.length >= minParts.length;
    },
    // 登录
    onSubmit() {
      // token().then((res) => {
      //   Cookies.set("token", res.data.access_token, { expires: 30 });
      // });
      this.flag = true
      let key = "system.param.adaptive"
      getConfigByConfigKey(key).then((res)=>{
        let configValue = res.data.configValue
        let version = config.version;
        if (this.compareVersion(version,configValue)){
          var systemConfigPosJson = OpenDataWap.share.selectSystemConfigPoList();
          var systemConfigPos = JSON.parse(systemConfigPosJson);
          //拿到本地数据
          if(systemConfigPos.length>0 && systemConfigPos[0].version.toString()!=version.toString()){
            // const store1 = useStore();
            var systemConfig = systemConfigPos[0]
            listSubsystem({ authCode: systemConfig.authCode }).then((response) => {
              // 授权码获取产线信息
              // store1.dispatch("sysConf/setProductLine", response.rows[0]);
              self.form = response.rows[0];
              self.form.status = 1;
              self.form.subSystemRegisterStatus = 0;
              self.form.version = version;
              self.form.ip=systemConfig.ipAddress
              const controlunit = {
                "subSysName":response.rows[0].name,
                "subSysCode":response.rows[0].code,
                "subSysId":response.rows[0].id,
                "deviceSN": systemConfig.deviceSN,
                "unitModel": systemConfig.unitModel,
                "unitTypeCode":"CE020103",
                "unitTypeName":"PDA"
              }
              const system = {
                cloudAddress:systemConfig.cloudAddress,
                authCode:systemConfig.authCode,
                code:response.rows[0].code,
                name:response.rows[0].name,
                ipAddress:systemConfig.ipAddress,
                runMode:"box",
                version:version,
                unitModel:systemConfig.unitModel,
                deviceSN:systemConfig.deviceSN,
              }
              // 添加设备到 厂级
              uploadControlunit(controlunit).then(res => {
                if (res.code==500){
                  Notify({type: 'warning', message: '该子系统已被注册或SN不正确', duration: 1500});
                }else {
                  //注册信息保存到本地
                  updateSubsystem(self.form).then((response) => {});
                  OpenDataWap.share.insertSystemConfigPo(JSON.stringify(system));
                }
              })
            });
          }
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          // 人员登陆
          this.userLogin(1);
        }else {
          this.userLogin(2);
          Dialog.confirm({
            title: "操作失败",
            // message: error + "",
            message:'PDA版本不匹配边侧系统，请升级新版本后重试',
            confirmButtonText: "升级",
            confirmButtonColor: "rgba(0, 0, 0, 1)",
          }).then(() => {
            ScanOverlay.show('正在下载...')
            let token = getToken();
            NativeQRCode.downloadNewVersion(sysRequest.defaults.baseURL+"/file/pda/download?fileName=app-release.apk",token)
            setTimeout(()=>{
              ScanOverlay.hide()
            },2500)
          })
        }
      }).catch(()=>{
        this.flag = false
        Notify({type: 'danger', message: '后端接口连接异常', duration: 1500});
      })
    },
  },
};
</script>
