<template>
  <div class="app-container">
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>数据备份设置</span>
        </div>
      </template>
      <el-form ref="backupFormRef" :model="backupForm" :rules="rules" label-width="120px" class="" :size="formSize" status-icon>
        <el-form-item label="备份路径" prop="backUpsUrl">
          <template #label>
            <span>
              <el-tooltip content="备份路径是指服务器上的文件路径" placement="top">
                <el-icon>
                  <question-filled />
                </el-icon>
              </el-tooltip>备份路径
            </span>
          </template>
          <el-input v-model="backupForm.backUpsUrl" clearable />
        </el-form-item>
        <el-form-item label="备份周期" prop="cronType">
          <template #label>
            <span>
              <el-tooltip content="每次执行备份数据的时间周期" placement="top">
                <el-icon>
                  <question-filled />
                </el-icon>
              </el-tooltip>备份周期
            </span>
          </template>
          <el-radio-group v-model="backupForm.cronType">
            <el-radio-button label="年">
              <span class="padding-lr-lg">年</span>
            </el-radio-button>
            <el-radio-button label="月">
              <span class="padding-lr-lg">月</span>
            </el-radio-button>
            <el-radio-button label="日">
              <span class="padding-lr-lg">日</span>
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="周期长度" prop="cronNum">
          <el-input v-model.number="backupForm.cronNum" :min="1" type="number" @change="handleCountChange">
            <template #append>{{backupForm.cronType}}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="清理数据" prop="tablesNeedClear">
          <template #label>
            <span>清理数据</span>
            <span v-if="backupForm.tablesNeedClear.length>0">({{backupForm.tablesNeedClear.length}})</span>
          </template>
          <el-card shadow="never" style="width: 100%">
            <el-scrollbar height="400px">
              <el-checkbox-group v-model="backupForm.tablesNeedClear">
                <div class="grid col-5">
                  <div v-for="(item) in tableList" :key="item.tableName">
                    <el-checkbox :label="item">
                      {{ item.annotation || item.tableName }}
                    </el-checkbox>
                  </div>
                </div>
              </el-checkbox-group>
            </el-scrollbar>
          </el-card>
        </el-form-item>
        <el-form-item>
          <template v-if="isModified">
            <el-button type="primary" @click="handleSubmit(backupFormRef)">保存</el-button>
            <el-button @click="handleReset(backupFormRef)">重置</el-button>
          </template>
          <el-button type="warning" @click="handleDoBackUp">执行一次</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup name="BackUp">
import { FormInstance, FormRules } from "element-plus";
import { nextTick, reactive, ref, watch } from "vue";
import {
  getBackUp,
  updateBackUp,
  getBackUpTables,
  doBackUp,
} from "@/api/systemSettings/backUp.js";
import useCurrentInstance from "@/hooks/useCurrentInstance";
const { proxy } = useCurrentInstance();

const formSize = ref("default");
const backupFormRef = ref<FormInstance>();
const backupForm = ref({
  backUpsUrl: "C:/",
  cronType: "年",
  cronNum: 1,
  tablesNeedClear: [],
  // cron: "",
});
const tableList = ref([]);
const isModified = ref(false);

const rules = reactive<FormRules>({
  backUpsUrl: [
    {
      required: true,
      message: "备份路径不能为空",
      trigger: "blur",
    },
    {
      min: 1,
      max: 100,
      message: "备份路径长度在1-100之内",
      trigger: "blur",
    },
  ],
  cronType: [
    {
      required: true,
      message: "周期类型不能为空",
      trigger: "blur",
    },
  ],
  cronNum: [
    {
      required: true,
      message: "周期长度不能为空",
      trigger: "blur",
    },
    // { min: 1, max: 100, message: '周期长度在1-100之内', trigger: 'blur' },
  ],
});

watch(
  () => backupForm,
  () => {
    isModified.value = true;
  },
  { deep: true }
);

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log("submit!");
      // console.log(backupForm);
      // createCron();
      updateBackUp(backupForm.value).then((response) => {
        proxy.$modal.msgSuccess(response.msg);
        isModified.value = false;
      });
    } else {
      proxy.$modal.msgError("请补全且正确填写内容");
      // console.log("error submit!", fields);
    }
  });
};

const handleReset = (formEl: FormInstance | undefined) => {
  proxy.$modal
    .confirm("是否重置设置？")
    .then(async () => {
      if (!formEl) return;
      formEl.resetFields();
      await initialData();
      proxy.$modal.msgSuccess("重置成功");
      isModified.value = false;
    })
    .catch(() => {});
};

const handleCountChange = (value: Number) => {
  // console.log(value);
  if (value < 1) {
    backupForm.value.cronNum = 1;
  }
};

const handleDoBackUp = (): void => {
  doBackUp(backupForm.value).then((response) => {
    proxy.$modal.msgSuccess(response.msg);
  });
};

const initialData = async () => {
  await getBackUp({}).then((response) => {
    // console.log(response);
    backupForm.value = response.data;
  });
  await getBackUpTables({}).then((response) => {
    // console.log(response);
    tableList.value = response.data;
  });
  nextTick(() => {
    isModified.value = false;
  });
};

initialData();
</script>
