<template>
  <div class="school-set-database-sync">
    <div class="part-box part-box-pad">
      <el-form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        label-width="100px"
        style="max-width: 1000px"
      >
        <el-form-item prop="type" label="数据库类型：">
          <el-radio-group v-model="modalForm.type">
            <el-radio
              v-for="(val, key) in DATABASE_TYPE"
              :key="key"
              :label="key"
              >{{ val }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item prop="host" label="host：">
              <el-input
                v-model.trim="modalForm.host"
                placeholder="请输入URL"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="port" label="port：">
              <el-input
                v-model.trim="modalForm.port"
                placeholder="请输入URL"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="dataname" label="dataname：">
              <el-input
                v-model.trim="modalForm.dataname"
                placeholder="请输入URL"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item prop="username" label="用户名：">
              <el-input
                v-model.trim="modalForm.username"
                placeholder="请输入用户名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="password" label="密码：">
              <el-input
                v-model.trim="modalForm.password"
                placeholder="请输入密码"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="toSave">保存</el-button>
          <el-button type="primary" @click="toTest">测试链接</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="part-box part-box-pad">
      <div class="box-justify mb-2">
        <div>
          <el-button type="primary" @click="getList">更新列表</el-button>
        </div>
        <div>
          <el-button type="primary" @click="toAdd">新增</el-button>
        </div>
      </div>

      <el-table ref="TableList" :data="dataList">
        <el-table-column
          prop="semesterName"
          label="学年学期"
          min-width="210"
        ></el-table-column>
        <el-table-column
          prop="examName"
          label="考试名称"
          min-width="160"
        ></el-table-column>
        <el-table-column
          prop="dataType"
          label="同步数据类型"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="detail"
          label="同步结果"
          min-width="100"
        ></el-table-column>
        <el-table-column prop="startTime" label="同步开始时间" width="170">
          <span slot-scope="scope">{{
            scope.row.startTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="endTime" label="同步结束时间" width="170">
          <span slot-scope="scope">{{
            scope.row.endTime | timestampFilter
          }}</span>
        </el-table-column>
        <el-table-column prop="cron" label="定时同步时间" width="140">
        </el-table-column>
        <el-table-column prop="status" label="同步状态" width="100">
          <template slot-scope="scope">
            {{ scope.row.status ? "同步中" : "已同步" }}
          </template>
        </el-table-column>
        <el-table-column prop="enable" label="启用/禁用" width="100">
          <template slot-scope="scope">
            {{ scope.row.enable | enableFilter }}
          </template>
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="260"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              class="btn-primary"
              type="text"
              @click="toEdit(scope.row)"
              >设置</el-button
            >
            <el-button
              class="btn-primary"
              type="text"
              @click="toViewLog(scope.row)"
              >查看日志</el-button
            >
            <el-button
              class="btn-primary"
              type="text"
              @click="toSync(scope.row)"
              >手动同步</el-button
            >
            <el-button
              :class="scope.row.enable ? 'btn-danger' : 'btn-primary'"
              type="text"
              @click="toEnable(scope.row)"
              >{{ scope.row.enable ? "禁用" : "启用" }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="5"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
          @size-change="pageSizeChange"
        >
        </el-pagination>
      </div>
    </div>
    <div class="tips-info">
      <p>同步数据类型：{{ dataTypeTips }}</p>
    </div>

    <!-- ModifyDatabaseSync -->
    <ModifyDatabaseSync
      ref="ModifyDatabaseSync"
      :instance="curRow"
      :school-id="school.id"
      @modified="getList"
    />
    <!-- DatabaseSyncLogDialog -->
    <DatabaseSyncLogDialog ref="DatabaseSyncLogDialog" :row-data="curRow" />
  </div>
</template>

<script>
import {
  schoolSetDatabaseSyncBaseinfo,
  schoolSetDatabaseSyncBaseinfoUpdate,
  schoolSetDatabaseSyncBaseinfoTest,
  schoolSetDatabaseSyncList,
  schoolSetDatabaseSyncHandleSync,
  schoolSetDatabaseSyncEnable,
} from "../../api";
import { DATABASE_TYPE } from "@/constants/enumerate";
import ModifyDatabaseSync from "./ModifyDatabaseSync.vue";
import DatabaseSyncLogDialog from "./DatabaseSyncLogDialog.vue";
import { DATABASE_SYNC_TYPE } from "@/constants/enumerate";

const initModalForm = {
  type: "",
  host: "",
  port: "",
  dataname: "",
  username: "",
  password: "",
};

export default {
  name: "school-set-database-sync",
  components: { ModifyDatabaseSync, DatabaseSyncLogDialog },
  props: {
    school: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      baseinfo: [],
      modalForm: { ...initModalForm },
      rules: {
        type: [
          {
            required: true,
            message: "请选择数据库类型",
            trigger: "change",
          },
        ],
        host: [
          {
            required: true,
            message: "请输入host",
            trigger: "change",
          },
          {
            message: "host不能超过99个字符",
            max: 99,
            trigger: "change",
          },
        ],
        port: [
          {
            required: true,
            message: "请输入port",
            trigger: "change",
          },
          {
            message: "port只能是数字",
            pattern: /^\d*$/,
            trigger: "change",
          },
          {
            message: "port不能超过6个字符",
            max: 6,
            trigger: "change",
          },
        ],
        dataname: [
          {
            required: true,
            message: "请输入dataname",
            trigger: "change",
          },
          {
            message: "dataname不能超过99个字符",
            max: 99,
            trigger: "change",
          },
        ],
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change",
          },
          {
            message: "用户名不能超过50个字符",
            max: 50,
            trigger: "change",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "change",
          },
          {
            message: "密码不能超过50个字符",
            max: 50,
            trigger: "change",
          },
        ],
      },
      isSubmit: false,
      dataList: [],
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      curRow: {},
      DATABASE_TYPE,
      DATABASE_SYNC_TYPE,
      // log
      logList: [],
      logModalIsShow: false,
    };
  },
  computed: {
    dataTypeTips() {
      return Object.entries(this.DATABASE_SYNC_TYPE)
        .map(([key, val]) => `${key}：${val}`)
        .join("，");
    },
  },
  mounted() {
    this.getBaseInfo();
    this.toPage(1);
  },
  methods: {
    async getBaseInfo() {
      const res = await schoolSetDatabaseSyncBaseinfo(this.school.id);
      this.baseinfo = res.result || [];
      // const codeMap = {
      //   "data.datasource.type": "type",
      //   "data.datasource.host": "host",
      //   "data.datasource.port": "port",
      //   "data.datasource.dataname": "dataname",
      //   "data.datasource.username": "username",
      //   "data.datasource.password": "password",
      // };
      this.baseinfo.forEach((item) => {
        const k = item.code.replace("data.datasource.", "");
        this.modalForm[k] = item.value;
      });
    },
    getData() {
      return this.baseinfo.map((item) => {
        const k = item.code.replace("data.datasource.", "");
        item.value = this.modalForm[k];
        return item;
      });
    },
    async toSave() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = { param: this.getData(), schoolId: this.school.id };
      const res = await schoolSetDatabaseSyncBaseinfoUpdate(datas).catch(
        () => {}
      );
      this.isSubmit = false;

      if (!res) return;
      this.$message.success("保存成功！");
    },
    async toTest() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = { param: this.getData(), schoolId: this.school.id };
      let errorMsg = "";
      const res = await schoolSetDatabaseSyncBaseinfoTest(datas).catch(
        (error) => {
          errorMsg = error.message || "测试失败！";
        }
      );
      this.isSubmit = false;
      const result = res ? "测试成功！" : errorMsg;

      this.$alert(result, {
        type: res ? "success" : "error",
        customClass: "alert-message",
        confirmButtonText: "确定",
      });
    },
    async getList() {
      const datas = {
        schoolId: this.school.id,
        pageNumber: this.current,
        pageSize: this.size,
      };
      const data = await schoolSetDatabaseSyncList(datas);
      this.dataList = data.records;
      this.total = data.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    toEdit(row) {
      this.curRow = row;
      this.$refs.ModifyDatabaseSync.open();
    },
    toAdd() {
      this.curRow = {};
      this.$refs.ModifyDatabaseSync.open();
    },
    toViewLog(row) {
      this.curRow = row;
      this.$refs.DatabaseSyncLogDialog.open();
    },
    async toSync(row) {
      const res = await schoolSetDatabaseSyncHandleSync({
        schoolId: row.schoolId,
        examId: row.examId,
      }).catch(() => {});
      if (!res) return;
      this.$message.success("操作成功！");
      this.getList();
    },
    async toEnable(row) {
      const action = row.enable ? "禁用" : "启用";
      const result = await this.$confirm(
        `确定要${action}当前同步记录吗?`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (result !== "confirm") return;

      const enable = !row.enable;
      await schoolSetDatabaseSyncEnable({
        schoolId: row.schoolId,
        examId: row.examId,
        enable,
      });
      row.enable = enable;
      this.$message.success("操作成功！");
    },
  },
};
</script>
