<template>
  <div class="education">
    <header>
      <h5>教育经历</h5>
      <span>
        <el-button @click="handleAdd" type="text" icon="el-icon-plus"></el-button>
      </span>
    </header>
    <div v-if="education.length > 0">
      <template v-for="(item, idx) in education">
        <div v-if="editingItem.indexOf(idx) < 0" :key="item.university" class="show">
          <h4>
            <span>{{`${item.start_time} - ${item.end_time || '至今'} ${item.university} ${item.major}`}}</span>
            <el-button @click="editItem(idx)" type="text">编辑</el-button>
          </h4>
          <p>{{item.description}}</p>
        </div>
        <div v-else :key="'education' + idx" class="edit">
          <el-form ref="form" :rules="rules" :model="item" label-width="147px">
            <div class="header">
              <date-range class="range" v-model="item.date"></date-range>
              <el-select
                v-model="item.university"
                allow-create
                filterable
                remote
                reserve-keyword
                placeholder="学校名称"
                :remote-method="fetchUniversity"
                :loading="loadingUniversity"
              >
                <el-option
                  v-for="item in universities"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
              <el-select
                class="small"
                v-model="item.major"
                allow-create
                filterable
                remote
                reserve-keyword
                placeholder="选择专业"
                :remote-method="fetchMajor"
                :loading="loadingMajor"
              >
                <el-option
                  v-for="item in majors"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
              <el-select class="small" v-model="item.education_background" placeholder="学历">
                <el-option
                  v-for="educationBackground in educationBackgrounds"
                  :key="educationBackground.value"
                  :label="educationBackground.label"
                  :value="educationBackground.value"
                ></el-option>
              </el-select>
              <span class="opts">
                <el-button type="danger" @click="handleDelete(idx, item)">删除</el-button>
                <el-button type="info" @click="handleCancel(idx, item)">取消</el-button>
                <el-button type="primary" @click="handleConfirm(idx, item)">保存</el-button>
              </span>
            </div>
            <div>
              <el-input class="big" v-model="item.diploma_url" placeholder="请输入学信网在线验证报告地址"></el-input>
            </div>
            <div class="content">
              <el-input
                type="textarea"
                :rows="7"
                placeholder="教育经历文字说明，不得低于15个字符"
                v-model="item.description"
              ></el-input>
              <uploader
                :imageUrl="item.diploma_photo"
                title="毕业证图片"
                @change="val => handleImageUrl(idx, val)"
              ></uploader>
            </div>
            <footer>
              <p>学信网在线验证报告, 例如：https://www.proginn.com</p>
              <p>注：学历证明可以是毕业证图片或学信网在线验证报告（二选一即可）</p>
            </footer>
          </el-form>
        </div>
      </template>
    </div>
    <div v-else class="empty">点击右上角“添加”按钮添加教育经历</div>
  </div>
</template>

<script>
import uploader from "@/components/uploader";
import dateRange from "@/components/date-range";
import { mapState } from "vuex";
export default {
  data() {
    return {
      // editing: true,
      editingItem: [],
      rules: {
        name: ""
      },
      init: {
        diploma_photo: "",
        diploma_url: "",
        start_time: "",
        end_time: "",
        date: [],
        university: "",
        major: "",
        education_background: "",
        description: ""
      },
      education: [],
      current: null,
      originEducation: [],
      universities: [],
      loadingUniversity: false,
      majors: [],
      loadingMajor: false,
      educationBackgrounds: []
    };
  },
  components: {
    uploader,
    dateRange
  },
  computed: {
    ...mapState(["userinfo"])
  },
  watch: {},
  async mounted() {
    this.getData();
    this.getEducationBackground();
  },
  methods: {
    async onSubmit(idx) {
      console.log("submit!", this.education);
      if (this.education.length > 10) {
        this.$message.error("最多可添加10项工作经历!");
      }
      const data = this.education.map(it => ({
        diploma_photo: it.diploma_photo,
        diploma_url: it.diploma_url,
        start_time: it.date[0],
        end_time: it.date[1],
        university: it.university,
        major: it.major,
        education_background: it.education_background,
        description: it.description
      }));
      const res = await this.$axios.$post("/api/user_education/save_all", {
        data: JSON.stringify(data)
      });
      if (res.status === 1) {
        this.$message.success("保存成功！");
        this.init = {
          diploma_photo: "",
          diploma_url: "",
          start_time: "",
          end_time: "",
          date: [],
          university: "",
          major: "",
          education_background: "",
          description: ""
        };
        this.getData();
        return true;
      } else {
        this.$message.error(res.info);
        return false;
      }
    },
    async getData() {
      const res = await this.$axios.$post("/api/user_education/list");
      const data = res.data || [];
      const education = data.map(it => ({
        ...it,
        date: [it.start_time || "", it.end_time || ""]
      }));
      console.log(education);
      this.education = education;
    },
    async getEducationBackground() {
      const res = await this.$axios.$post(
        "/api/simple_data/select_education_background"
      );
      const data = res.data || [];
      this.educationBackgrounds = data.map(it => ({
        value: it.id,
        label: it.name
      }));
    },
    async fetchUniversity(keyword) {
      console.log(keyword);
      this.loadingUniversity = true;
      const res = await this.$axios.$post(
        "/api/simple_data/select_university",
        { keyword }
      );
      this.loadingUniversity = false;
      const data = res.data || [];
      this.universities = data.map(it => ({ value: it.id, label: it.name }));
    },
    async fetchMajor(keyword) {
      console.log(keyword);
      this.loadingMajor = true;
      const res = await this.$axios.$post("/api/simple_data/select_major", {
        keyword
      });
      this.loadingMajor = false;
      const data = res.data || [];
      this.majors = data.map(it => ({ value: it.id, label: it.name }));
    },
    handleRankClose() {
      this.rankForm = {
        first: ""
      };
    },
    handleRank() {
      this.rankDialog = false;
    },
    handleAdd() {
      if (this.userinfo && this.userinfo.realname_verify_status === "0") {
        this.$message.error("请先进行实名认证");
        return;
      }
      if (
        this.editingItem.length > 0 &&
        !this.education[this.editingItem[0]].id
      ) {
        this.$message.error("请先保存现有修改");
        return;
      }
      this.education.push(this.init);
      this.editingItem = [this.education.length - 1];
    },
    handleImageUrl(idx, url) {
      this.education[idx].diploma_photo = url;
    },
    async handleDelete(idx) {
      this.editingItem = [];
      this.education.splice(idx, 1);
      await this.onSubmit();
    },
    handleCancel(idx, item) {
      this.editingItem = [];
      if (!item.id) {
        this.education.splice(idx, 1);
      }
    },
    handleConfirm(idx, item) {
      // const item = this.education.slice(idx, idx + 1)[0];
      if (!item.date) {
        this.$message.error("请设置开始时间/结束时间!");
        return;
      } else if (
        item.date &&
        item.date[0] &&
        item.date[1] &&
        item.date[0] > item.date[1]
      ) {
        this.$message.error("请设置开始时间小于结束时间!");
        return;
      }
      if (!item.university || !item.major || !item.education_background) {
        this.$message.error("请设置学校名称/专业/学历!");
        return;
      }
      if (!item.description || item.description.length < 15) {
        this.$message.error("教育经历不得低于15个字符");
        return;
      }
      // if (!item.diploma_url && !item.diploma_photo) {
      //   this.$message.error("请提供学历证明!");
      //   return;
      // }
      this.editingItem = [];
      // const submitItem = {
      //   ...item,
      //   start_time: item.date[0],
      //   end_time: item.date[1]
      // };
      this.onSubmit();
    },
    editItem(idx) {
      if (this.userinfo && this.userinfo.realname_verify_status === "0") {
        this.$message.error("请先进行实名认证");
        return;
      }
      this.editingItem = [idx];
    }
  }
};
</script>

<style lang="scss" scoped>
.education {
  header .el-icon-plus {
    font-size: 18px;
  }
  .edit {
    padding: 20px;
    > form {
      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      .range {
        margin-right: 10px;
      }
      .opts {
        display: flex;
        align-items: center;
        .el-button {
          margin-left: 5px;
        }
      }
      .el-select,
      .el-input {
        width: 136px;
        margin-right: 10px;
        .el-input--suffix .el-input__inner {
          padding-right: 0;
        }
      }
      .small {
        width: 140px;
      }
      .big {
        width: 100%;
      }
      .times {
        .el-checkbox {
          width: 88px;
        }
        .el-input {
          width: 160px;
        }
      }
      .content {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-top: 10px;
        .el-textarea {
          display: flex;
          width: 766px;
          height: 162px;
        }
      }
    }
  }
  .show {
    padding: 23px 33px 23px 20px;
    border-bottom: 1px solid #ebeef5;
    &:last-of-type {
      border: 0;
    }
    h4 {
      display: flex;
      justify-content: space-between;
      height: 44px;
      font-size: 14px;
      font-family: PingFangSC-Medium;
      font-weight: 500;
      color: #308eff;
      line-height: 44px;
    }
    p {
      word-break: break-all;
      margin-top: 8px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(102, 102, 102, 1);
      line-height: 24px;
    }
  }

  .empty {
    margin: 112px auto 104px;
    font-size: 27px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    text-align: center;
    color: rgba(205, 205, 205, 1);
    line-height: 38px;
  }
  footer p {
    margin-top: 15px;
    width: 766px;
    font-size: 12px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(145, 154, 167, 1);
    line-height: 17px;
  }
}
</style>
