<template>
  <div>
    <el-dialog
      class="modify-course-outline-target"
      :visible.sync="modalIsShow"
      :title="title"
      top="10vh"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @open="visibleChange"
    >
      <el-form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        :key="modalForm.id"
        label-width="120px"
      >
        <el-form-item prop="targetName" label="课程目标名称：">
          <el-input
            v-model.trim="modalForm.targetName"
            placeholder="请输入课程目标名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="obeCultureProgramRequirementId"
          label="毕业要求指标点："
        >
          <requirement-select
            v-if="modalIsShow"
            v-model="modalForm.obeCultureProgramRequirementId"
            :tree-data="requirementList"
            @change="requirementChange"
          ></requirement-select>

          <el-button
            type="text"
            class="btn-primary ml-1"
            icon="el-icon-circle-plus-outline"
            @click="toSelectDimension"
            >选择知识点</el-button
          >
        </el-form-item>
        <el-form-item prop="degreeRequirement" label="目标分解详情：">
          <el-input
            v-model="modalForm.degreeRequirement"
            placeholder="请输入目标分解详情"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 6 }"
            :maxlength="999"
            resize="none"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" :disabled="isSubmit" @click="submit"
          >确认</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- SelectDimensionDialog -->
    <select-dimension-dialog
      ref="SelectDimensionDialog"
      :param="{ obeCourseOutlineId: instance.obeCourseOutlineId }"
      :selected-data="modalForm.dimensionIdList"
      :disabled-data="disabledDimensionIds"
      @confirm="dimensionSelected"
      @enforce-close="enforceClose"
    ></select-dimension-dialog>
  </div>
</template>

<script>
import {
  updateCourseOutlineTarget,
  courseOutlineTargetRequirementKnowledge,
} from "../../api";
import RequirementSelect from "./RequirementSelect.vue";
import SelectDimensionDialog from "./SelectDimensionDialog.vue";
import { mapState } from "vuex";

const initModalForm = {
  id: null,
  obeCourseOutlineId: "",
  targetName: "",
  degreeRequirement: "",
  obeCultureProgramRequirementId: "",
  dimensionIdList: [],
};

export default {
  name: "modify-course-outline-target",
  components: { SelectDimensionDialog, RequirementSelect },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
    dimensions: {
      type: Array,
      default() {
        return [];
      },
    },
    requirementList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  computed: {
    ...mapState("target", ["cwStatus"]),
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "课程目标";
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      dimensionList: [],
      disabledDimensionIds: [],
      rules: {
        targetName: [
          {
            required: true,
            message: "请输入课程目标名称",
            trigger: "change",
          },
          {
            max: 30,
            message: "课程目标名称不能超过30个字",
            trigger: "change",
          },
        ],
        obeCultureProgramRequirementId: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请选择毕业要求指标点"));
              }

              if (!this.modalForm.dimensionIdList.length) {
                return callback(new Error("请选择知识点"));
              }

              return callback();
            },
          },
        ],
        degreeRequirement: [
          {
            required: false,
            max: 999,
            message: "目标分解详情不能超过999个字",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);
      if (val.dimensionList) {
        this.dimensionList = [...val.dimensionList];
        this.updateDimensionIds();
      } else {
        this.dimensionList = [];
        this.modalForm.dimensionIdList = [];
      }
      this.updateDisabledDimensionIds(
        this.modalForm.obeCultureProgramRequirementId
      );
    },
    visibleChange() {
      this.initData(this.instance);
    },
    enforceClose() {
      this.modalIsShow = false;
      this.$emit("enforce-close");
    },
    async requirementChange() {
      this.modalForm.dimensionIdList = [];
      if (!this.modalForm.obeCultureProgramRequirementId) return;
      const res = await courseOutlineTargetRequirementKnowledge({
        obeCourseOutlineId: this.instance.obeCourseOutlineId,
        obeCultureProgramRequirementId:
          this.modalForm.obeCultureProgramRequirementId,
      });

      this.modalForm.dimensionIdList = (res || []).map((item) => item.id);
      this.$refs.modalFormComp.validateField("obeCultureProgramRequirementId");
      this.updateDisabledDimensionIds(
        this.modalForm.obeCultureProgramRequirementId
      );
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    toSelectDimension() {
      if (!this.modalForm.obeCultureProgramRequirementId) {
        this.$message.error("请选择毕业要求指标点");
        return;
      }

      this.$refs.SelectDimensionDialog.open();
    },
    updateDimensionIds() {
      this.modalForm.dimensionIdList = this.dimensionList.map(
        (item) => item.id
      );
    },
    updateDisabledDimensionIds(obeCultureProgramRequirementId) {
      this.disabledDimensionIds = this.dimensions
        .filter((item) => item.requirementId !== obeCultureProgramRequirementId)
        .map((item) => item.dimensionIds)
        .flat();
    },
    dimensionSelected(dimensions) {
      this.dimensionList = [...dimensions];
      this.updateDimensionIds();
      this.$refs.modalFormComp.validateField("obeCultureProgramRequirementId");
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.cwStatus.everSettingStatus) {
        const confirm = await this.$confirm(
          `${this.title}会影响权重设置，确定要${this.title}吗?`,
          "提示",
          {
            type: "warning",
          }
        ).catch(() => {});
        if (confirm !== "confirm") return;
      }

      if (this.isSubmit) return;
      this.isSubmit = true;
      const res = await updateCourseOutlineTarget(this.modalForm).catch(
        () => {}
      );
      this.isSubmit = false;

      if (!res) return;

      this.$message.success(this.title + "成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
