<template>
  <div class="page-wrapper systerm-add">
    <div class="page-container">
      <a-collapse
        v-model="activeName"
        :bordered="false"
        expand-icon-position="right"
        class="header"
      >
        <a-collapse-panel key="a" :header="$t('BASE_INFO')">
          <a-form-model ref="addForm" :rules="rules" :model="addForm">
            <a-row :span="24">
              <a-col :span="8">
                <a-form-model-item
                  prop="jobCode"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('TASK_CODE')"
                >
                  <a-input v-model="addForm.jobCode" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="jobName"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('TASK_NAME')"
                >
                  <a-input v-model="addForm.jobName" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="datasourceId"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('DATA_SOURCE')"
                >
                  <a-select
                    v-model="addForm.datasourceId"
                    show-search
                    :filter-option="false"
                    :default-active-first-option="false"
                    :placeholder="$t('PLACEENTER')"
                    @change="dataSourceChange"
                    @search="handSearchDataSource"
                  >
                    <a-select-option
                      v-for="item in dataSourceList"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.dataSourceName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <MomTable
                  row-key="key"
                  :columns="columns"
                  :data-source="addForm.jobItems"
                  :pagination="false"
                  :auto-adaptive-width="false"
                  :action-buttons="actionButtons"
                >
                  <div slot="tableName" slot-scope="text, row, index">
                    <a-select
                      v-model="row.tableName"
                      show-search
                      allow-clear
                      :placeholder="$t('PLACEENTER')"
                      @change="() => handChange(row.tableName, row, index)"
                    >
                      <a-select-option
                        v-for="item in tablesNameList"
                        :key="item"
                        :value="item"
                      >
                        {{ item }}
                      </a-select-option>
                    </a-select>
                  </div>
                  <div slot="orderField" slot-scope="text, row">
                    <a-select
                      v-model="row.orderField"
                      show-search
                      allow-clear
                      :placeholder="$t('PLACEENTER')"
                    >
                      <a-select-option
                        v-for="item in row.sortFieldList"
                        :key="item"
                        :value="item"
                      >
                        {{ item }}
                      </a-select-option>
                    </a-select>
                  </div>
                </MomTable>
                <p class="btn_add" @click="handleAdd">
                  <a-icon type="plus" /> {{ $t("ADD") }}
                </p>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="archivePolicy"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('ARCHIVE_POLICY')"
                >
                  <a-select
                    v-model="addForm.archivePolicy"
                    allow-clear
                    :placeholder="$t('PLACEENTER')"
                    @change="handArchiveChange"
                  >
                    <a-select-option
                      v-for="item in archivePolicyList"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col v-if="addForm.archivePolicy === 'NUM'" :span="8">
                <a-form-model-item
                  prop="dataMaxNum"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('MAXIMUM_NUMBER_OF_DATA')"
                >
                  <a-input
                    v-model="addForm.dataMaxNum"
                    onkeyup="value=value.replace(/\D/g,'')"
                    allow-clear
                    @blur="handBlur('dataMaxNum')"
                  />
                </a-form-model-item>
              </a-col>
              <a-col v-else :span="8">
                <a-form-model-item
                  prop="dataMaxDays"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('DATA_RETENTION_DAYS')"
                >
                  <a-input
                    v-model="addForm.dataMaxDays"
                    onkeyup="value=value.replace(/\D/g,'')"
                    allow-clear
                    @blur="handBlur('dataMaxDays')"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="batchNum"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('BTACH_PROCESSING_NUMBER')"
                >
                  <a-input
                    v-model="addForm.batchNum"
                    onkeyup="value=value.replace(/\D/g,'')"
                    allow-clear
                    @blur="handBlur('batchNum')"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="archiveMode"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('FILING_METHOD')"
                >
                  <a-select
                    v-model="addForm.archiveMode"
                    allow-clear
                    :placeholder="$t('PLACEENTER')"
                    @change="handChangeArchive"
                  >
                    <a-select-option
                      v-for="item in archiveModeList"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col v-if="addForm.archiveMode === 'DB'" :span="8">
                <a-form-model-item
                  prop="targetDatasourceId"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('DESTINATION_DATA_SOURCE')"
                >
                  <a-select
                    v-model="addForm.targetDatasourceId"
                    show-search
                    :placeholder="$t('PLACEENTER')"
                    :filter-option="false"
                    :default-active-first-option="false"
                    @search="handSearchTargetData"
                  >
                    <a-select-option
                      v-for="item in targetDatasourceIdList"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.dataSourceName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col v-else :span="8">
                <a-form-model-item
                  prop="archiveDir"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('ARCHIVE_FILE_DIRECTORY')"
                >
                  <a-input v-model="addForm.archiveDir" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="planTime"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('DAILY_EXECUTION_TIME')"
                >
                  <a-time-picker
                    :value="addForm.planTime"
                    style="width: 100%"
                    format="HH:mm:ss"
                    value-format="HH:mm:ss"
                    :placeholder="$t('PLACESELECT')"
                    @change="(t, time) => handChangeTime(time)"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                v-if="
                  addForm.archivePolicy === 'DAYS' &&
                  addForm.archiveMode === 'DB'
                "
                :span="8"
              >
                <a-form-model-item
                  prop="splitByDay"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                  :label="$t('BY_TAIENT')"
                >
                  <a-radio-group v-model="addForm.splitByDay" name="radioGroup">
                    <a-radio
                      v-for="item in whetherList"
                      :key="item.value"
                      :value="item.value"
                      >{{ item.label }}</a-radio
                    >
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-collapse-panel>
      </a-collapse>
    </div>
    <div class="page-bottom-op">
      <a-button type="primary" @click="confirm">
        <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
      </a-button>
      <a-button @click="cancel">
        <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>
<script>
import { Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { v1 as uuidv1 } from "uuid";

export default {
  components: {
    Icon,
  },
  data() {
    return {
      activeName: "a",
      addForm: {
        jobCode: "", // 任务编码
        jobName: "", // 任务名称
        datasourceId: "", // 数据源
        archivePolicy: "", // 归档策略
        dataMaxDays: "", // 数据保留天数
        batchNum: "", // 批量处理数量
        dataMaxNum: "", // 数据最大条数
        archiveMode: "", // 归档方式
        archiveDir: "", // 归档目录
        targetDatasourceId: "", // 目标数据源ID
        planTime: "", // 计划时间
        splitByDay: "N", // 是否按天分表
        jobItems: [
          {
            key: uuidv1(),
            tableName: "",
            orderField: "",
            sortFieldList: [],
          },
        ],
      },
      archivePolicyList: [], // 归档策略列表
      archiveModeList: [], // 归档方式
      whetherList: [], // 数据字典是否
      dataSourceList: [], // 数据源的列表
      tablesNameList: [], // 表名列表
      sortFieldList: [], // 顺序字段列表
      targetDatasourceIdList: [], // 目标数据源列表
      columns: [
        {
          dataIndex: "tableName",
          title: () => this.$t("TABLE_NAME"), // 表名
          sortable: false,
          sorter: false,
          minWidth: 180,
          scopedSlots: { customRender: "tableName" },
        },
        {
          dataIndex: "orderField",
          title: () => this.$t("SORT_FIELD"), // 排序字段
          sortable: false,
          sorter: false,
          minWidth: 180,
          scopedSlots: { customRender: "orderField" },
        },
      ], // 附属机构 列
      actionButtons: [
        (h, { record, index }) => (
          <a-button
            type="link"
            onClick={() => this.handleDelete(record, index)}>
            <Icon
              type="icon-edit-delete"
              style="color: #d45f5f"
              size={18}
              title={this.$t("DELETE")}
            />
          </a-button>
        ),
      ],
    };
  },
  computed: {
    rules() {
      return {
        jobCode: [
          {
            max: 32,
            required: false,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        jobName: [
          {
            max: 64,
            required: true,
            message: this.$t("PLACEENTER") + 64 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        datasourceId: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        archivePolicy: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        dataMaxDays: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          this.validateFieldLength(1, 9),
        ],
        batchNum: [
          {
            required: false,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          this.validateFieldLength(1, 9),
        ],
        dataMaxNum: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          this.validateFieldLength(1, 9),
        ],
        archiveMode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        archiveDir: [
          {
            max: 255,
            required: true,
            message: this.$t("PLACEENTER") + 255 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        targetDatasourceId: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        planTime: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        splitByDay: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
      };
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      return Promise.all([
        this.getDictByCode(`DIC:DVOPS:ARCHIVE_MODE`), // 归档方式
        this.getDictByCode(`DIC:COMMON:WHETHER_CHAR`), //  是否数据字典
        this.getDictByCode(`DIC:DVOPS:ARCHIVE_POLICY`), // 归档策略
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/list`), // 数据源的下拉
      ]).then(
        ([archiveModeRes, whetherRes, archivePolicyRes, dataSourceRes]) => {
          this.archiveModeList = archiveModeRes?.data?.data;
          this.whetherList = whetherRes?.data?.data;
          this.archivePolicyList = archivePolicyRes?.data?.data;
          this.addForm.archivePolicy = archivePolicyRes?.data?.data[0]?.value;
          this.addForm.archiveMode = archiveModeRes?.data?.data[0]?.value;
          this.dataSourceList = dataSourceRes?.data?.data;
        }
      );
    },
    handSearchDataSource(val) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/list`, {
          params: { dataSourceName: val },
        })
        .then((res) => {
          this.dataSourceList = res?.data?.data;
        });
    },
    handSearchTargetData(val) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource/list`, {
          params: { dataSourceName: val },
        })
        .then((res) => {
          this.targetDatasourceIdList = [];
          res?.data?.data.forEach((item) => {
            if (item.id !== this.addForm.datasourceId) {
              this.targetDatasourceIdList.push(item);
            }
          });
        });
    },
    handChangeTime(time) {
      this.addForm.planTime = time;
    },
    dataSourceChange(val) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/datasource-query/tables/${val}`
        )
        .then((res) => {
          this.clearTbale();
          this.tablesNameList = res?.data?.data;
          this.targetDatasourceIdList = [];
          this.dataSourceList.forEach((item) => {
            if (item.id !== val) {
              this.targetDatasourceIdList.push(item);
            }
          });
        })
        .catch(() => {
          this.clearTbale();
        });
    },
    clearTbale() {
      this.addForm.jobItems = [
        {
          key: uuidv1(),
          tableName: "",
          orderField: "",
          sortFieldList: [],
        },
      ];
    },
    confirm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          // eslint-disable-next-line no-plusplus
          for (let i = 0; i < this.addForm.jobItems.length; i++) {
            const item = this.addForm.jobItems[i];
            if (!item.tableName) {
              this.$message.error(this.$t("REQUIRE_TABLE_NAME"));
              return;
            }
            if (!item.orderField) {
              this.$message.error(this.$t("REQUIRE_SORT_FIELD"));
              return;
            }
          }
          this.$axios
            .post(
              `${ApiConstant.PREFIX_CORE}/api/sys/devops/archive-job`,
              this.addForm
            )
            .then((res) => {
              this.$message.success(this.$t("ADD_SUCCESS"));
              this.$store.dispatch("tagsView/jumpBeforeView", {
                to: { path: "/upms/system/setting/archivingTasks" },
                vm: this,
              });
            });
        }
      });
    },
    cancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/upms/system/setting/archivingTasks" },
        vm: this,
      });
    },
    handleDelete(row, index) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.addForm.jobItems.splice(index, 1);
        },
      });
    },
    handleAdd() {
      this.addForm.jobItems.push({
        key: uuidv1(),
        tableName: "",
        orderField: "",
        sortFieldList: [],
      });
    },
    handBlur(name) {
      this.addForm[name] = this.addForm[name].replace(/\D/g, "");
    },
    handChange(val, row, index) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/datasource-query/columns`, {
          params: {
            dataSourceId: this.addForm.datasourceId,
            tableName: val,
          },
        })
        .then((res) => {
          this.$set(
            this.addForm.jobItems[index],
            "sortFieldList",
            res?.data?.data || []
          );
          this.$set(this.addForm.jobItems[index], "orderField", "");
        });
    },
    // 归档方式
    handChangeArchive(val) {
      this.addForm.archiveDir = ""; // 归档目录
      this.addForm.targetDatasourceId = ""; // 目标数据源ID
      this.addForm.splitByDay = "N"; // 是否按天分表
      this.$refs.addForm.clearValidate();
    },
    // 归档策略
    handArchiveChange() {
      this.addForm.dataMaxDays = ""; // 数据保留天数
      this.addForm.dataMaxNum = ""; // 数据最大条数
      this.addForm.splitByDay = "N"; // 是否按天分表
      this.$refs.addForm.clearValidate();
    },
  },
};
</script>
<style lang="less" scoped>
.btn_add {
  color: #0fd19c;
  text-align: center;
  border: 1px dashed #d9d9d9;
  padding: 10px 0;
  cursor: pointer;
  margin: 10px 0;
}
</style>
