<template>
  <div class="container">
    <div class="header">
      <div class="title flex-row">
        <img src="@/assets/images/bg-1.png" alt/>
        <div class="right flex-row">
          <div class="circle flex-center">
            <i class="el-icon-user-solid"/>
          </div>
          <div class="go_login" v-if="!userBid" @click="goLogin">去登录</div>
          <el-dropdown v-else @command="commandHandle">
            <span class="el-dropdown-link flex-row">
              <span class="drop-down-content">{{ nickname }}</span>
              <i class="el-icon-caret-bottom el-icon--right"></i>
            </span>
            <el-dropdown-menu class="selectTab" slot="dropdown">
              <el-dropdown-item v-show="typeTabShow" command="1" class="custom-dropdown-item">记录查看
              </el-dropdown-item>
              <el-dropdown-item v-show="typeTabShow" command="2" class="custom-dropdown-item">修改密码
              </el-dropdown-item>
              <el-dropdown-item v-show="typeTabShow" command="5" class="custom-dropdown-item">
                个人中心
              </el-dropdown-item>
              <el-dropdown-item command="3">退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div v-if="showControlArea" class="control flex-row">
        <ul class="menu flex-row">
          <li
              v-for="(item, index) in menuList"
              :class="{ active: num === index }"
              :key="item.id"
              @click="handleSelect(item.value)"
              class="menu-list"
          >
            {{ item.name }}
            <span class="menu-tag" v-show="index === 2 && tagNum > 0">
              {{ tagNum }}
            </span>
          </li>
        </ul>
        <div class="search-box flex-row" v-show="['show0', 'show1'].includes(searchShowFlag)">
          <el-input
              v-model="keywords"
              :placeholder="searchShowFlag === 'show1' ? '请输入认知任务名称' : '请输入量表名称'"
              @clear="searchScale"
              @keyup.enter="searchScale"
          />
          <img src="@/assets/images/icon-search.png" alt="" @click="searchScale"/>
        </div>
      </div>
    </div>

    <div class="section" :class="{ 'main-content' : hasWrap, 'top': !showControlArea }">
      <router-view ref="Childmain"></router-view>
    </div>

    <el-dialog
        :title="dialogTitle"
        :visible.sync="userDialogVisiblephone1"
        width="1240px"
        top="6vh"
        :close-on-click-modal="false"
    >
      <el-form
          :model="userRuleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="180px"
          class="demo-ruleForm"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="身份证号：" prop="phone">
              <el-input
                  v-model="userRuleForm.phone"
                  @change="onCardNoChange"
                  readonly
                  placeholder="请输入身份证号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="petName">
              <el-input v-model="userRuleForm.petName" placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="年龄：" prop="age">
              <el-input
                  type="number"
                  v-model="userRuleForm.age"
                  planceholder="请输入年龄"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别：" prop="gender">
              <el-radio-group v-model="userRuleForm.gender">
                <el-radio label="0">男</el-radio>
                <el-radio label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="生日：" prop="birthday">
              <date-select
                  ref="dateSelect"
                  :years-model-prants="userRuleForm.birthday"
                  @dateChange="dateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="军衔：" prop="military">
              <el-select v-model="userRuleForm.military" placeholder="请选择军衔">
                <el-option
                    v-for="item in militaries"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="职务：" prop="profession">
              <el-input
                  type="text"
                  :maxlength="30"
                  v-model="userRuleForm.profession"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="飞行等级：" prop="fightRegistration">
              <el-select v-model="userRuleForm.fightRegistration" placeholder="请选择飞行等级">
                <el-option
                    v-for="item in fightRegistrations"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="单位：" prop="brigade">
              <el-input
                  v-if="isOtherDepartment"
                  type="text"
                  :maxLength="50"
                  v-model="userRuleForm.brigade"
              >
              </el-input>

              <el-input
                  v-else
                  type="number"
                  :min="1"
                  :max="100"
                  v-model.number="userRuleForm.brigade"
              >
                <template slot="suffix"><span class="suffix">旅</span></template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="" label-width="0">
              <el-checkbox v-model="isOtherDepartment" @change="onDepartmentChange">其他单位</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item prop="detachment" label-width="0">
              <el-input
                  type="number"
                  :min="1"
                  :max="9999"
                  v-model.number="userRuleForm.detachment"
              >
                <template slot="suffix"><span class="suffix">大队</span></template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="总飞行时间：" prop="flightDuration">
              <el-input
                  type="number"
                  :min="1"
                  :max="9999"
                  v-model="userRuleForm.flightDuration"
                  planceholder="请输入总飞行时间"
              >
                <template slot="suffix"><span class="suffix">小时</span></template>
              </el-input>
            </el-form-item>
            <el-form-item label="飞过机型：" prop="flyingModels">
              <el-select
                  v-model="userRuleForm.flyingModels"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择机型，可多选">
                <el-option
                    v-for="item in fightTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现机型飞行时间：" prop="currentTypeFlightDuration">
              <el-input
                  type="number"
                  :min="1"
                  :max="9999"
                  v-model="userRuleForm.currentTypeFlightDuration"
                  planceholder="请输入现机型飞行时间"
              >
                <template slot="suffix"><span class="suffix">小时</span></template>
              </el-input>
            </el-form-item>
            <el-form-item label="现飞机型：" prop="currentFlyingModels">
              <el-select
                  v-model="userRuleForm.currentFlyingModels"
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择机型">
                <el-option
                    v-for="item in fightTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" size="small" @click="submitUserForm(10)">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog
        :title="dialogTitle"
        :visible.sync="userDialogVisible"
        width="1120px"
        top="6vh"
        :close-on-click-modal="false"
        :before-close="handleClose"
    >
      <!-- <div v-if="parseInt(userRuleForm.phone1) == 0">
        <el-form
          :model="userRuleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="请输入手机号" prop="phone">
            <el-input
              type="text"
              maxlength="11"
              v-model="userRuleForm.phone1"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button @click="submitUserForm(1)">不再提示</el-button>
            <el-button type="primary" @click="submitUserForm">提交 </el-button>
          </el-form-item>
        </el-form>
      </div> -->
      <div>
        <el-form
            :model="userRuleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="120px"
            class="demo-ruleForm"
        >
          <el-form-item label="姓名" prop="petName">
            <el-input
                type="text"
                maxlength="11"
                v-model="userRuleForm.petName"
            />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="userRuleForm.gender">
              <el-radio label="0">男</el-radio>
              <el-radio label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="生日" prop="birthday">
            <date-select
                v-if="yearsModelPrants && yearsModelPrants !== ''"
                :yearsModelPrants="yearsModelPrants"
                @dateChange="dateChange"
            />
          </el-form-item>

          <el-form-item v-if="systemVersion !== 'lan'" label="职业" prop="profession">
            <el-input
                v-model="userRuleForm.profession"
                placeholder="请输入职业"
            />
          </el-form-item>
          <el-form-item label="请输入手机号" prop="phone">
            <el-input
                type="text"
                maxlength="11"
                v-model="userRuleForm.phone"
            />
          </el-form-item>

          <el-form-item>
            <!-- <el-button v-if=" parseInt(userRuleForm.phone) == 0" @click="submitUserForm(1)">不再提示</el-button> -->
            <el-button type="success" @click="submitUserForm">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- 修改密码弹窗 -->
    <el-dialog
        title="修改密码"
        :visible.sync="dialogVisible"
        width="38%"
        :close-on-click-modal="false"
    >
      <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="180px"
          class="demo-ruleForm"
      >
        <el-form-item label="请输入旧密码" prop="oldPassword">
          <el-input
              type="password"
              v-model="ruleForm.oldPassword"
              autocomplete="off"
              show-password
          />
        </el-form-item>
        <el-form-item label="请输入新密码" prop="pass">
          <el-input
              type="password"
              v-model="ruleForm.pass"
              autocomplete="off"
              show-password
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="checkPass">
          <el-input
              type="password"
              v-model="ruleForm.checkPass"
              autocomplete="off"
              show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="success" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {oSessionStorage, getInfoFromIdCard, isValidIDCard} from "@/utils/utils";
import screenfull from "screenfull";
import {mapGetters, mapActions} from "vuex";
import DateSelect from "../components/DateSelect.vue";

export default {
  components: {DateSelect},
  computed: {
    ...mapGetters({
      num: "tagActive",
    }),
  },
  data() {
    let menuList
    const systemVersion = process.env.VUE_APP_VERSION
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"))
      } else {
        // let juPassword =
        //   /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]{8,16}$/;
        // if (!juPassword.test(this.ruleForm.pass)) {
        //   callback(new Error("格式为数字+英文字母+特殊字符(~!@#$%^&*)8-16位"));
        // } else {
        //   this.$refs.ruleForm.validateField("checkPass");
        // }
        if (value.length < 6 || value.length > 18) {
          callback(new Error("新密码长度需在6~18位之间"))
        } else {
          this.$refs.ruleForm.validateField("checkPass")
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"))
      } else {
        callback()
      }
    }
    const validatePass3 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"))
      } else {
        callback()
      }
    }
    const checkPhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"))
      } else {
        if (systemVersion === "public") {
          if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value)) {
            callback(new Error("请输入正确的手机号码"))
          } else {
            callback()
          }
        } else {
          if (3 > value.length || value.length > 18) {
            callback(new Error("长度需在3~18位之间"))
          } else if (/[^\w\.V]/ig.test(value)) {
            callback(new Error("请不要输入中文和空格"))
          } else {
            callback()
          }
        }
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (
          this.userInfo.password === "" ||
          this.userInfo.password === null ||
          typeof this.userInfo.password === "undefined"
      ) {
        callback(new Error("请输入密码"))
      } else {
        // let juPassword =
        //   /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]{8,16}$/;
        // if (systemVersion == "lan") {
        //   if (!/^\d{6}$/.test(this.userInfo.password)) {
        //     callback(new Error("密码需为6位数字"));
        //   } else {
        //     callback();
        //   }
        // }
        // if (!juPassword.test(this.userInfo.password)) {
        //   callback(new Error("格式为数字+英文字母+特殊字符(~!@#$%^&*)8-16位"));
        // } else {
        //   callback();
        // }
        if (6 > value.length || value.length > 18) {
          callback(new Error("密码长度需在6~18位之间"))
        } else {
          callback()
        }
      }
    }
    const validatePasswordCheck = (rule, value, callback) => {
      if (
          this.userInfo.passwordCheck === "" ||
          this.userInfo.passwordCheck === null ||
          typeof this.userInfo.passwordCheck === "undefined"
      ) {
        callback(new Error("请输入确认密码"))
      } else {
        if (this.userInfo.password !== this.userInfo.passwordCheck) {
          callback(new Error("两次密码请保持一致"))
        } else {
          callback()
        }
      }
    }
    const checkBirthday = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("生日不能为空"))
      } else {
        if (value.split("-")[0] == 'null' || value.split("-")[1] == 'null' || value.split("-")[2] == 'null') {
          callback(new Error("请补全生日"))
        } else {
          callback()
        }
      }
    }

    if (systemVersion === "institution" || systemVersion === "lan") {
      menuList = [
        {value: 0, name: "量表", tag: 0},
        {value: 1, name: "认知任务", tag: 0},
        {value: 2, name: "测试计划", tag: 0},
      ]
    } else {
      menuList = [
        {value: 0, name: "量表"},
        {value: 1, name: "认知任务"}
      ]
    }

    const checkBrigade = (rule, value, callback) => {
      if (value) {
        if (this.isOtherDepartment) {
          if (value.length > 50) {
            callback(new Error('单位长度不能超出 50 个字符'))
          } else {
            callback()
          }
        } else {
          const result = parseInt(value)
          if (result < 1 || result > 100) {
            callback(new Error('单位数字不能超出 1~100 的范围'))
          } else {
            callback()
          }
        }
      } else {
        callback(new Error("单位（ 旅 ）不能为空"))
      }
    }

    const checkDetachment = (rule, value, callback) => {
      if (value) {
        if (value < 1 || value > 9999) {
          callback(new Error('大队数字不能超出 1~9999 的范围'))
        } else {
          callback()
        }
      } else {
        callback(new Error("大队不能为空"))
      }
    }

    const flyingModelsValidator = (rule, value, callback) => {
      if (!value.length) {
        // 一定要写 callBack() 验证完成时调用的回调函数 https://github.com/yiminghe/async-validator
        callback(new Error('请至少选择一种机型！'))
      } else {
        callback()
      }
    }

    const flightDurationValidator = (rule, value, callback) => {
      if (value > 99999 || value < 1) {
        callback(new Error('总飞行时间不能超出 1 ~ 99999'));
      } else {
        callback();
      }
    }
    const currentTypeFlightDurationValidator = (rule, value, callback) => {
      if (value > 99999 || value < 1) {
        callback(new Error('现机型飞行时间不能超出 1 ~ 99999'));
      } else {
        callback();
      }
    }

    return {
      isOtherDepartment: false, // 是否是其他单位
      yearsModelPrants: "",
      systemVersion: systemVersion,
      menuList: menuList,
      // activeIndex: 0,
      //搜索框提示语
      institutionNo: "",
      searchPrompt: "",
      tagNum: 0,
      subjectInfos: [], //tab展示的数据列表
      userNameForShow: "", //用户展示用户名
      userBid: "", //用户唯一标识
      userId: "",
      routerList: ["MainTable", "CognitiveAbility", "TestPlan"],
      pageNum: 1,
      pageSize: 10,
      totalNum: 0,
      allPage: 0,
      keywords: "",
      dialogVisible: false, //弹出窗是否可见
      userDialogVisible: false,
      userDialogVisiblephone1: false,
      userRuleForm: {
        birthday: "", //生日
        profession: "", //职业
        phone: "", //用户唯一标识
        petName: "", //用户名
        gender: "", //性别
        institutionNo: process.env.VUE_APP_INSNO,
        userStatus: "1",
        additionInfo: "",
        vCode: "",
        roleType: "1",
        brigade: '', // 旅
        detachment: '', // 大队
        fightRegistration: '', // 飞行等级
        flightDuration: '', // 总飞行时间
        currentTypeFlightDuration: '', // 现飞行时间
        flyingModels: '', // 飞过机型
        currentFlyingModels: '', // 现飞机型
        age: '',
        military: ''
      },
      dialogTitle: '完善信息',
      //修改密码
      ruleForm: {
        pass: "",
        checkPass: "",
        oldPassword: "",
      },
      typeTabShow: true,
      rules: {
        // tel: [{ required: true, validator: phoneRules, trigger: "blur" }],
        phone: [{required: true, validator: checkPhone, trigger: "change"}],
        gender: [{required: true, message: "请选择性别", trigger: "change"}],
        institutionNo: [
          {required: true, message: "机构编号不能为空", trigger: "blur"}
        ],
        petName: [
          {
            required: true,
            message: "昵称不能为空",
            trigger: "blur"
          },
          {
            max: 18,
            message: "长度在18位及以内",
            trigger: "blur"
          }
        ],
        birthday: [
          {
            required: true,
            validator: checkBirthday,
            trigger: "change"
          }
        ],
        profession: [
          {
            required: true,
            message: "职业不能为空",
            trigger: "blur"
          },
        ],
        password: [
          {required: true, validator: validatePassword, trigger: "blur"}
        ],
        passwordCheck: [
          {
            required: true,
            validator: validatePasswordCheck,
            trigger: "blur"
          }
        ],
        vCode: [
          {
            required: true,
            message: "请输入短信验证码",
            trigger: "blur"
          }
        ],
        newPsd: [
          {
            required: true,
            message: "请输入新密码",
            // trigger: "blur",
            trigger: "change"
          }
        ],
        brigade: [{ required: true, validator: checkBrigade, trigger: "blur" }],
        detachment: [{ required: true, validator: checkDetachment, trigger: "blur" }],
        fightRegistration: [{ required: true, message: "请选择飞行等级", trigger: "change" }],
        flightDuration: [
          { required: true, message: "请输入总飞行时间", trigger: "blur" },
          { validator: flightDurationValidator, trigger: "change" }
        ],
        flyingModels: [{ required: true, validator: flyingModelsValidator, trigger: "change" }],
        currentTypeFlightDuration: [
          { required: true, message: "请输入现机型飞行时间", trigger: "blur" },
          { validator: currentTypeFlightDurationValidator, trigger: "change" }
        ],
        currentFlyingModels: [{ required: true, validator: flyingModelsValidator, trigger: "change" }],
        age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
        military: [{ required: true, message: "军衔不能为空", trigger: "blur" }],
      },
      tabFlag: "",
      hasWrap: true,
      showControlArea: false, // 是否显示模块切换
      userType: "",
      nickname: "", //用户昵称
      searchShow: true,
      searchShowFlag: 'show0',
      userStatus: null, //用户状态,

      airPlanOptions: [
        { label: "A340", value: "A340" },
        { label: "B777-200", value: "B777-200" },
        { label: "波音767", value: "波音767" }
      ],
      militaries: [
        { label: '未定级', value: '未定级' },
        { label: '少尉', value: '少尉' },
        { label: '中尉', value: '中尉' },
        { label: '上尉', value: '上尉' },
        { label: '少校', value: '少校' },
        { label: '中校', value: '中校' },
        { label: '上校', value: '上校' },
        { label: '大校', value: '大校' },
      ],
      fightRegistrations: [
        { label: '特级', value: '特级' },
        { label: '1级', value: '1级' },
        { label: '2级', value: '2级' },
        { label: '3级', value: '3级' },
        { label: '未定级', value: '未定级' },
      ],
      fightTypes: [
        { label: 'J-10', value: 'J-10' },
        { label: 'J-11', value: 'J-11' },
        { label: 'J-16', value: 'J-16' },
        { label: 'Su-20', value: 'Su-20' },
        { label: 'Su-27', value: 'Su-27' },
        { label: 'Su-30', value: 'Su-30' },
        { label: 'Su-35', value: 'Su-35' },
      ],
    }
  },

  created() {
    document.onkeydown = function (e) {
      let key = window.event.keyCode;
      if (key === 122) {
        e.preventDefault();
        screenfull.toggle();
      }
    };
    //权限控制
    if (
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == null ||
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") === ""
    ) {
      if (this.systemVersion !== "public") {
        this.$message.error("请登录！");
        this.$router.push({
          name: "Login",
        });
      }
    }

    let tempSearchShow = sessionStorage.getItem("searchShowFlag");
    if (tempSearchShow) {
      this.searchShowFlag = tempSearchShow
    }

    //如果10002机构普通用户并且不是测试账号，则不展示量表和认知任务分类，直接跳转至认知任务列表页面
    if (
        sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9527") === "10002" &&
        sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9528") === "1" && //普通用户
        sessionStorage
            .getItem("f7a42fe7211f98ac7a60a285ac3a9e87")
            .indexOf("10002test") === -1
    ) {
      // 不是测试账号
      this.handleSelect(1);
      this.typeTabShow = false;
    }
    this.showControlArea = (this.$route.path === "/welcome/mainTable" ||
        this.$route.path === "/welcome/CognitiveAbility" ||
        this.$route.path === "/welcome/TestPlan");
  },
  // 页面初始化函数
  mounted() {
    this.institutionNo = sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9527");
    // console.log("机构编号为"+this.institutionNo)
    this.searchPrompt = "请输入量表名称";
    // this.$root.activeIndex = "0";
    this.userNameForShow = sessionStorage.getItem("435e0648d634175c46bd40ac366545a8");
    this.userId = sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f");
    this.userBid = localStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9e87");
    this.userType = sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9528");

    // 校验用户其他元素信息 先检测用户单位信息 若没有则弹出完善信息框
    setTimeout(() => {
      this.userRuleForm = JSON.parse(sessionStorage.getItem("user-all-info"))
      console.log(' ------------------------------- this.userRuleForm: ', this.userRuleForm)
      if (!this.userRuleForm || !this.userRuleForm.brigade || this.userRuleForm.brigade === '') {
        this.dialogTitle = "完善信息"
        this.userDialogVisiblephone1 = true
      } else {
        const currentFlyingModels = JSON.parse(this.userRuleForm.currentFlyingModels)
        this.userRuleForm.currentFlyingModels = currentFlyingModels.length ? currentFlyingModels[0] : ''
        this.userRuleForm.flyingModels = JSON.parse(this.userRuleForm.flyingModels)
      }
    }, 1100)

    // 配合公网版游客模式改造
    if (this.userId) {
      this.getUserForm();
      this.loadData();
    }
    if (!sessionStorage.getItem('backToIndex')) {
      sessionStorage.setItem('backToIndex', '0');
    }
  },
  watch: {
    $route(to, from) {
      this.searchShow = !(to.path === '/welcome/TestPlan')
      // console.log(to, from);
      this.hasWrap = !(to.path === "/welcome/testResult" ||
          to.path === "/PersionDetail" ||
          to.path === "/welcome/scaleResult");

      this.showControlArea = (to.path === "/welcome/mainTable" ||
          to.path === "/welcome/CognitiveAbility" ||
          to.path === "/welcome/TestPlan");
      // console.log('this.showControlArea:', this.showControlArea)
    },
    userDialogVisiblephone1(newVal) {
      if(newVal) {
        setTimeout(() => {
          this.$refs.ruleForm.clearValidate()
        }, 120)
      }
    }
  },
  methods: {
    ...mapActions({
      setTagActive: "setTagActive",
    }),
    onCardNoChange(cardNo) {
      if (!isValidIDCard(cardNo)) {
        return
      }

      const idCardInfo = getInfoFromIdCard(cardNo)

      if (idCardInfo) {
        console.log(idCardInfo)
        this.userRuleForm.gender = idCardInfo.gender
        this.userRuleForm.birthday = idCardInfo.birthday
        this.userRuleForm.age = idCardInfo.age
      }
    },
    onDepartmentChange() {
      this.userRuleForm.brigade = ''
    },
    //个人信息弹窗关闭
    handleClose(done) {
      //如果用户状态为4，禁止关闭弹窗
      if (this.userStatus === 4) {
        // return;
        this.$confirm('需要您补充完整的用户信息，确定要退出吗？')
            .then(_ => {
              //退出登陆
              this.escape();
              // done();
            })
            .catch(_ => {
            });

      } else {
        done()
      }
    },
    // 选择注册日期
    dateChange(obj) {
      // this.userRuleForm.birthday = `${obj.year}`;
      this.userRuleForm.birthday = `${obj.year}-${obj.month}-${obj.day}`;
    },
    // 查询量表数据
    loadData() {
      let _this = this;
      this.$http.get(
          `/testPlan/user/plan?userId=${this.userId}&status=3&isComplete=0&searchKey=&beginTime=&endTime=&beginNum=1&pageSize=50`,
          {},
          (response) => {
            if (response?.data?.num > 0) {
              _this.tagNum = response.data.num;
            }
          }
      );
    },
    personCenter() {
      this.$router.push({
        name: "PersonalCenter",
      });
    },
    escape() {
      this.$http.post("system/logout", {
        institutionNo: this.institutionNo,
        phone: this.userBid,
        roleType: this.userType,
      }, (res) => {

        if (res && res.code == 200) {
          this.$message({
            message: "已成功退出登录",
            type: "success",
          });
          sessionStorage.clear();
          localStorage.clear();
          this.nickname = "";
          this.userBid = "";
          this.$router.push({path: "/",});

        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    // 任务类型 量表测试-0  认知任务-1
    handleSelect(key) {
      this.$root.search = "";
      this.keywords = "";
      oSessionStorage.removeItem("currentPage");
      oSessionStorage.removeItem("currentTab");
      console.log('key:', key)
      if (key == 0) {
        this.searchPrompt = "请输入量表名称";
      } else {
        this.searchPrompt = "请输入认知任务名称";
      }
      sessionStorage.setItem('backToIndex', key);
      //当key等于0时且 this.routerList[key] 等于MainTable 时不进行跳转页面
      if (key == "0" || key == "1" || key == "2") {
        //当当前页面量表主页面时 直接调用onsearch
        //当是量表页面的子页面时 先跳转到量表主页面 认知任务同理
        if (key == "0" || key == 0) {
          sessionStorage.setItem("searchShowFlag", 'show0')
          this.searchShowFlag = 'show0'
          let ll = this.$route.name;
          if (ll === "MainTable") {
            this.$refs["Childmain"].onSearch();
          } else {
            this.$router.push({
              name: "MainTable",
              params: {},
            });
            // this.$router.go();
          }
        }
        if (key == "1") {
          sessionStorage.setItem("searchShowFlag", 'show1')
          this.searchShowFlag = 'show1'
          let ll = this.$route.name;
          if (ll === "CognitiveAbility") {
            this.$refs["Childmain"].onSearch();
          } else {
            this.$router.push({
              name: "CognitiveAbility",
              params: {},
            });
          }
        }
        if (key == "2") {
          sessionStorage.setItem("searchShowFlag", 'no')
          this.searchShowFlag = 'no'
          let ll = this.$route.name;
          if (ll === "TestPlan") {
            // this.$refs["Childmain"].onSearch();
          } else {
            this.$router
                .push({
                  name: "TestPlan",
                  params: {},
                })
                .catch((err) => {
                });
          }
        }
      } else {
        this.$router.push({
          name: this.routerList[key],
          params: {},
        });
      }
      // this.tabFlag = key;
    },
    searchScale() {
      //如果10002机构普通用户并且不是测试账号直接返回，不让查询量表数据
      if (
          sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9527") === "10002" && //10002机构
          sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9528") === "1" && //普通用户
          sessionStorage
              .getItem("f7a42fe7211f98ac7a60a285ac3a9e87")
              .indexOf("10002test") === -1
      ) {
        //不是测试账号
        return;
      }
      this.$root.search = this.keywords;
      let ro = this.$route.name;
      //当路由名字是  ScaleTestPage  或者 ScaleDetail 时 需要将标志转到mainTable
      if (ro == "MainTable") {
        this.$refs["Childmain"].onSearch();
      } else if (
          ro == "ScaleDetail" ||
          ro == "ScaleTestPage" ||
          ro == "ScaleResult" ||
          ro == "scaleResultSCl"
      ) {
        // this.$refs["Childmain"].onSearch();
        this.$root.activeIndex = "0";
        this.$router.push({
          name: "MainTable",
          params: {},
        });
      } else if (ro == "CognitiveAbility") {
        this.$refs["Childmain"].onSearch();
      } else {
        this.$root.activeIndex = "1";
        this.$router.push({
          name: "CognitiveAbility",
          params: {},
        });
      }
    },
    changePwd() {
      this.dialogVisible = true;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      let temp = sessionStorage.getItem('user-rule-form')
      if(formName === 'ruleForm' && temp) {
        this.userRuleForm = JSON.parse(sessionStorage.getItem('user-rule-form'))
      }
      // this.dialogVisible = false;
    },
    statusFormat(row) {
      if (row.status == 1) {
        return "手动关闭";
      } else if (row.status == 3) {
        return "正常使用";
      } else {
        return "关闭";
      }
    },
    submitUserForm(v, formName = 'ruleForm') {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false
        } else {
          if (v == 1) {
            this.userRuleForm.phone = 1;
          } else if (v == 10) {
            // this.userRuleForm.phone = this.userRuleForm.phone1;
            // this.userRuleForm.phone || this.userRuleForm.phone1;
          } else {
            if (!this.userRuleForm.petName) {
              this.$message.warning("请输入昵称");
              return;
            }
            if (!this.userRuleForm.gender) {
              this.$message.warning("请选择性别");
              return;
            }
            if (!this.userRuleForm.birthday) {
              this.$message.warning("请选择生日");
              return;
            }
            if (this.userRuleForm.birthday.split("-")[0] == 'null' || this.userRuleForm.birthday.split("-")[1] == 'null' || this.userRuleForm.birthday.split("-")[2] == 'null') {
              this.$message.warning("请补全生日");
              return;
            }
            if (this.systemVersion != 'lan' && !this.userRuleForm.profession) {
              this.$message.warning("请输入职业");
              return;
            }
          }
          // let asd = {
          //   institutionNo: this.institutionNo,
          //   phone: this.userBid,
          //   newModelPhone: this.userRuleForm.phone,
          //   petName: this.userRuleForm.petName,
          //   gender: this.userRuleForm.gender,
          //   birthday: this.userRuleForm.birthday,
          //   profession: this.userRuleForm.profession,
          // };
          let params = {
            institutionNo: this.institutionNo,
            phone: this.userBid,
            // newModelPhone: this.userRuleForm.phone,
            petName: this.userRuleForm.petName,
            gender: this.userRuleForm.gender,
            birthday: this.userRuleForm.birthday,
            profession: this.userRuleForm.profession,
            roleType: this.userType,
            brigade: this.userRuleForm.brigade, // 旅
            detachment: this.userRuleForm.detachment, // 大队
            fightRegistration: this.userRuleForm.fightRegistration, // 飞行等级
            flightDuration: this.userRuleForm.flightDuration, // 总飞行时间
            currentTypeFlightDuration: this.userRuleForm.currentTypeFlightDuration, // 现飞行时间
            flyingModels: this.userRuleForm.flyingModels, // 飞过机型
            currentFlyingModels: [this.userRuleForm.currentFlyingModels], // 现飞机型
            age: this.userRuleForm.age,
            military: this.userRuleForm.military
          };
          console.log('提交的参数：', params)
          sessionStorage.setItem('user-rule-form', JSON.stringify(this.userRuleForm))
          this.$http.post("/user/hf/update", params, (res) => {
            if (res && res.code == 200) {
              // this.getUserForm();
              this.$message.success('完善信息成功！');
              sessionStorage.setItem("435e0648d634175c46bd40ac366545a8", this.userRuleForm.petName) // 用户昵称
              localStorage.setItem("f7a42fe7211f98ac7a60a285ac3a9e87", this.userRuleForm.phone) // 用户账号
              sessionStorage.setItem("f7a42fe7211f98ac7a60a285ac3a9e87", this.userRuleForm.phone) // 用户账号
              this.nickname = res.data.userEntity.petName;
              sessionStorage.setItem("user-all-info", JSON.stringify({
                ...res.data.userAttribute,
                ...res.data.userEntity
              }))
              this.userDialogVisiblephone1 = false
              this.resetForm('ruleForm')
            } else {
              this.$message.error(res.msg);
            }
          })
        }
      })
    },
    getUserForm() {
      this.$http.get(
          "/user/getModelPhone?institutionNo=" +
          this.institutionNo +
          "&phone=" +
          this.userBid +
          "&roleType=" +
          this.userType,
          {},
          (res) => {
            console.log("修改后的信息", res);
            if (res && res.code == 200) {

              this.userRuleForm.phone = res.data.phone;
              this.userRuleForm.petName = res.data.petName;
              this.userRuleForm.gender = res.data.gender;
              this.userRuleForm.birthday = res.data.birthday;
              this.userRuleForm.age = res.data.age
              this.userRuleForm.military = res.data.military
              this.isOtherDepartment = Number.isNaN(parseInt(res.data.brigade))
              this.yearsModelPrants = res.data.birthday;
              this.userRuleForm.profession = res.data.profession;
              //用户昵称单独变量处理，防止个人中心修改未提交联动
              this.nickname = res.data.petName;
              //获取用户状态，如果为4强制弹窗要求用户补全信息
              this.userStatus = res.data.userStatus;
              // if (this.userStatus == '4') {
              //   this.userDialogVisible = true;
              // } else {
              //   this.userDialogVisible = false;
              // }
              // console.log("res登陆",res)

            } else {
              this.$message.error(res.msg);
            }

          }
      );
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http.post(
              "system/updatePassword",
              {
                id: this.userId,
                oldPassword: this.$md5(this.ruleForm.oldPassword),
                password: this.$md5(this.ruleForm.checkPass),
              },
              (res) => {
                this.dialogVisible = false;
                this.$message({
                  message: "密码修改完成！",
                  type: "success",
                });
                sessionStorage.clear();
                this.$router.push({
                  path: "/",
                });
              }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    openTestPlan() {
      this.testPlanDialog = true;
      this.getTestPlanData();
    },
    // getTestPlanData() {
    //   if (this.time.length == 0) {
    //     this.$http.get(
    //       "/testPlan/user/plan?userId=" +
    //         this.userId +
    //         "&searchKey=" +
    //         this.searchKeyForTestPlan +
    //         "&beginNum=" +
    //         this.currentPageForTestPlan +
    //         "&pageSize=" +
    //         this.pageSizeForTestPlan +
    //         "&beginTime=" +
    //         "" +
    //         "&endTime=" +
    //         "",
    //       {},
    //       (response) => {
    //         // console.log(response);
    //         this.totalForTestPlan = response.data.num;
    //         this.testPlanData = response.data.testPlanEntities;
    //         // console.log(this.tableData)
    //         // console.log(response.data.testPlanEntities)
    //         console.log(response);
    //       }
    //     );
    //   } else {
    //     this.$http.get(
    //       "/testPlan/user/plan?userId=" +
    //         this.userId +
    //         "&searchKey=" +
    //         this.searchKeyForTestPlan +
    //         "&beginNum=" +
    //         this.currentPageForTestPlan +
    //         "&pageSize=" +
    //         this.pageSizeForTestPlan +
    //         "&beginTime=" +
    //         this.time[0] +
    //         "&endTime=" +
    //         this.time[1],
    //       {},
    //       (response) => {
    //         // console.log(response);
    //         this.totalForTestPlan = response.data.num;
    //         this.testPlanData = response.data.testPlanEntities;
    //         // console.log(this.tableData)
    //         // console.log(response.data.testPlanEntities)
    //         console.log(response);
    //       }
    //     );
    //   }
    // },
    // onSubmit() {
    //   this.currentPageForTestPlan = 1;
    //   //点击搜索时需要将值赋值给搜索的按钮
    //   this.getTestPlanData();
    // },
    // reset() {
    //   this.searchKeyForTestPlan = "";
    //   this.time = "";
    //   this.getTestPlanData();
    // },
    // 下拉菜单回调
    commandHandle(i) {
      if (i == 1) {
        this.searchShow = false;
        // this.setTagActive(3);
        this.personCenter();
      } else if (i == 2) {
        this.changePwd();
        this.searchShow = true;
      } else if (i == 3) {
        // this.setTagActive(0);
        this.searchShow = true;
        this.keywords = "";
        // this.scaleName =""
        this.$root.search = "";
        this.$store.dispatch("setTagNum", 0);
        this.escape();
      } else if (i == 5) {
        this.searchShow = true;
        this.dialogTitle = '个人中心'
        this.userDialogVisiblephone1 = true;
        // this.userRuleForm.phone = sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9e87")
        // if (this.userRuleForm.phone1 == 0) {
        //   this.userDialogVisiblephone1 = true;
        // } else {
        //   this.userDialogVisible = true;
        // }
      }
    },

    goLogin() {
      this.$router.push(`/login?redirect=${this.$route.fullPath}`);
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  height: 100vh;
  padding: 0;
  margin: 0;
  overflow: hidden;
  position: relative;
  background-color: #E9EEF6;
  user-select: none;

  .header {
    width: 100%;
    height: 100%;
    // height: 348px;
    // background: url('~@/assets/images/bg-1.png') no-repeat 0 0 / 100% 338px border-box border-box fixed;
    background: url('~@/assets/images/bg-2.png') no-repeat 0 0 / 100% 100% border-box border-box fixed;

    .title {
      width: 100%;
      height: 70px;
      background-color: rgba(0, 55, 110, 0.5);
      justify-content: space-between;
      background: url('~@/assets/images/bg-1.png') no-repeat 0 0 / 100% 338px border-box border-box fixed;
      img {
        height: 100%;
        width: 100%;
        margin-left: 28px;
      }

      .right {
        margin-right: 72px;

        .circle {
          width: 32px;
          height: 32px;
          background-color: white;
          overflow: hidden;
          border-radius: 50%;
          font-size: 20px;
          color: #ababab;
        }

        .el-dropdown-link {
          font-size: 24px;
          cursor: pointer;
          color: #ffffff;
          margin-left: 24px;

          .drop-down-content {
            max-width: 120px;
            text-align: right;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }
    }

    .control {
      width: 100%;
      margin-top: 30px;
      height: 60px;
      margin-left: 100px;
      position: relative;

      .menu {
        width: 700px;
        height: 60px;
        padding: 5px 10px;
        border-radius: 30px;
        background-color: white;
        justify-content: space-between;

        li {
          width: 168px;
          font-size: 22px;
          color: #555555;
          text-align: center;
          line-height: 50px;
          border-radius: 25px;
          cursor: pointer;

          &.active {
            color: white;
            background-color: #26B600;
          }

          &:not(.active):hover {
            color: white;
            background-color: rgba(78, 175, 48, 0.692);
          }
        }
      }

      .search-box {
        width: 400px;
        height: 60px;
        position: absolute;
        right: 200px;
        top: 0;
        border-radius: 30px;
        background-color: rgba(255, 255, 255, 0.6);
        justify-content: space-around;

        ::v-deep .el-input {
          width: 80%;
          height: 60px;

          .el-input__inner {
            height: 60px;
            line-height: 60px;
            background-color: transparent;
            border: 0;
            color: #26B600;
            font-size: 20px;

            &::placeholder {
              color: #26B600;
            }
          }
        }

        img {
          width: 32px;
          height: 32px;
          margin-right: 10px;
          cursor: pointer;
        }
      }
    }
  }

  .main-content {
    position: absolute;
    left: 100px;
    top: 210px;
    width: calc(100% - 200px);
    height: calc(100% - 230px);
    background-color: transparent;
    overflow: hidden;

    &.top {
      top: 150px !important;
    }
  }
}

::v-deep .el-dialog {
  .el-dialog__body {
    .el-form {
      .el-form-item {
        margin-bottom: 24px;

        .el-select {
          width: 100%;
        }
      }
    }
  }
}

.el-menu.el-menu--horizontal {
  border-bottom: 1px solid #e6e6e6 !important;
}

a {
  color: #242323;
}

.mainbody {
  height: 640px;
  width: 450px;
}

.middle {
  top: 50%;
  left: 50%;
  position: absolute;

  transform: translate(-50%, -50%);
}

.form-box {
  width: 100%;
  height: 100%;
  margin: auto;
  background: #ffffff;

  border-radius: 20px;
}

.input-normal {
  width: 220px;
  height: 30px;
  margin: 20px auto;
  padding: 0;
  text-align: center;
  border-radius: 20px;
  outline: none;
  display: block;
  transition: 0.3s;
  border: 1px solid #e6e6e6;
}

.input-normal-data {
  width: 220px;
  height: 30px;
  margin: 20px auto;
  padding: 0;
  text-align: center;
  border-radius: 20px;
  outline: none;
  display: block;
  transition: 0.3s;
}

.input-normal-first {
  width: 220px;
  height: 30px;
  margin: 0px auto;
  padding: 0;
  text-align: center;
  border-radius: 20px;
  outline: none;
  display: block;
  transition: 0.3s;
  border: 1px solid #e6e6e6;
}

.input-normal-radio {
  width: 100px;
  height: 30px;
  margin: 30px auto;
  padding: 0;
  text-align: center;
  border-radius: 20px;
  outline: none;
  display: block;
  transition: 0.3s;
  border: 1px solid #e6e6e6;
}

.loginButtonClass {
  width: 100px;
  height: 36px;
  margin: auto;
  font-size: 18px;
  text-align: center;
  color: white;
  border-radius: 20px;
  display: block;
  background: darkslategrey;
  transition: 0.3s;
}

p {
  margin: 15px auto;
  padding: 0;
  font-size: 16px;
  color: white;
  display: block;
  text-align: center;
}

a {
  color: aqua;
  cursor: pointer;
}

.selectTab {
  min-width: 100px;

  .custom-dropdown-item {
    font-size: 0.083rem;
  }
}

.section {
  flex: 1;
}

.menu-list {
  position: relative;
}

.input-with-selects {
  width: 80%;
}

.menu-tag {
  position: absolute;
  top: 12px;
  right: 9px;
  background: red;
  color: #fff;
  padding: 0px 9px;
  height: 25px;
  text-align: center;
  line-height: 25px;
  border-radius: 13px;
  font-size: 12px;
}

.search_box_active {
  opacity: 0.01;
}

/* 适应pad样式 */
@media screen and (max-width: 1024px) {
  .search_box {
    margin-left: 10px;
  }
}

.go_login {
  font-size: 14px;
  color: #ffffff;
  cursor: pointer;
}

.suffix {
  color: #606266;
}

</style>
