<template>
  <div class="referInfo">
    <el-form
      ref="referRef"
      :model="referForm"
      label-position="top"
      class="checkForm"
      :rules="referInfoRules"
    >
      <div class="cont_title">个人信息</div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="referForm.name"
              placeholder="填写真实姓名"
              size="small"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="referForm.gender" size="small">
              <el-radio label="0">男</el-radio>
              <el-radio label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="id_card">
            <el-input
              v-model="referForm.id_card"
              placeholder="填写真实姓名身份证号"
              size="small"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthday">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-select v-model="bdYear" placeholder="年">
                  <el-option
                    v-for="(item, index) in yearArrs"
                    :key="index"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-select v-model="bdMonth" placeholder="月">
                  <el-option
                    v-for="(item, index) in monthArrs"
                    :key="index"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-select v-model="bdDay" placeholder="日" @change="getTime()">
                  <el-option
                    v-for="(item, index) in dayArrs"
                    :key="index"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="籍贯" prop="jiguan_code">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-select
                  v-model="jgProvinceCode"
                  placeholder="省"
                  @keyup.enter.native="selsectProvince"
                  @change="changeProvince(1, $event)"
                >
                  <el-option
                    v-for="item in selectProvince"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="12">
                <el-select
                  v-model="jiguan_city"
                  placeholder="市"
                  @change="getJiguan()"
                >
                  <el-option
                    v-for="item in selectCityJiguan"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="民族" prop="nation">
            <el-input
              v-model="referForm.nation"
              placeholder="填写民族"
              size="small"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入学年份(高中)" prop="start_school_date">
            <el-select
              v-model="referForm.start_school_date"
              placeholder="填写入学年份(高中)"
              clearable
            >
              <el-option
                v-for="(item, index) in yearArrs"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="政治面貌" prop="political_status">
            <el-input
              v-model="referForm.political_status"
              placeholder="填写政治面貌"
              size="small"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号">
            <el-input
              v-model="phone"
              placeholder="18355151517"
              size="small"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input
              v-model="referForm.email"
              placeholder="填写电子邮箱"
              size="small"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="cont_title">学校信息</div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="就读中学" prop="school_province">
            <el-select
              v-model="referForm.school_province"
              clearable
              placeholder="省"
              @change="changeProvince(2, $event)"
            >
              <el-option
                v-for="item in selectProvince"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label=" " prop="school_city">
            <el-select
              v-model="referForm.school_city"
              clearable
              placeholder="市"
              @change="changeCity($event)"
            >
              <el-option
                v-for="item in selectCitySchool"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label=" " prop="school">
            <el-select v-model="referForm.school" clearable placeholder="中学">
              <el-option
                v-for="item in selectSchoolList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中学联系人" prop="school_contacts">
            <el-input
              v-model="referForm.school_contacts"
              placeholder="填写中学联系人"
              size="small"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中学联系电话" prop="school_phone">
            <el-input
              v-model="referForm.school_phone"
              placeholder="填写中学联系电话"
              size="small"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="cont_title">学习成绩证明材料</div>
      <el-form-item
        label="上传申请资料图片"
        prop="backgroundPicture"
        class="bgPic"
      >
        <div class="bgInfo">1、资料包括：XXXXXXXXXXXXX；</div>
        <div class="bgInfo">
          2、请上传1-10张图片，支持JPG、JPEG、PNG等格式，每张图片不超过10M
        </div>
        <div class="image_add">
          <div class="image_in">
            <el-upload
              ref="imgUrl"
              name="multipartFile"
              list-type="picture-card"
              :disabled="isUploading || fileList.length >= 10"
              action="#"
              accept=".jpg,.jpeg,.png"
              :limit="10"
              :file-list="fileList"
              :before-upload="beforeAvatarUpload"
              :on-progress="handleUploadProgress"
              :on-success="uploadSuccess"
              :http-request="uploadPicture"
            >
              <i style="font-size: 44px" class="el-icon-circle-plus"> </i>
              <!-- <div class="text">上传材料</div> -->
              <div slot="file" slot-scope="{ file }">
                <!-- <div v-for="(item, idx) in fileList" :key="idx"> -->
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </div>

          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="resultPicture" alt="" />
          </el-dialog>
        </div>
      </el-form-item>

      <el-form-item class="btn">
        <el-button @click="confirm">提交资料</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
/* eslint-disable */
import {
  getAccount,
  getAchievementOss,
  delPic,
  setAccount,
  getProAndCity,
  getSchool,
} from "r/index/signUp";
import { upload } from "r/index/network";
import {
  validateid_card,
  validateEmail,
  validatePhone,
} from "common/validator";

export default {
  name: "CheckForm",

  data() {
    let validateContent = (rule, value, callback) => {
      // console.log(rule, value, callback);
      // console.log(this.referForm.birthday);
      if (!this.referForm.birthday) {
        callback(new Error("出生日期不能为空！"));
      } else {
        callback();
      }
    };
    let validateContents = (rule, value, callback) => {
      // console.log(rule, value, callback);
      // console.log(this.referForm.jiguan_code);
      if (!this.referForm.jiguan_code) {
        callback(new Error("籍贯不能为空！"));
      } else {
        callback();
      }
    };
    return {
      isUploading: false, // 图片上传蒙层
      referForm: {
        name: null,
        gender: null,
        id_card: null,
        birthday: null,
        jiguan_code: null,
        nation: null,
        start_school_date: null,
        political_status: null,
        // phone: null,
        email: null,
        school_province: null,
        school_city: null,
        school: null,
        school_contacts: null,
        school_phone: null,
      },
      phone: "",
      schoolName: [],
      referInfoRules: {
        name: [
          { required: true, message: "真实姓名不能为空！", trigger: "blur" },
        ],
        gender: [
          { required: true, message: "性别不能为空！", trigger: "change" },
        ],
        id_card: [
          { required: true, message: "身份证号码不能为空！", trigger: "blur" },
          { validator: validateid_card, trigger: "blur" },
        ],
        birthday: [
          {
            required: true,
            validator: validateContent,
            trigger: "change",
          },
        ],
        jiguan_code: [
          { required: true, validator: validateContents, trigger: "change" },
        ],
        nation: [
          { required: true, message: "民族不能为空！", trigger: "blur" },
        ],
        start_school_date: [
          {
            required: true,
            message: "高中入学年份不能为空！",
            trigger: "change",
          },
        ],
        political_status: [
          { required: true, message: "政治面貌不能为空！", trigger: "blur" },
        ],
        email: [
          { required: true, message: "邮箱不能为空！", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" },
        ],
        school_province: [
          {
            required: true,
            message: "请选择所在学校省份！",
            trigger: "change",
          },
        ],
        school_city: [
          {
            required: true,
            message: "请选择所在学校城市！",
            trigger: "change",
          },
        ],
        school: [
          { required: true, message: "请选择所在学校！", trigger: "change" },
        ],
        school_contacts: [
          { required: true, message: "请填写学校联系人！", trigger: "blur" },
        ],
        school_phone: [
          { required: true, message: "手机号不能为空！", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
      },
      selectProvince: [], //省份
      CityName: {}, //根据省份筛选出所有城市的对象
      selectCityJiguan: [], //籍贯城市列表
      selectCitySchool: [], //就读中学-城市列表
      selectSchoolList: [], //就读中学-中学列表
      jgProvinceCode: "", //省份id
      jiguan_city: "", //城市id(和省份id拼接)
      yearArrs: [], //生日涉及的近10年的年份
      monthArrs: [
        "01",
        "02",
        "03",
        "04",
        "05",
        "06",
        "07",
        "08",
        "09",
        "10",
        "11",
        "12",
      ],
      dayArrs: [
        "01",
        "02",
        "03",
        "04",
        "05",
        "06",
        "07",
        "08",
        "09",
        "10",
        "11",
        "12",
        "13",
        "14",
        "15",
        "16",
        "17",
        "18",
        "19",
        "20",
        "21",
        "22",
        "23",
        "24",
        "25",
        "26",
        "27",
        "28",
        "29",
        "30",
        "31",
      ],
      bdYear: "", //选择的生日年份
      bdMonth: "", //选择的生日月份
      bdDay: "", //选择的生日日期F
      // 上传的图片
      dialogImageUrl: "",
      dialogVisible: false,
      picList: [],
      fileList: [],
      resultPicture: "",
      dialogVisible: false,
      disabled: false, //限制输入框
    };
  },
  created() {
    this.phone = window.localStorage.getItem("phone"); //本地取用户手机号
    let signUpFile = window.localStorage.getItem(
      "sign_up_file_" + window.localStorage.getItem("phone")
    );
    console.log(JSON.parse(signUpFile));
    if (signUpFile && JSON.parse(signUpFile).length > 0) {
      this.fileList = JSON.parse(signUpFile);
    }
    this.getAccount();
    this.getProAndCity();
    this.getSchool();
    this.getTenYear();
  },
  watch: {
    self(val) {
      for (var k in val) {
        if (val[k] == null || !val[k]) {
          val[k] = this.referForm[k];
        }
      }
      this.selfInfo = val;
      if (val.birthday && val.birthday !== "") {
        //出生日期
        this.bdYear = val.birthday.slice(0, 4); //前4位取年
        this.bdMonth = val.birthday.slice(4, 6); //中2位取月
        this.bdDay = val.birthday.slice(6, 8); //后2位取日
      }
      if (
        val.jiguan_code &&
        val.jiguan_code !== "" &&
        val.jiguan_code !== "00"
      ) {
        //籍贯
        // console.log(val.jiguan_code, "val.jiguan_code+++++");
        this.jgProvinceCode = Number(val.jiguan_code.slice(0, 2)); //前2位取省份
        // console.log(this.jgProvinceCode, "val.jiguan_code+++++");
        this.selectJgProvince(this.jgProvinceCode, "1");
        this.jgCityCode = Number(val.jiguan_code.slice(2, 6)); //后4位取城市
        console.log(this.jgCityCode, "val.jiguan_code+++++");
      }
    },
  },
  methods: {
    //获取近10年的年份
    getTenYear() {
      let nowDate = new Date();
      let currentYear = nowDate.getFullYear();
      // console.log(nowDate, currentYear);
      let yearArr = [];
      let rxYearArr = [];
      for (let i = 0; i < 22; i++) {
        let year = currentYear - i;
        yearArr.push(year);
      }
      // console.log(yearArr, "yearArr");
      for (let i = 0; i < 10; i++) {
        let year = currentYear - i;
        rxYearArr.push(year);
      }
      this.yearArrs = yearArr;
      this.rxYearArrs = rxYearArr;
    },
    // 页面信息个人获取
    getAccount() {
      getAccount({}).then((res) => {
        // console.log(res, "getAccount");
        if (res.data.code != 200) {
          return this.$message.error(res.data.message);
        }
      });
    },
    getTime() {
      this.referForm.birthday =
        this.bdYear.toString() +
        this.bdMonth.toString() +
        this.bdDay.toString(); //组装出生日期
      // console.log(this.referForm.birthday);
    },
    getJiguan() {
      this.referForm.jiguan_code =
        this.jgProvinceCode.toString() + this.jiguan_city.toString();
      // console.log(this.referForm.jiguan_code);
    },

    // 获取省份城市
    getProAndCity() {
      getProAndCity({}).then((res) => {
        // console.log(res, "getProAndCity");
        if (res.data.code != 200) {
          return this.$message.error(res.data.message);
        }
        this.selectProvince = res.data.province_list;
        this.CityName = res.data.city_list;
      });
    },
    changeProvince(type, value) {
      // console.log(value, "value");
      let selectCity = [];
      for (const key in this.CityName) {
        if (this.CityName[key].parent_id == value) {
          selectCity.push(this.CityName[key]);
        }
      }
      if (type == 1) {
        this.selectCityJiguan = selectCity;
        this.jiguan_city = "";
      } else {
        this.selectCitySchool = selectCity;
        this.referForm.school_city = "";
        this.referForm.school = "";
      }
    },
    changeCity(value) {
      let selectSchool = [];
      for (const key in this.schoolName) {
        if (this.schoolName[key].city_id == value) {
          selectSchool.push(this.schoolName[key]);
        }
      }
      this.selectSchoolList = selectSchool;
      this.referForm.school = "";
    },

    // 获取学校
    getSchool() {
      getSchool({}).then((res) => {
        // console.log(res, "getSchool");
        if (res.data.code != 200) {
          return this.$message.error(res.data.message);
        }
        this.schoolName = res.data.school_list;
      });
    },

    // 图片上传成功前钩子
    beforeAvatarUpload(file) {
      console.log(file, "beforeImage");
      const isJPG = file.type === "image/jpg";
      const isPng = file.type === "image/png";
      const isJPEG = file.type === "image/jpeg";
      const isLt10M = file.size / 1024 / 1024 < 10;
      //  console.log(isLt10M)
      if (!isJPG && !isPng && !isJPEG) {
        this.$message.info("上传图片只能是 JPG,JPEG或png 格式!");
      }
      if (!isLt10M) {
        this.$message.info("上传图片大小不能超过 10MB!");
      }
      return (isJPG || isPng || isJPEG) && isLt10M;
    },

    handlePictureCardPreview(file) {
      console.log(file);
      this.resultPicture = file.url;
      this.dialogVisible = true;
    },
    // 文件上传中处理
    handleUploadProgress(event, file, fileList) {
      console.log(fileList);
      this.isUploading = true;
      if (this.fileList.lenge < 10) {
        return this.$message.info("chaochushuliamng");
      }
    },
    uploadSuccess(res, file) {
      // console.log(res, "111");
      this.referForm.achievementPath = res;
      this.fileList[0] = {
        name: file.name,
        url: res,
      };
      this.$refs["imgUrl"].clearFiles(); //上传成功之后清除历史记录
    },
    uploadPicture(params) {
      // console.log("已经准备好上传图片", params);
      this.file = params.file;
      let raw = params.file;
      let image = {
        name: raw.name,
        size: raw.size,
        type: raw.type,
      };
      this.getOssConfigs(image, params.file);
    },
    async getOssConfigs(image, file) {
      let obj = {
        url: "",
        savefile: "",
      };
      await getAchievementOss({ image: image })
        .then((res) => {
          console.log(res, "开始上传图片");
          if (res.data.code === 200) {
            let oss_url = res.data.config.host;
            let filename = res.data.config.file;

            let formData = new FormData();
            formData.append("OSSAccessKeyId", res.data.config.accessid);
            formData.append("policy", res.data.config.policy);
            formData.append("signature", res.data.config.signature);
            formData.append("filename", res.data.config.file);
            formData.append("key", res.data.config.savefile);
            formData.append("callback", res.data.config.callback);
            formData.append("success_action_status", 200);
            formData.append("file", file);
            // console.log(formData);
            upload(oss_url, formData)
              .then((ress) => {
                console.log(ress, "ress");
                if (ress.data.code != 200) {
                  console.log(ress, "ress");
                  return this.$message.error(ress.data.message);
                }
                this.resultPicture = filename + "?t=" + Date.parse(new Date());
                this.$forceUpdate();
                this.$message.success("上传成功");
                obj = {
                  url: ress.data.picture_path,
                  savefile: res.data.config.savefile,
                };
                this.fileList.push(obj);
                console.log(this.fileList, " this.fileList");
                window.localStorage.setItem(
                  "sign_up_file_" + window.localStorage.getItem("phone"),
                  JSON.stringify(this.fileList)
                );
              })
              .catch((err) => {
                this.$message.error(err);
              });
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //删除图片
    handleRemove(file) {
      let savefile = file.savefile;
      delPic({ object: savefile }).then((res) => {
        console.log(res, "delpic");
        if (res.data.code != 200) {
          return this.$message.error(res.data.message);
        }
        // delete this.fileList[idx];

        this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.fileList.forEach((item, idx) => {
              console.log(item.url == file.url);
              if (item.url == file.url) {
                this.fileList.splice(idx, 1);
                window.localStorage.setItem(
                  "sign_up_file_" + window.localStorage.getItem("phone"),
                  JSON.stringify(this.fileList)
                );
              }
            });
            console.log(this.fileList);

            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      });
    },
    confirm() {
      this.$refs["referRef"].validate((valid) => {
        console.log(valid);
        if (!valid) return;
        console.log("11", valid);
        // return;
        setAccount(this.referForm).then((res) => {
          console.log(res, "setAccount");
          if (res.data.code != 200) {
            return this.$message.error(res.data.message);
          }
          this.$emit("getstatus", res.data.status);
          this.$message.success("提交审核成功");
          this.$router.push("/signUp/check");
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "a/scss/btn";
.referInfo {
  padding: 0 50px 110px 50px;
  .checkForm {
    flex: 1;
    .cont_title {
      height: 48px;
      line-height: 48px;
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #12141c;
    }

    ::v-deep .el-form-item {
      margin-bottom: 20px;

      .el-form-item__label {
        height: 32px;
        line-height: 32px;
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #12141c;
      }

      .el-form-item__content {
        // height: 40px;
        // line-height: 40px;

        .el-input {
          height: 40px;

          .el-input__inner {
            height: 40px;
            line-height: 40px;
            border-radius: 4px;
            border: 1px solid #e1e3e6;
            background-color: #ffffff;

            &:hover {
              border-color: var(--color);
            }

            &:focus {
              border-color: var(--color);
            }
          }
        }
        // 圆
        .el-radio-group {
          .el-radio {
            .el-radio__label {
              color: #656872;
            }

            .el-radio__input {
              .el-radio__inner {
                width: 20px;
                height: 20px;
                line-height: 20px;
                border-radius: 50%;
                &:hover {
                  border-color: var(--color);
                }
              }

              &.is-checked {
                .el-radio__inner {
                  background: #ffffff !important;
                  border-color: var(--color);

                  &::after {
                    width: 7.5px;
                    height: 7.5px;
                    background: var(--color) !important;
                  }
                }
              }
            }
          }
        }
      }

      &.btn {
        .el-form-item__content {
          text-align: center;
        }
      }

      &.bgPic {
        // height: 260px;
        .el-form-item__label {
          font-size: 14px;
        }
        .bgInfo {
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 500;
          color: #a7a2a6;
          line-height: 24px;
        }
      }
      .el-select {
        width: 100%;
      }
      .image_add {
        position: relative;
        margin-top: 24px;
        .image_in {
          .limit_10 {
            display: none;
          }
          .el-upload-list--picture-card {
            .item_img {
              width: 100%;
            }
          }
        }
        //去除upload组件过渡效果 css
        .el-upload-list__item {
          transition: none !important;
          div {
            height: 100%;
          }
        }
        .el-upload--picture-card {
          display: inline-block;
        }
        .el-upload {
          position: relative;
          .el-icon-circle-plus {
            font-size: 52px;
            color: var(--color);
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
        i {
          font-size: 52px;
          color: var(--color);
        }
        .text {
          font-size: 14px;
          color: #a7a2a6;
          text-align: center;
        }
      }
   
    }
  }
}
</style>
