<style scoped>
.title {
  height: 50px;
  line-height: 50px;
  padding-top: 57px;
  font-size: 36px;
  font-family: Source Han Sans CN,sans-serif;
  font-weight: 500;
  color: #1d1d1d;
  text-align: center;
}
#box {
  box-sizing: border-box;
  /* margin-top: 250px; */
  width: 720px;
  height: 1280px;
  padding-left: 30px;
  padding-right: 30px;
  padding-top: 250px;
  font-size: 28px;
}
.van-form {
  margin-top: 150px;
  background-color: rgb(237, 237, 237);
}
.van-field {
  background-color: rgb(237, 237, 237);
  border-bottom: 1px solid #cbcbcb;
  height: 100px;
  font-size: 28px;
  line-height: 100px;
  padding: 0;
}
.btns {
  margin: 160px auto 0px;
  background-color: #04a175;
  height: 80px;
  width: 620px;
  border-radius: 41px;
  font-size: 28px;
  color: rgb(255, 255, 255);
  border: none;
}
:deep(.van-cell__right-icon) {
  line-height: 100px;
  font-size: 30px;
}

</style>

<template>
  <div id="box">
    <h3 class="title">{{title}}</h3>
    <van-form @submit="onSubmit">
      <van-cell-group inset style="margin: 0">
        <van-field
            v-model="deviceSN"
            name="deviceSN"
            label="设备SN码"
            placeholder="请输入设备SN码"
            :rules="rules.deviceSN"

        />
        <van-field
          v-model="cloudAddress"
          name="cloudAddress"
          label="边侧地址"
          placeholder="请输入边侧地址"
          :rules="rules.cloudAddress"

        />
        <van-field
          v-model="authCode"
          name="authCode"
          label="子系统编码"
          placeholder="请输入当前子系统编码"
          :rules="rules.authCode"
        />
        <van-field
          v-model="unitModel"
          name="unitModel"
          label="电子设备型号"
          placeholder="请输入电子设备型号"
          :rules="rules.unitModel"
        />
        <van-field
            v-model="ipAddress"
            name="ipAddress"
            label="IP地址"
            placeholder="请输入IP地址"
            :rules="rules.ipAddress"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          class="btns"
        >
          注册
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { ref, watch,onMounted  } from "vue";
import {Form, Field, Button, CellGroup, Cell, Popup, Picker, Notify, Dialog} from "vant";
import { isCloudAdress, subSysToken } from "@/api/system/registerConfig";
import { mapMutations, useStore } from "vuex";
import { useRouter } from "vue-router";
import {
  listSubsystem,
  updateSubsystem,
} from "@/api/qrcode/device/subsystem/subsystem";
import { removeToken } from "@/utils/auth";
import config from "../../../../package.json";
import {uploadControlunit} from "@/api/qrcode/device/controlunit/controlunit";
import {getConfigByConfigKey} from "@/api/system/config";
import request from 'src/utils/request'
import NativeQRCode from "@/common/nativeJSdk/native";
import sysRequest from "@/utils/sysRequest";
import OpenDataWap from "@/common/nativeJSdk/OperData";


export default {
  name: "systemInit",
  components: {
    NativeQRCode,
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
  },
  setup() {
    const title = import.meta.env.VITE_APP_TITLE
    const type = import.meta.env.VITE_APP_TYPE
    const store1 = useStore();
    const route = useRouter();

    const columns = [
      { key: "box", value: "”盒条件“关联人工作业单元" },
      { key: "dlr", value: "“条零”关联人工作业单元" },
      // {key: 'pkg', value: '盒条系统'},
    ];
    // 系统模式
    const result = ref({ key: "box", value: "“盒条件”关联人工作业单元" });
    // 厂级系统ip+端口
    const cloudAddress =
      ref(store1.state.sysConf.cloudServerAddress) || ref("");
    // 授权码
    const authCode = ref(store1.state.sysConf.authCode) || ref("");

    // sn
    const deviceSN = ref(store1.state.sysConf.deviceSN) || ref("");
    // 电子设备型号
    const unitModel = ref(store1.state.sysConf.unitModel) || ref("");
    // ip
    const ipAddress = ref(store1.state.sysConf.ipAddress) || ref("");
    const showPicker = ref(false);
    // const ip = ref("");

    // 判断授权码
    const unitAuthCode = (value) => {
      return store1
        .dispatch("sysConf/SetAuthCode", value)
        .then((res) => {
          // console.log(res)
          return true;
        })
        .catch((err) => {
          console.log(err);
          return false;
        });
    };
    // 检测ip格式
    const ipAddressCheck = (value) => {
      return store1
          .dispatch("sysConf/SetIpAddress", value)
          .then((res) => {
            return true;
          })
          .catch((err) => {
            Notify(err)
            return false;
          });
    };
    // function getWifiIpAddress() {
    //   var xhr = new XMLHttpRequest();
    //   xhr.open('GET', 'http://ip-api.com/json', true);
    //   xhr.onreadystatechange = function () {
    //     if (xhr.readyState === 4 && xhr.status === 200) {
    //       var response = JSON.parse(xhr.responseText);
    //       var ipAddress = response.query;
    //       ip.value = ipAddress
    //     }
    //   };
    //   xhr.send();
    // }
    // onMounted(getWifiIpAddress)
    // 判断IP地址
    const unitAddressCheck = (value) => {
      return store1
        .dispatch("sysConf/SetCloudServerAddress", value)
        .then((res) => {
          return true;
        })
        .catch((err) => {
          return false;
        });
    };

    // 规则
    const rules = {
      cloudAddress: [
        {
          required: true,
          validator: unitAddressCheck,
          message: "请输入正确边策地址,格式:http://127.0.0.1:80",
        },
      ],
      authCode: [
        {
          required: true,
          validator: unitAuthCode,
          message: "请输入正确子系统编码",
        },
      ],
      deviceSN: [
        {
          required: true,
          message: "请输入SN码",
        },
      ],
      unitModel: [
        {
          required: true,
          message: "请输入电子设备型号",
        },
      ],
      ipAddress: [
        {
          required: true,
          validator: ipAddressCheck,
          message: "请输入ip",
        },
      ],
    };

    //选择系统模式并赋值
    const onConfirm = (value) => {
      result.value = value;
      showPicker.value = false;
    };

    const colunmsFieldNames = {
      text: "value",
    };
    // 版本比较
    function 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;
    }
    // 提交
    const onSubmit = (values) => {
      //版本适配
      // let key = "system.param.adaptive"
      // getConfigByConfigKey(key).then((res)=>{
      //   let configValue = res.data.configValue
      //   let version = config.version;
      //   if (compareVersion(version,configValue)) {
          console.log(config.version,'第一步');
          result.value.key = type
          // values.runMode = result.value.key;
          values.runMode = type;
          console.log('第二部');
          store1.dispatch("sysConf/setDeviceSN", deviceSN);
          store1.dispatch("sysConf/setDeviceModel", unitModel);
          console.log('三');
          listSubsystem({ authCode: authCode.value }).then((response) => {
            console.log('四');
            // 授权码获取产线信息
            store1.dispatch("sysConf/setProductLine", response.rows[0]);
            self.form = response.rows[0];
            self.form.status = 1;
            self.form.subSystemRegisterStatus = 0;
            self.form.version = config.version;
            // self.form.ip = ip.value;
            self.form.ip=ipAddress.value
            const controlunit = {
              "subSysName":response.rows[0].name,
              "subSysCode":response.rows[0].code,
              "subSysId":response.rows[0].id,
              "deviceSN": deviceSN.value,
              "unitModel": unitModel.value,
              "unitTypeCode":"CE020103",
              "unitTypeName":"PDA"
            }
            const system = {
              cloudAddress:cloudAddress.value,
              authCode:authCode.value,
              code:response.rows[0].code,
              name:response.rows[0].name,
              ipAddress:ipAddress.value,
              runMode:"box",
              version:config.version,
              unitModel:unitModel.value,
              deviceSN:deviceSN.value,
            }
            // let rows = {};
            // rows["facilitySn"] = values.deviceSN;
            // rows["ipAddress"] = values.cloudAddress;
            // rows["subsystemCoding"] = values.authCode;
            // this.$nativeQRCode.insertQrCodeRegistration(rows);
            console.log(response,'111');
            console.log(response.rows[0],'222')
            console.log(controlunit,'33333')
            // 添加设备到 厂级
            uploadControlunit(controlunit).then(response => {
              if (response.code==500){
                Notify({type: 'warning', message: '该子系统已被注册或SN不正确', duration: 1500});
              }else {
                //注册信息保存到本地
                OpenDataWap.share.insertSystemConfigPo(JSON.stringify(system));
                updateSubsystem(self.form).then((response) => {});

                //设置厂级编码
                let key = "system.param.sysCode"
                getConfigByConfigKey(key).then((res)=>{
                  let configValue = res.data.configValue
                  store1.dispatch("sysConf/setSystemSysCode", configValue);
                })

                // 设置当前pda运行模式
                store1.commit("sysConf/SET_RUN_MODE", values.runMode);
                // 初始化子系统配置
                store1.dispatch("sysConf/InitSysConf");
                // 跳转登录界面
                route.push({ path: "/login" });
              }
            })
          });
        // } else {
        //   Dialog.confirm({
        //     title: "操作失败",
        //     // message: error + "",
        //     message:'PDA版本不匹配边侧系统，请升级新版本后重试',
        //     confirmButtonText: "升级",
        //     confirmButtonColor: "rgba(0, 0, 0, 1)",
        //   }).then(() => {
        //       NativeQRCode.downloadNewVersion(sysRequest.defaults.baseURL+"/file/pda/download?fileName=app-release.apk")
        //   })
        // }
      // })
    };
    return {
      onSubmit,
      authCode,
      cloudAddress,
      // ip,
      ipAddress,
      unitModel,
      result,
      columns,
      colunmsFieldNames,
      deviceSN,
      onConfirm,
      showPicker,
      rules,
      store1,
      type,
      title
    };
  },
  created() {
    removeToken();
  },
  methods: {},
  watch: {},
};
</script>

