<template>
  <div>
    <el-dialog
      class="modify-course"
      :visible.sync="modalIsShow"
      :title="title"
      top="10vh"
      width="700px"
      :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="130px"
      >
        <el-form-item prop="semesterId" label="学期：">
          <el-select
            v-model="modalForm.semesterId"
            placeholder="学期"
            filterable
            :disabled="isEdit"
            @change="semesterChange"
          >
            <el-option
              v-for="item in semesterList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="examId" label="考试：">
          <el-select
            v-model="modalForm.examId"
            placeholder="考试"
            filterable
            :disabled="isEdit"
          >
            <el-option
              v-for="item in examList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学年（考务）：">
          <el-input
            v-model.trim="modalForm.xn"
            placeholder="请输入学年（考务）"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="学期（考务）：">
          <el-input
            v-model.trim="modalForm.xq"
            placeholder="请输入学期（考务）"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="考试名称（考务）：">
          <el-input
            v-model.trim="modalForm.ksmc"
            placeholder="请输入考试名称（考务）"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="dataType" label="同步数据类型：">
          <el-checkbox-group v-model="modalForm.dataType">
            <el-checkbox
              v-for="(val, key) in DATABASE_SYNC_TYPE"
              :key="key"
              :label="key"
              >{{ val }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="startTime" label="同步开始时间：">
          <el-date-picker
            v-model="modalForm.startTime"
            type="datetime"
            value-format="timestamp"
            placeholder="选择时间"
            @change="() => timeChange('startTime')"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="endTime" label="同步结束时间：">
          <el-date-picker
            v-model="modalForm.endTime"
            type="datetime"
            value-format="timestamp"
            placeholder="选择时间"
            @change="() => timeChange('endTime')"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="cron" label="定时同步时间：">
          <el-input
            v-model.trim="modalForm.cron"
            placeholder="请输入定时同步时间"
            clearable
          ></el-input>
          <p class="tips-info">如：每天1点开始同步，0 0 1 * * ?</p>
        </el-form-item>
        <el-form-item prop="phoneNumber" label="同步异常预警：">
          <el-input
            v-model.trim="modalForm.phoneNumber"
            placeholder="请输入同步异常预警"
            clearable
          ></el-input>
          <p class="tips-info">支持填写多个手机号，用英文,隔开</p>
        </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>
  </div>
</template>

<script>
import { schoolSetDatabaseSyncUpdate } from "../../api";
import { conditionListSemester, conditionListExam } from "../../../base/api";
import { DATABASE_SYNC_TYPE } from "@/constants/enumerate";

const initModalForm = {
  semesterId: "",
  examId: "",
  dataType: "",
  startTime: "",
  endTime: "",
  cron: "0 0 1 * * ?",
  phoneNumber: "",
  xn: "",
  xq: "",
  ksmc: "",
};

export default {
  name: "modify-database-sync",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
    schoolId: {
      type: String,
      default: "",
    },
  },
  computed: {
    isEdit() {
      return !!this.instance.examId;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "同步记录";
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      DATABASE_SYNC_TYPE,
      modalForm: { ...initModalForm },
      rules: {
        semesterId: [
          {
            required: true,
            message: "请选择学期",
            trigger: "change",
          },
        ],
        examId: [
          {
            required: true,
            message: "请选择考试",
            trigger: "change",
          },
        ],
        dataType: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value || !value.length) {
                return callback(new Error(`请选择同步数据类型`));
              }

              callback();
            },
            trigger: "change",
          },
        ],
        startTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error(`请选择同步开始时间`));
              }

              if (this.modalForm.endTime && value >= this.modalForm.endTime) {
                return callback(new Error(`开始时间必须早于结束时间`));
              }

              callback();
            },
            trigger: "change",
          },
        ],
        endTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error(`请选择同步结束时间`));
              }

              if (
                this.modalForm.startTime &&
                value <= this.modalForm.startTime
              ) {
                return callback(new Error(`结束时间必须晚于开始时间`));
              }

              callback();
            },
            trigger: "change",
          },
        ],
        cron: [
          {
            required: true,
            message: "请输入定时同步时间",
            trigger: "change",
          },
        ],
        phoneNumber: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error(`请输入同步异常预警`));
              }

              const vals = value.split(",");
              const reg = /^1\d{10}$/;

              if (vals.some((val) => !reg.test(val))) {
                return callback(new Error(`内容中存在不合适的手机号码`));
              }

              callback();
            },
            trigger: "change",
          },
        ],
      },
      semesterList: [],
      examList: [],
    };
  },
  mounted() {
    this.getSemesters();
  },
  methods: {
    initData(val) {
      if (val.examId) {
        this.modalForm = this.$objAssign(initModalForm, val);
        this.modalForm.dataType = val.dataType ? val.dataType.split(",") : [];
      } else {
        this.modalForm = { ...initModalForm };
        this.modalForm.dataType = [];
      }

      this.getExams();
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async getSemesters() {
      const res = await conditionListSemester(
        {},
        { headers: { schoolId: this.schoolId } }
      );
      this.semesterList = res || [];
    },
    async getExams() {
      if (!this.modalForm.semesterId) return;
      const res = await conditionListExam(
        { semesterId: this.modalForm.semesterId },
        { headers: { schoolId: this.schoolId } }
      );
      this.examList = res || [];
    },
    semesterChange() {
      this.examList = [];
      this.modalForm.examId = "";
      this.getExams();
    },
    timeChange(field) {
      const key = field === "startTime" ? "endTime" : "startTime";
      this.$refs.modalFormComp.validateField(key);
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = {
        ...this.modalForm,
        schoolId: this.schoolId,
        dataType: this.modalForm.dataType.join(),
      };
      const res = await schoolSetDatabaseSyncUpdate(datas).catch(() => {});
      this.isSubmit = false;

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