<!--
 * @Description: 退役军人认证页面
 * @Author: 空白格
 * @Date: 2022-08-17 11:30:23
 * @LastEditors: gcz
 * @LastEditTime: 2022-08-30 10:56:49
 * @FilePath: \veterans_client_web\src\views\PersonalCenter\ApplyEducationAuth\ApplyEducationAuthIndex.vue
 * @Copyright: Copyright (c) 2016~2022 by 空白格, All Rights Reserved.
-->
<template>
  <div class="app-main">
    <BannerBreadcrumb title="退役军人认证码" :breadcrumb="true" />
    <div class="app-main-box">
      <div class="app-main-box-content">
        <div class="title">退役军人申请码</div>
        <el-form ref="form" :model="form" :rules="rules" label-width="180px">
          <el-form-item label="姓名" prop="veteName">
            <el-input
              v-model="form.veteName"
              placeholder="请输入真实姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="veteIdCard">
            <el-input
              v-model="form.veteIdCard"
              @blur="idNumberChange(form.veteIdCard)"
              placeholder="请输入身份证号"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="veteSex">
            <el-input
              disabled
              v-model="form.veteSex"
              placeholder="输入身份证自动获取"
            ></el-input>
          </el-form-item>
          <el-form-item label="民族" prop="nation">
            <el-input
              v-model="form.nation"
              placeholder="请输入您的民族"
            ></el-input>
          </el-form-item>
          <el-form-item label="所在区域" prop="veteHousehArea">
            <el-cascader
              filterable
              size="large"
              ref="addressSelect"
              :options="addressOptions"
              v-model="form.veteHousehArea"
              :leafOnly="true"
              @change="addrChange"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="veteResiAddress">
            <el-input
              v-model="form.veteResiAddress"
              placeholder="请输入您的详细地址"
            ></el-input>
          </el-form-item>
          <el-form-item label="户籍类别" prop="houseTypeId">
            <el-radio-group
              v-model="form.houseTypeId"
              @change="houseTypeChange"
            >
              <el-radio
                v-for="(item, index) in houseTypeList"
                :label="item.text"
                :key="index"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="户籍地" prop="veteHousehRegiCode">
            <el-cascader
              filterable
              size="large"
              ref="addressSelect"
              :options="addressOptions"
              v-model="form.veteHousehRegiCode"
              :leafOnly="true"
              @change="regiAddrChange"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="文化程度" prop="degrEduc">
            <el-select
              @change="degrEducChange"
              v-model="form.degrEduc"
              placeholder="请选择您的文化程度"
            >
              <el-option
                v-for="item in degrEducList"
                :key="item.index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="政治面貌" prop="politOutlook">
            <el-select
              @change="politOutlookChange"
              v-model="form.politOutlook"
              placeholder="请选择您的政治面貌"
            >
              <el-option
                v-for="item in politOutlookList"
                :key="item.index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="就业状况" prop="jobStatus">
            <el-radio-group v-model="form.jobStatus">
              <el-radio
                v-for="(item, index) in employmentStatusList"
                :label="item.value"
                :key="index"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="薪资范围" prop="salaryRangeName">
            <el-select
              @change="salaryRangeChange"
              v-model="form.salaryRangeName"
              placeholder="请选择您的薪资范围"
            >
              <el-option
                v-for="item in salaryRangeList"
                :key="item.index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="QQ" prop="qqNum">
            <el-input
              v-model="form.qqNum"
              placeholder="请输入您的QQ"
            ></el-input>
          </el-form-item>
          <el-form-item label="微信" prop="wxNum">
            <el-input
              v-model="form.wxNum"
              placeholder="请输入您的微信"
            ></el-input>
          </el-form-item>
          <el-form-item label="近期1寸免冠照片" prop="wxNum">
            <el-upload
              class="uploader file-uploader"
              :action="action"
              :show-file-list="false"
              :file-list="fileList"
              :on-success="fileUploadSuccess"
              accept="image/*"
              :limit="2"
              list-type="picture"
            >
              <img v-if="fileTempImg" :src="fileTempImg" class="uploader-img" />
              <i v-else class="el-icon-plus uploader-icon"></i>
              <div class="text">上传照片</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="">
            <el-button class="submit-btn" @click="submit" type="primary"
              >提交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-dialog
      title=""
      :visible.sync="dialogVisible"
      width="30%"
      custom-class="success-dialog"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <img
        class="img"
        src="@/assets/images/success-icon.png"
        alt=""
        srcset=""
      />
      <div class="text">提交成功，等待审核</div>
      <span class="btn" @click="confirmSuccess">确 定</span>
    </el-dialog>
  </div>
</template>
<script>
import BannerBreadcrumb from "@/components/BannerBreadcrumb";
import { getDictData } from "@/api/Dict";
import { getIdInfo } from "@/api/PersonalCenter";
import { veteEduc, getVeteEducData } from "@/api/ApplyEducationAuth";
// https://github.com/Plortinus/element-china-area-data
import {
  regionDataPlus,
  regionData,
  CodeToText,
  TextToCode,
} from "element-china-area-data";
import { mapState } from "vuex";
export default {
  name: "ApplyEducationAuthIndex",
  components: {
    BannerBreadcrumb,
  },
  data() {
    return {
      dialogVisible: false,
      // 上传地址
      action: process.env.VUE_APP_BASE_API + "/file/upload/single/minio",
      // action: process.env.VUE_APP_UPLOAD_URL,
      // action:'http://api.veterans.hongweisoft.com/file/upload/single/minio',
      addressOptions: regionData,
      fileList: [],
      form: {
        veteName: "",
        veteIdCard: "",
        veteSex: "",
        nation: "",
        qqNum: "",
        wxNum: "",
        degrEduc: "",
        degrEducId: "",
        houseType: "",
        houseTypeId: "",
        politOutlook: "",
        politOutlookId: "",
        veteHousehRegi: "",
        veteHousehRegiCode: ["520000"],
        veteHousehArea: ["520000"],
        veteResiAddress: "",
        veteDateBirth: "",
        veteStatus: "1",
        files: [],
        jobStatus: "",
        salaryRange: "",
        salaryRangeName: "",
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        areaId: "",
        areaName: "",
      },
      // 表单验证
      rules: {
        veteName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: ["change", "blur"],
          },
        ],
        veteIdCard: [
          {
            required: true,
            pattern:
              /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0[1-9]|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
            // 正则检验前先将值转为字符串
            transform(value) {
              return String(value);
            },
            message: "请正确输入身份证号",
            trigger: ["change", "blur"],
          },
        ],
        vetePhone: [
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: "请正确输入手机号",
            required: true,
            trigger: ["change", "blur"],
          },
        ],
        veteHousehArea: [
          {
            required: true,
            message: "请选择户籍区域",
            trigger: ["change", "blur"],
          },
        ],
        veteResiAddress: [
          {
            required: true,
            message: "请填写详细地址",
            trigger: ["change", "blur"],
          },
        ],
        nation: [
          {
            required: true,
            message: "请填写民族",
            trigger: ["change", "blur"],
          },
        ],
        degrEduc: [
          {
            required: true,
            message: "请选择文化程度",
            trigger: ["change", "blur"],
          },
        ],
        politOutlook: [
          {
            required: true,
            message: "请选择政治面貌",
            trigger: ["change", "blur"],
          },
        ],
        houseTypeId: [
          {
            required: true,
            message: "请选择户籍类别",
            trigger: ["change", "blur"],
          },
        ],
        veteHousehRegi: [
          {
            required: true,
            message: "请选择户籍地",
            trigger: ["change", "blur"],
          },
        ],
        veteHousehRegiCode: [
          {
            required: true,
            message: "请选择户籍地",
            trigger: ["change", "blur"],
          },
        ],
        // salaryRangeName: [
        // 	{
        // 		required: true,
        // 		message: '请选择薪资范围',
        // 		trigger: ['change', 'blur']
        // 	}
        // ],
        // jobStatus: [
        // 	{
        // 		required: true,
        // 		message: '请选择就业状态',
        // 		trigger: ['change', 'blur']
        // 	}
        // ]
      },
      // 文化程度
      degrEducShow: false,
      degrEducList: [],
      degrEducIndex: [],
      // 政治面貌
      politOutlookShow: false,
      politOutlookList: [],
      politOutlookIndex: [],
      // 户籍地
      regionShow: false,
      regionDefault: [],
      // 户籍类型
      houseTypeShow: false,
      houseTypeList: [],
      houseTypeIndex: [],
      // 户籍区域
      areaShow: false,
      // 薪资范围
      salaryRangeShow: false,
      salaryRangeIndex: [],
      salaryRangeList: [],
      salaryRangeIndex: [],
      // 就业状态
      employmentStatusList: [],
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    fileTempImg() {
      // console.log('this.form.files',this.form.files);
      if (this.form.files.length >= 1) {
        return this.form.files[0].filesUrl;
      } else {
        return false;
      }
    },
  },
  created() {
    this.getVeteDegrEduc();
    this.getVetePolitOutlook();
    this.getVeteHouseType();
    this.getSalaryRange();
    this.getEmploymentStatus();
    this.getVeteEducData();
  },
  mounted() {},
  methods: {
    /**
     * 获取已经提交的数据
     */
    getVeteEducData() {
      getVeteEducData().then((res) => {
        if (res.code == 200) {
          const data = res.data;
          for (let key in data.veteEduc) {
            if (key !== "files") {
              this.form[key] = data.veteEduc[key];
            }
          }
          if (data.veteEduc) {
            this.form.veteSex = data.veteEduc.veteSex === 0 ? "男" : "女";
            // 文化程度
            this.degrEducList.forEach((item, index) => {
              if (item.text === data.veteEduc.degrEducId) {
                this.degrEducIndex = [index];
              }
            });
            // 政治面貌
            this.politOutlookList.forEach((item, index) => {
              if (item.text === data.veteEduc.politOutlookId) {
                this.politOutlookIndex = [index];
              }
            });
            // 户籍类型
            this.houseTypeList.forEach((item, index) => {
              if (item.text === data.veteEduc.houseTypeId) {
                this.houseTypeIndex = [index];
              }
            });
            // 户籍区域
            if (
              data.veteEduc.provinceId &&
              data.veteEduc.cityId &&
              data.veteEduc.areaId
            ) {
              this.form.veteHousehArea = [
                data.veteEduc.provinceId.toString(),
                data.veteEduc.cityId.toString(),
                data.veteEduc.areaId.toString(),
              ];
              // console.log('data.veteEduc.provinceId',data.veteEduc.provinceId);
              // console.log('data.veteEduc.provinceId',data.veteEduc.cityId);
              // console.log('data.veteEduc.provinceId',data.veteEduc.areaId);
              // console.log('this.form',JSON.parse(JSON.stringify(this.form)));
            }
            // console.log('veteHousehArea',this.form.veteHousehArea);
            if (data.veteEduc.veteHousehRegi) {
              let veteHousehRegiArr = data.veteEduc.veteHousehRegi.split("-");
              this.form.veteHousehRegiCode = [
                TextToCode[veteHousehRegiArr[0]]?.code,
                TextToCode[veteHousehRegiArr[0]][veteHousehRegiArr[1]]?.code,
                TextToCode[veteHousehRegiArr[0]][veteHousehRegiArr[1]][
                  veteHousehRegiArr[2]
                ]?.code || "",
              ];
              console.log(
                "this.form.veteHousehRegiCode",
                this.form.veteHousehRegiCode
              );
            }
            // 薪资范围
            this.form.salaryRange = data.veteEduc.salaryRange;
            this.salaryRangeList.forEach((item, index) => {
              if (Number(item.value) === Number(data.veteEduc.salaryRange)) {
                this.salaryRangeIndex = [index];
                this.form.salaryRangeName = item.label;
              }
            });
            if(data.veteEduc.veteIdCard){
              this.idNumberChange(data.veteEduc.veteIdCard)
            }
          }
          this.form.files = data.files;
        }
      });
    },
    /**
     * 获取文化程度类别
     */
    getVeteDegrEduc() {
      getDictData({
        key: "degr_educ",
      }).then((res) => {
        if (res.code == 200) {
          this.degrEducList = res.data.map((item) => {
            return {
              ...item,
              value: item.text,
            };
          });
        }
      });
    },
    /**
     * 获取政治面貌类别
     */
    getVetePolitOutlook() {
      getDictData({
        key: "polit_outlook",
      }).then((res) => {
        if (res.code == 200) {
          this.politOutlookList = res.data.map((item) => {
            return {
              ...item,
              value: item.text,
            };
          });
        }
      });
    },
    /**
     * 获取户籍类别
     */
    getVeteHouseType() {
      getDictData({
        key: "house_type",
      }).then((res) => {
        if (res.code === 200) {
          this.houseTypeList = res.data.map((item) => {
            return {
              ...item,
              value: item.text,
            };
          });
        }
      });
    },
    /**
     * 获取薪资范围
     */
    getSalaryRange() {
      getDictData({
        key: "salary_range",
      }).then((res) => {
        if (res.code === 200) {
          this.salaryRangeList = res.data.map((item) => {
            return {
              ...item,
              value: item.text,
            };
          });
        }
      });
    },
    /**
     * 就业状态
     */
    getEmploymentStatus() {
      getDictData({
        key: "member_job_status",
      }).then((res) => {
        if (res.code === 200) {
          this.employmentStatusList = res.data.map((item) => {
            return {
              ...item,
              value: Number(item.text),
            };
          });
        }
      });
    },
    fileUploadSuccess(res, file) {
      // console.log("res", res);
      // console.log("file", file);
      this.form.files = [];
      this.form.files.push({
        filesUrl: res.data.url,
        filesType: 6,
      });
    },
    idNumberChange(val) {
      const reg =
        /^\d{6}((?:19|20)((?:\d{2}(?:0[13578]|1[02])(?:0[1-9]|[12]\d|3[01]))|(?:\d{2}(?:0[13456789]|1[012])(?:0[1-9]|[12]\d|30))|(?:\d{2}02(?:0[1-9]|1\d|2[0-8]))|(?:(?:0[48]|[2468][048]|[13579][26])0229)))\d{2}(\d)[xX\d]$/;
      if (!reg.test(val)) {
        return;
      }
      // 根据身份证得出性别
      this.form.veteSex = parseInt(val.substr(16, 1)) % 2 === 1 ? "男" : "女";
      // 设置出生日期
      this.form.veteDateBirth =
        val.substring(6, 10) +
        "-" +
        val.substring(10, 12) +
        "-" +
        val.substring(12, 14) +
        " 00:00:00";
      // 根据身份证号获取基本信息
      getIdInfo({
        id: this.form.veteIdCard,
      }).then((res) => {
        if (res.code === 200) {
          if (res.data) {
            this.form.nation = res.data.nation;
            this.form.veteName = res.data.veteName;
            this.form.vetePhone = res.data.vetePhone;
            this.form.veteResiAddress = res.data.veteResiAddress;
          }
        } else {
          uni.showToast({
            icon: "none",
            title: res.msg,
          });
        }
      });
    },
    addrChange(value) {
      this.form.provinceId = value[0];
      this.form.cityId = value[1];
      this.form.areaId = value[2];
      this.form.provinceName = CodeToText[value[0]];
      this.form.cityName = CodeToText[value[1]];
      this.form.areaName = CodeToText[value[2]];
      this.form.veteResiAddress =
        CodeToText[value[0]] + CodeToText[value[1]] + CodeToText[value[2]];
      // console.log(
      //   CodeToText[value[0]] + CodeToText[value[1]] + CodeToText[value[2]],
      //   "选中地址"
      // );
      console.log("this.provinceName", this.provinceName);
      console.log("addrChange", value);
      // console.log("this.form.veteHousehArea", this.form.veteHousehArea);
    },
    regiAddrChange(value) {
      this.form.veteHousehRegi = `${CodeToText[value[0]]}-${
        CodeToText[value[1]]
      }-${CodeToText[value[2]]}`;
      console.log(
        CodeToText[value[0]] + CodeToText[value[1]] + CodeToText[value[2]],
        "选中地址"
      );
      console.log("addrChange", value);
      console.log("this.form.veteHousehArea", this.form.veteHousehArea);
    },
    submit() {
      console.log("this.form", JSON.parse(JSON.stringify(this.form)));
      this.form.vetePhone = this.userInfo.mobile;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.files.length < 1) {
            this.$message({
              message: "近期1寸免冠照片",
              type: "error",
            });
          } else {
            let params = {
              veteEduc: {},
            };
            params.files = this.form.files;
            for (let key in this.form) {
              if (key !== "files") {
                params.veteEduc[key] = this.form[key];
              }
            }
            params.veteEduc.veteSex = params.veteEduc.veteSex === "男" ? 0 : 1;
            veteEduc(params).then((res) => {
              if (res.code === 200) {
                this.dialogVisible = true;
                // this.$message({
                // 	message: '提交成功，等待审核！',
                //   type: 'success',
                // 	duration: 2000,
                // 	success: () => {
                // 		this.$u.route(
                // 			'/pages/applyEducationCode/applyEducationSuccess'
                // 		)
                // 	}
                // });
                this.$store.dispatch("GetUserInfo").then((res) => {
                  console.log("获取用户信息:", res);
                });
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          }
        }
      });
    },
    houseTypeChange(e) {
      for (let index = 0; index < this.houseTypeList.length; index++) {
        const item = this.houseTypeList[index];
        if (item.text == e) {
          console.log("this.form", this.form);
          this.form.houseType = this.houseTypeList[index].label;
          break;
        }
      }
    },
    // jobStatusChange(e){
    //   for (let index = 0; index < this.employmentStatusList.length; index++) {
    //     const item =  this.employmentStatusList[index];
    //     if(item.text == e){
    //       console.log('this.form',this.form);
    //       this.form.jobStatus = this.employmentStatusList[index].label;
    //       break;
    //     }
    //   }
    // },
    degrEducChange(e) {
      for (let index = 0; index < this.degrEducList.length; index++) {
        const item = this.degrEducList[index];
        if (item.text == e) {
          this.form.degrEduc = this.degrEducList[index].label;
          this.form.degrEducId = this.degrEducList[index].value;
          break;
        }
      }
    },
    politOutlookChange(e) {
      for (let index = 0; index < this.politOutlookList.length; index++) {
        const item = this.politOutlookList[index];
        if (item.text == e) {
          this.form.politOutlook = this.politOutlookList[index].label;
          this.form.politOutlookId = this.politOutlookList[index].value;
          break;
        }
      }
    },
    salaryRangeChange(e) {
      for (let index = 0; index < this.salaryRangeList.length; index++) {
        const item = this.salaryRangeList[index];
        if (item.text == e) {
          this.form.salaryRangeName = this.salaryRangeList[index].label;
          this.form.salaryRange = this.salaryRangeList[index].value;
          break;
        }
      }
    },
    confirmSuccess() {
      this.dialogVisible = false;
      this.$router.push("/");
    },
    resetForm() {
      this.$refs["form"].resetFields();
    },
  },
};
</script>
<style lang="scss" scoped>
:deep(.success-dialog) {
  border-radius: 32px;
  text-align: center;
  .img {
    width: 134px;
  }
  .text {
    font-weight: 400;
    font-size: 28px;
    color: #000;
    letter-spacing: 0.13px;
    margin: 27px auto 140px;
  }
  .btn {
    width: 281px;
    display: inline-block;
    height: 58px;
    line-height: 58px;
    background: #709078;
    border-radius: 7px;
    font-size: 24px;
    color: #fff;
    cursor: pointer;
    margin-bottom: 45px;
  }
}
:deep(.banner-breadcrumb-breadcrumb) {
  margin-bottom: 14px;
}
.title {
  text-align: center;
  font-weight: 500;
  font-size: 40px;
  line-height: 1;
  color: #111;
  letter-spacing: 2.07px;
  padding: 23px 0;
  border-bottom: 1px solid #d7d7d7;
  margin-bottom: 43px;
}
.file-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  //   float: left;
  & + .uploader {
    margin-left: 20px;
  }
  .text {
    position: absolute;
    left: 0;
    bottom: 0;
    right: 0;
  }
  .el-upload:hover {
    border-color: #409eff;
  }
  .uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .uploader-img {
    width: 100px;
    height: 100px;
    display: block;
  }
}
.app-main-box {
  margin-top: 0;
}
.el-form {
  width: 50%;
}
.submit-btn {
  width: 265px;
}
</style>
