<template>
  <div class="info" id="workexp">
    <header class="sign-new-header">
      <div class="sign-new-header-title">工作经历（必填）</div>
      <span>
        <el-button
          v-if="experience.length > 0"
          @click="showRankDialog"
          type="text"
          >设置优先展示</el-button
        >
        <el-dialog
          title="设置优先展示工作经历"
          :visible.sync="rankDialog"
          :before-close="handleRankClose"
        >
          <el-form ref="form" :model="rankForm" class="first-form">
            <el-radio-group v-model="rankForm.first">
              <template v-for="(item, idx) in experience">
                <el-radio :label="item.id" :value="item.id" :key="item.id">
                  <div class="first-radio">
                    <span class="des">
                      <span>{{ item.company }}</span>
                      <span>{{ item.title }}</span>
                    </span>
                    <el-button @click="editItem(item, idx)" type="text"
                      >编辑</el-button
                    >
                  </div>
                </el-radio>
              </template>
            </el-radio-group>
          </el-form>
          <div class="first-tips">
            <h6>温馨提示</h6>
            <p>
              1.
              只有上传过工作证明且通过认证的工作经历，才可选择设置为"优先展示工作经历"
              <br />2. 修改公司,
              职位信息，"保存"成功后，客栈将在一个工作日内完成审核，审核通过后，即可生效
            </p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="rankDialog = false">取 消</el-button>
            <el-button type="primary" @click="handleRank">确 定</el-button>
          </span>
        </el-dialog>
        <el-button @click="handleAdd" type="text" icon="el-icon-plus"
          >添加</el-button
        >
      </span>
    </header>
    <div v-if="experience.length > 0">
      <template v-for="(item, idx) in experience">
        <div v-if="editingItem.indexOf(idx) < 0" :key="item.id" class="show">
          <h4>
            <span>{{
              `${item.start_time} - ${item.end_time || "至今"} ${
                item.company
              } ${item.title}`
            }}</span>
            <span v-if="item.is_main == '1'" class="first">优先展示</span>
            <span v-if="item.isAuth == 1" class="verify">已认证</span>
            <img
              @click="editItem(item, idx)"
              src="~/assets/img/svg/edit.svg"
              class="sign-edit-icon"
            />
          </h4>
          <p>{{ item.description }}</p>
        </div>
        <stepExperienceForm
          v-else
          :key="`experience${idx}`"
          :idx="idx"
          :item="item"
          :handleCancel="handleCancel"
          :handleConfirm="handleConfirm"
          :handleDelete="handleDelete"
        ></stepExperienceForm>
      </template>
    </div>
    <div v-else class="empty">点击右上角“添加”按钮添加工作经历</div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import experienceForm from "./experience-form";
import stepExperienceForm from "./step-experience-form";

export default {
  data() {
    return {
      // editing: true,
      editingItem: [],
      rules: {},
      init: {
        work_certify_img: "",
        start_time: "",
        date: [],
        end_time: "",
        company: "",
        title: "",
        is_main: 0,
        description: ""
      },
      experience: [],
      originExperience: [],
      current: null,
      rankDialog: false,
      rankForm: {
        first: ""
      }
    };
  },
  components: {
    experienceForm,
    stepExperienceForm
  },
  computed: {
    ...mapState(["userinfo"])
  },
  watch: {
    experience: function(val) {
      this.$emit("workExperienceChange", val);
    }
  },
  async mounted() {
    this.getData();
  },
  methods: {
    async onSubmit() {
      console.log("submit!", this.originExperience);
      if (this.originExperience.length > 10) {
        this.$message.error("最多可添加10项工作经历!");
      }
      const res = await this.$axios.$post("/api/user_experience/save_all", {
        data: JSON.stringify(this.originExperience)
      });
      if (res.status === 1) {
        this.$message.success("保存成功！");
        this.getData();
      } else if (res.status === 2 && res.info.indexOf("管理员审核") > -1) {
        // 保存工作经历，需要审核时，同样重新获取数据
        this.getData();
      }
      else{
        this.getData();
      }
    },
    async getData() {
      const res = await this.$axios.$post("/api/user_experience/get_my_list");
      const data = res.data || [];
      const experience = data.map((it, index) => {
        if (it.is_main == "1") {
          this.rankForm.first = it.id;
        }
        return {
          ...it,
          date: [it.start_time, it.end_time]
        };
      });
      this.experience = experience;
      this.originExperience = data;
    },
    handleRankClose() {
      this.rankDialog = false;
      // this.rankForm = {
      //   first: ""
      // };
    },
    handleRank() {
      let idx = 0;
      this.experience.map((it, index) => {
        if (it.id == this.rankForm.first) {
          idx = index;
        }
        return it;
      });
      // this.experience.forEach((item, index) => {
      //   if (idx === index) {
      //     item.is_main = 1;
      //   } else {
      //     item.is_main = 0;
      //   }
      // })
      this.originExperience.forEach((item, index) => {
        if (idx === index) {
          item.is_main = 1;
        } else {
          item.is_main = 0;
        }
      });

      this.onSubmit();
      this.rankDialog = false;
    },
    handleAdd() {
      if (this.userinfo && this.userinfo.realname_verify_status === "0") {
        this.$message.error("请先进行实名认证");
        return;
      }
      if (
        this.editingItem.length > 0 &&
        !this.experience[this.editingItem[0]].id
      ) {
        this.$message.error("请先保存现有修改");
        return;
      }
      const _init = JSON.parse(JSON.stringify(this.init));
      this.experience.push(_init);
      this.editingItem = [this.experience.length - 1];
    },
    handleDelete(item, idx) {
      this.experience.splice(idx, 1);
      this.originExperience.splice(idx, 1);
      this.editingItem = [];
      this.onSubmit();
    },
    handleCancel(item, idx) {
      const origin = this.originExperience.slice(idx, idx + 1)[0];

      if (!origin) {
        this.editingItem = [];
        this.experience.splice(idx, 1);
      } else {
        const originCopy = JSON.parse(JSON.stringify(origin));
        originCopy.date = [origin.start_time, origin.end_time];
        this.editingItem = [];
        if (!item.id) {
          this.experience.splice(idx, 1);
        } else {
          this.experience.splice(idx, 1, originCopy);
        }
      }
    },
    handleConfirm(item, idx) {
      this.cnzz("签约", "签约页面+工作经历保存", "");
      const origin = this.originExperience.slice(idx, idx + 1)[0];
      // 编辑 item 时，item 对象中的 key 顺序均相同，可直接使用 JSON.stringify 做比较
      let itemCopy = JSON.parse(JSON.stringify(item));
      delete itemCopy["date"];
      if (JSON.stringify(itemCopy) == JSON.stringify(origin)) {
        this.$message.error("请修改后保存!");
        return;
      }
      // if (item == origin) {
      //   this.$message.error("请修改后保存!");
      //   return;
      // }
      console.log(item.date);
      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.company || !item.title) {
        this.$message.error("请设置公司名称/职位!");
        return;
      }
      if (!item.description || item.description.length < 40) {
        this.$message.error("经历描述不少于40字符!");
        return;
      }
      this.editingItem = [];
      item.start_time = item.date[0];
      item.end_time = item.date[1];
      this.originExperience.splice(idx, 1, item);
      this.onSubmit();
    },
    editItem(item, idx) {
      this.rankDialog = false;
      this.editingItem = [idx];
    },
    showRankDialog() {
      if (this.experience.length < 1) {
        this.$message.error("请先添加工作经历");
        return false;
      }
      this.rankDialog = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.info {
  header .el-icon-plus {
    font-size: 18px;
  }
  .first,
  .verify {
    width: 70px;
    height: 32px;
    background: rgba(48, 142, 255, 1);
    border-radius: 2px;
    text-align: center;
    font-size: 12px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    color: rgba(255, 255, 255, 1);
    line-height: 32px;
  }
  .verify {
    background: #fff;
    border-radius: 2px;
    color: rgba(16, 185, 106, 1);
    border: 1px solid rgba(16, 185, 106, 1);
  }

  .show {
    // padding: 18px 0;
    border-bottom: 1px solid #ebeef5;
    word-break: break-all;

    h4 {
      position: relative;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height: 60px;
      line-height: 60px;
      font-size: 15px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #0b121a;
      span {
        margin-right: 20px;
      }
      button {
        position: absolute;
        right: 0;
      }
    }
    p {
      border-top: 1px solid #ebeef5;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(102, 102, 102, 1);
      line-height: 24px;
      padding: 18px 0;
    }
  }
  .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;
  }
  .first-form {
    margin-left: 40px;
    .el-radio-group {
      display: flex;
      flex-direction: column;
    }
  }
  .first-radio {
    position: relative;
    display: inline-flex;
    justify-content: space-between;
    align-items: center;
    width: 350px;
    margin: 0 20px 20px;
    .des span {
      margin-right: 40px;
    }
  }
  .first-tips {
    margin-top: 10px;
    h6 {
      font-size: 16px;
      margin-bottom: 20px;
    }
    p {
      font-size: 14px;
      line-height: 1.4;
    }
  }

  .sign-edit-icon {
    position: absolute;
    right: 20px;
  }
}
</style>
