<template>
  <div>
    <el-dialog
      class="modify-course-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="100px"
      >
        <el-form-item prop="targetName" label="课程目标：">
          <el-input
            v-model.trim="modalForm.targetName"
            placeholder="请输入课程目标"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="dimensionIdList" label="毕业要求指标：">
          <el-button
            type="text"
            class="btn-primary"
            icon="el-icon-circle-plus-outline"
            @click="toSelectDimension"
            >选择知识点</el-button
          >
          <el-table
            v-if="dimensionList.length"
            :data="dimensionList"
            :show-header="false"
            border
          >
            <el-table-column prop="name" label="知识点">
              <template slot-scope="scope">
                {{ scope.row.name }}（{{ scope.row.code }}）
              </template>
            </el-table-column>
            <el-table-column
              class-name="action-column"
              label="操作"
              width="40"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  class="btn-danger"
                  icon="el-icon-error"
                  @click="toDeleteDimension(scope.$index)"
                >
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </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"
      :course="{ teachCourseId: instance.teachCourseId }"
      :selected-data="modalForm.dimensionIdList"
      :disabled-data="instance.disabledDimensionIds"
      @confirm="dimensionSelected"
      @enforce-close="enforceClose"
    ></select-dimension-dialog>
  </div>
</template>

<script>
import { updateCourseTarget } from "../../api";
import SelectDimensionDialog from "./SelectDimensionDialog.vue";
import { mapState } from "vuex";

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

export default {
  name: "modify-course-target",
  components: { SelectDimensionDialog },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    ...mapState("base", ["cwStatus"]),
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "课程目标";
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      dimensionList: [],
      rules: {
        targetName: [
          {
            required: true,
            message: "请输入课程目标",
            trigger: "change",
          },
          {
            max: 30,
            message: "课程目标不能超过30个字",
            trigger: "change",
          },
        ],
        dimensionIdList: [
          {
            validator: (rule, value, callback) => {
              if (value && value.length) {
                return callback();
              }
              return callback(new Error("请选择毕业要求指标"));
            },
          },
        ],
        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 = [];
      }
    },
    visibleChange() {
      this.initData(this.instance);
    },
    enforceClose() {
      this.modalIsShow = false;
      this.$emit("enforce-close");
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    toSelectDimension() {
      this.$refs.SelectDimensionDialog.open();
    },
    updateDimensionIds() {
      this.modalForm.dimensionIdList = this.dimensionList.map(
        (item) => item.id
      );
    },
    dimensionSelected(dimensions) {
      this.dimensionList = [...dimensions];
      this.updateDimensionIds();
      this.$refs.modalFormComp.validateField("dimensionIdList");
    },
    toDeleteDimension(index) {
      this.dimensionList.splice(index, 1);
      this.updateDimensionIds();
      this.$refs.modalFormComp.validateField("dimensionIdList");
    },
    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 updateCourseTarget(this.modalForm).catch(() => {});
      this.isSubmit = false;

      if (!res) return;

      if (res.warning) {
        this.$notify({
          title: "警告",
          message: "课程目标有变化，请重新设置权重设置！",
          type: "warning",
          duration: 5000,
        });
      }

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