<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="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-act-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 { updateCourseOutlineTarget } from "../../api";
import SelectDimensionDialog from "../../../base/components/course-simple/SelectDimensionDialog.vue";

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

export default {
  name: "modify-course-outline-target",
  components: { SelectDimensionDialog },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    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.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>
