<template>
  <div class="page-wrapper systerm-edit">
    <i-dialog-form
      ref="drawerForm"
      :title="drawTitle"
      :visible="drawerVisible"
      @save="saveNewRule"
      @close="close"
    >
      <i-form
        slot="iDialogForm"
        ref="newRuleForm"
        :form-item="newRuleFormItem"
        :search-form="newRuleForm"
        :span="1"
      >
        <!-- 段类型 -->
        <i-table-select
          slot="fieldType"
          v-model="newRuleForm.fieldType"
          dict-code="DIC:CORE:CODERULE_FIELD_TYPE"
          @change="fieldTypeChange"
        />
      </i-form>
    </i-dialog-form>
    <div class="page-container">
      <a-collapse
        v-model="activeNameA"
        :bordered="false"
        expand-icon-position="right"
        class="collapse-header-divide"
      >
        <a-collapse-panel key="a" :header="$t('BASE_INFO')">
          <a-form-model
            ref="ruleForm"
            layout="horizontal"
            :model="ruleForm"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-row type="flex" justify="space-between">
              <a-col :span="8">
                <a-form-model-item
                  prop="ruleCode"
                  :rules="{
                    required: true,
                    message: $t('PLACEENTER'),
                    trigger: 'blur',
                  }"
                  :label="$t('RULE_CODE')"
                >
                  <a-input v-model="ruleForm.ruleCode" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="ruleName"
                  :rules="{
                    required: true,
                    message: $t('PLACEENTER'),
                    trigger: 'blur',
                  }"
                  :label="$t('RULE_NAME')"
                >
                  <a-input v-model="ruleForm.ruleName" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item :label="$t('REMARK')" prop="remark">
                  <a-input v-model="ruleForm.remark" type="textarea" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-collapse-panel>
      </a-collapse>
      <a-collapse
        v-model="activeNameB"
        :bordered="false"
        expand-icon-position="right"
        class="collapse-header-divide functionPermissionsContainer"
      >
        <a-collapse-panel key="b" :header="$t('RULE_SETTING')">
          <!-- <a-row>
            <a-button
              type="success"
              icon="el-icon-plus icon-defult"
              @click.stop="handleAdd"
            >
              {{ $t('ADD') }}
            </a-button>
          </a-row>
          <i-table
            :table-data="tableData"
            :if-selection="false"
            :max-height="450"
            :if-index="false"
            :table-columns="tableColumns"
            class="mt-12"
            @edit="handleEdit"
            @delete="handleDelete"
          /> -->
          <MomTable
            :columns="tableColumns"
            :data-source="tableData"
            :pagination="false"
            :mega-extend="{ rowIndex: true, rowAction: { width: 150 } }"
            row-key="seq"
            :action-buttons="tableAction"
            @edit="handleEdit"
            @delete="handleDelete"
          >
            <a-row slot="toolbar">
              <a-button type="success" @click.stop="handleAdd">
                <a-icon type="plus" /> {{ $t("ADD") }}
              </a-button>
            </a-row>
            <template slot="fieldType" slot-scope="text">
              <span>{{ getAttrValue(typeList, text) }}</span>
            </template>
            <template slot="resetFrequency" slot-scope="text">
              <span>{{ getAttrValue(frequencyList, text) }}</span>
            </template>
          </MomTable>
          <div class="viewCodeRules">
            {{ $t("CODE_PREVIEW") }}：{{ uuidStr }}
          </div>
        </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";

export default {
  components: {
    Icon,
  },
  data() {
    return {
      activeNameA: "a",
      activeNameB: "b",
      drawerVisible: false,
      tableData: [],
      drawTitle: "",
      seq: 0,
      newRuleFormItem: {
        // seq: {
        //   i18n: 'INDEX', // 序号
        //   itemType: 'input-numer',
        //   min: 1,
        //   isRequired: true,
        // },
        fieldType: {
          i18n: "FILED_TYPE", // 段类型
          isRequired: true,
          dictCode: "DIC:CORE:CODERULE_FIELD_TYPE",
          options: [],
        },
        fieldValue: {
          i18n: "FIELD_VALUE", // 段值
          isRequired: true,
          itemType: "select",
          options: [],
          hidden: true,
        },
        dateMask: {
          i18n: "DATE_MASK", // 日期掩码
          isRequired: true,
          itemType: "select",
          options: [],
          hidden: true,
        },
        resetFrequency: {
          i18n: "RESET_FREQUENCY", // 重置频率
          itemType: "select",
          isRequired: true,
          options: [],
          hidden: true,
        },
        seqLength: {
          i18n: "SEQ_LENGTH", // 位数
          isRequired: true,
          itemType: "input-numer",
          options: [],
          hidden: true,
        },
        startValue: {
          i18n: "STARTTING_VALUE", // 开始值
          itemType: "input-numer",
          isRequired: true,
          hidden: true,
        },
        currentValue: {
          i18n: "CURRENT_VALUE", // 当前值
          itemType: "input-numer",
          isRequired: true,
          hidden: true,
        },
      },
      add: false,
      newRuleForm: {
        // seq: 0, // 	序号
        fieldType: "", // 	段类型:UUID、日期DATE、变量VARIABLE、常量CONSTANT、序列SEQ、分隔符SEPARATOR
        dateMask: "", // 		日期格式
        fieldValue: "", // 	段值
        resetFrequency: "", // 重置频率：每天DAY 每月MONTH 每季QUARTER 每年YEAR 从不NEVER
        seqLength: "", // 		位数
        startValue: "", // 	开始值
        currentValue: "", // 	当前值
      },
      ruleForm: {
        remark: "", // 备注
        ruleCode: "", // 规则编码
        ruleName: "", // 规则名称
      },
      typeList: [],
      frequencyList: [],
      uuidStr: "",
      tableAction: [
        (h, value, a, b) => (
          <a-button
            class="table-action-button"
            type="text"
            onClick={() => this.handleMoveUp(value)}>
            <i
              class="el-icon-top"
              style="font-size:18px"
              title={this.$t("BUTTON:COMMON:MOVE_UP")}
            />
          </a-button>
        ),
        (h, value, a, b) => (
          <a-button
            class="table-action-button"
            type="text"
            onClick={() => this.handleMoveDown(value)}>
            <i
              class="el-icon-bottom"
              style="font-size:18px"
              title={this.$t("BUTTON:COMMON:MOVE_DOWN")}
            />
          </a-button>
        ),
        "edit",
        "delete",
      ],
    };
  },
  computed: {
    tableColumns() {
      return [
        // {
        //   dataIndex: 'seq',
        //   key: 'seq',
        //   title: () => this.$t('COLUMN:CORE:SYSTEM:CODERULE:SORT'), // 段类型
        //   sorter: false
        // },
        {
          dataIndex: "fieldType",
          key: "fieldType",
          title: () => this.$t("FILED_TYPE"), // 段类型
          options: [],
          scopedSlots: { customRender: "fieldType" },
          sorter: false,
        },
        {
          dataIndex: "fieldValue",
          title: () => this.$t("FIELD_VALUE"), // 段值
          sorter: false,
          options: [],
        },
        {
          dataIndex: "dateMask",
          sorter: false,
          title: () => this.$t("DATE_MASK"), // 日期掩码
        },
        {
          dataIndex: "resetFrequency",
          key: "resetFrequency",
          title: () => this.$t("RESET_FREQUENCY"), // 重置频率
          scopedSlots: { customRender: "resetFrequency" },
          sorter: false,
          options: [],
        },
        {
          dataIndex: "seqLength",
          sorter: false,
          title: () => this.$t("SEQ_LENGTH"), // 位数
        },
        {
          dataIndex: "startValue",
          sorter: false,
          title: () => this.$t("STARTTING_VALUE"), // 开始值
        },
        {
          dataIndex: "currentValue",
          sorter: false,
          title: () => this.$t("CURRENT_VALUE"), // 当前值
        },
        {
          dataIndex: "resetDate",
          sorter: false,
          width: 200,
          title: () => this.$t("RESET_DATE"), // 上次重置日期
        },
      ];
    },
  },
  mounted() {
    this.initPageData();
  },
  methods: {
    initPageData() {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/code-rule/get-by-id/${this.$route.query.id}`
        )
        .then((res) => {
          this.ruleForm = res.data.data;
          this.tableData = res.data.data.codeRuleDetails || [];
          this.tableDataStr();
        });

      this.getDictByCode(`DIC:CORE:CODERULE_FIELD_VALUE_TYPE`).then((res) => {
        this.tableColumns[1].options = res.data.data;
        this.newRuleFormItem.fieldValue.options = res.data.data;
      });

      this.getDictByCode(`DIC:CORE:CODERULE_FIELD_TYPE`).then((res) => {
        this.typeList = res.data.data;
      });

      this.getDictByCode(`DIC:CORE:CODERULE_DATE_FORMATE_TYPE`).then((res) => {
        this.newRuleFormItem.dateMask.options = res.data.data;
      });

      this.getDictByCode(`DIC:CORE:CODERULE_RESET_FREQUENCY`).then((res) => {
        this.newRuleFormItem.resetFrequency.options = res.data.data;
        this.frequencyList = res.data.data;
      });

      this.getDictByCode(`DIC:CORE:CODERULE_BIT_TYPE`).then((res) => {
        this.newRuleFormItem.seqLength.options = res.data.data;
      });
    },
    cancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/upms/system/setting/codeRules" },
        vm: this,
      });
    },
    close(visible) {
      this.drawerVisible = visible;
    },
    // 改变段类型
    fieldTypeChange(val) {
      if (!val) {
        return;
      }
      if (this.drawerVisible) {
        this.$refs.newRuleForm.$refs.iForm.clearValidate();
        this.newRuleForm = this.$options.data().newRuleForm;
      }

      if (val === "VARIABLE") {
        this.newRuleFormItem.fieldValue.hidden = false;
        this.newRuleFormItem.fieldValue.itemType = "select";
        this.newRuleFormItem.fieldValue.rule = {
          required: true,
          message: this.$t("PLACESELECT"),
          trigger: "change",
        };
        this.newRuleFormItem.dateMask.hidden = true;
        this.newRuleFormItem.resetFrequency.hidden = true;
        this.newRuleFormItem.seqLength.hidden = true;
        this.newRuleFormItem.startValue.hidden = true;
        this.newRuleFormItem.currentValue.hidden = true;
      } else if (val === "CONSTANT") {
        this.newRuleFormItem.fieldValue.hidden = false;
        this.newRuleFormItem.fieldValue.itemType = "input";
        this.newRuleFormItem.fieldValue.rule = {
          required: true,
          message: this.$t("PLACEENTER"),
          trigger: "blur",
        };
        this.newRuleFormItem.dateMask.hidden = true;
        this.newRuleFormItem.resetFrequency.hidden = true;
        this.newRuleFormItem.seqLength.hidden = true;
        this.newRuleFormItem.startValue.hidden = true;
        this.newRuleFormItem.currentValue.hidden = true;
      } else if (val === "UUID") {
        this.newRuleFormItem.seqLength.itemType = "select";
        this.newRuleFormItem.seqLength.rule = {
          required: true,
          message: this.$t("PLACESELECT"),
          trigger: "change",
        };
        this.newRuleFormItem.seqLength.hidden = false;
        this.newRuleFormItem.dateMask.hidden = true;
        this.newRuleFormItem.resetFrequency.hidden = true;
        this.newRuleFormItem.startValue.hidden = true;
        this.newRuleFormItem.fieldValue.hidden = true;
        this.newRuleFormItem.currentValue.hidden = true;
      } else if (val === "DATE") {
        this.newRuleFormItem.dateMask.hidden = false;
        this.newRuleFormItem.seqLength.hidden = true;
        this.newRuleFormItem.resetFrequency.hidden = true;
        this.newRuleFormItem.startValue.hidden = true;
        this.newRuleFormItem.fieldValue.hidden = true;
        this.newRuleFormItem.currentValue.hidden = true;
      } else if (val === "SEQ") {
        this.newRuleFormItem.seqLength.itemType = "input-numer";
        this.newRuleFormItem.startValue.itemType = "input-numer";
        this.newRuleFormItem.currentValue.itemType = "input-numer";
        this.newRuleFormItem.seqLength.rule = {
          required: true,
          message: this.$t("PLACEENTER"),
          trigger: "blur",
        };
        this.newRuleFormItem.seqLength.hidden = false;
        this.newRuleFormItem.resetFrequency.hidden = false;
        this.newRuleFormItem.dateMask.hidden = true;
        this.newRuleFormItem.startValue.hidden = false;
        this.newRuleFormItem.currentValue.hidden = false;
        this.newRuleFormItem.fieldValue.hidden = true;
      }
    },
    handleAdd() {
      this.clearForm();
      this.drawTitle = this.$t("ADD");
      this.newRuleFormItem.seqLength.hidden = true;
      this.newRuleFormItem.resetFrequency.hidden = true;
      this.newRuleFormItem.dateMask.hidden = true;
      this.newRuleFormItem.startValue.hidden = true;
      this.newRuleFormItem.currentValue.hidden = true;
      this.newRuleFormItem.fieldValue.hidden = true;
      this.drawerVisible = true;
      this.add = true;
      this.$nextTick(() => {
        this.$refs.newRuleForm.$refs.iForm.resetFields();
        if (this.tableData.length > 0) {
          // eslint-disable-next-line
          const maxValue = Math.max.apply(
            Math,
            this.tableData.map((item) => {
              return item.seq;
            })
          );
          this.seq = maxValue + 1;
        }
      });
    },
    clearForm() {
      this.newRuleForm = {
        seq: 0, // 	序号
        fieldType: "", // 	段类型:UUID、日期DATE、变量VARIABLE、常量CONSTANT、序列SEQ、分隔符SEPARATOR
        dateMask: "", // 		日期格式
        fieldValue: "", // 	段值
        resetFrequency: "", // 重置频率：每天DAY 每月MONTH 每季QUARTER 每年YEAR 从不NEVER
        seqLength: "", // 		位数
        startValue: "", // 	开始值
        currentValue: "", // 	当前值
      };
    },
    // 上移
    handleMoveUp(row) {
      const { index } = row;
      if (index > 0) {
        if (row.true_label === this.tableData[index - 1].true_label) {
          const upDate = this.tableData[index - 1];
          this.tableData.splice(index - 1, 1);
          this.tableData.splice(index, 0, upDate);
        } else {
          this.$message.error(this.$t("UP"));
        }
      } else {
        this.$message.error(this.$t("NOUP"));
      }
    },
    // 下移
    handleMoveDown(row) {
      const { index } = row;
      if (index + 1 === this.tableData.length) {
        this.$message.error(this.$t("DOWN"));
      } else {
        const downDate = this.tableData[index + 1];
        this.tableData.splice(index + 1, 1);
        this.tableData.splice(index, 0, downDate);
      }
    },
    handleEdit(row) {
      this.drawTitle = this.$t("EDIT");
      this.fieldTypeChange(row.fieldType);
      this.newRuleForm = { ...row };
      const { seq } = row;
      this.seq = seq;
      this.drawerVisible = true;
      this.add = false;
    },
    handleDelete(row) {
      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: () => {
          const index = this.tableData.findIndex(
            (item) => item.seq === row.seq
          );
          this.tableData.splice(index, 1);
          this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
          this.tableDataStr();
        },
      });
    },
    saveNewRule() {
      if (
        this.newRuleForm.startValue &&
        this.newRuleForm.currentValue &&
        parseFloat(this.newRuleForm.startValue) >
          parseFloat(this.newRuleForm.currentValue)
      ) {
        this.$message.error(this.$t("VALUE_WARNING")); // 当前值不能小于开始值
        return;
      }
      if (
        this.newRuleForm.startValue &&
        this.newRuleForm.seqLength &&
        JSON.stringify(parseFloat(this.newRuleForm.startValue)).length >
          parseFloat(this.newRuleForm.seqLength)
      ) {
        this.$message.error(this.$t("START_DIGITS")); // 开始值不能大于位数
        return;
      }
      if (this.tableData.length > 0) {
        if (this.add) {
          const result = this.tableData.find((item) => item.seq === this.seq);
          if (result) {
            this.$message.error(this.$t("CAN_NOT_SAME"));
            return;
          }
        }
      }
      this.$refs.newRuleForm.$refs.iForm.validate((valid) => {
        if (valid) {
          this.drawerVisible = false;
          const tempObj = {
            seq: this.seq,
          };
          if (this.add) {
            this.tableData.push({ ...this.newRuleForm, ...tempObj });
          } else {
            const index = this.tableData.findIndex(
              (item) => item.seq === this.seq
            );
            this.tableData.splice(index, 1, {
              ...this.newRuleForm,
              ...tempObj,
            });
          }
          this.newRuleFormItem.seqLength.hidden = true;
          this.newRuleFormItem.dateMask.hidden = true;
          this.newRuleFormItem.resetFrequency.hidden = true;
          this.newRuleFormItem.startValue.hidden = true;
          this.newRuleFormItem.fieldValue.hidden = true;
          this.activeNameB = "b";
        } else {
          this.$message.error(this.$t("REQUIRED_INFO"));
        }
      });
      this.tableDataStr();
    },
    // eslint-disable-next-line consistent-return
    formatDate(type) {
      const date = new Date();
      const y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? `0${MM}` : MM;
      let d = date.getDate();
      d = d < 10 ? `0${d}` : d;
      let h = date.getHours();
      h = h < 10 ? `0${h}` : h;
      let m = date.getMinutes();
      m = m < 10 ? `0${m}` : m;
      let s = date.getSeconds();
      s = s < 10 ? `0${s}` : s;
      if (type === "yyyyMMddHHmmss") {
        return `${y}${MM}${d}${h}${m}${s}`;
      }
      if (type === "yyyyMMdd") {
        return `${y}${MM}${d}`;
      }
      if (type === "yyyyMM") {
        return `${y}${MM}`;
      }
      if (type === "yyyy") {
        return `${y}`;
      }
    },
    tableDataStr() {
      this.uuidStr = "";
      this.tableData.forEach((item, index) => {
        if (item.fieldType === "UUID") {
          this.uuidCode(item.seqLength, index);
        } else if (item.fieldType === "VARIABLE") {
          this.uuidStr += item.fieldValue;
        } else if (item.fieldType === "DATE") {
          this.uuidStr += this.formatDate(item.dateMask);
        } else if (item.fieldType === "CONSTANT") {
          this.uuidStr += item.fieldValue;
        } else if (item.fieldType === "SEQ") {
          const num =
            typeof item.startValue !== "string"
              ? JSON.stringify(item.startValue).length
              : item.startValue.length;
          if (item.seqLength === num) {
            this.uuidStr += item.startValue;
            // eslint-disable-next-line valid-typeof
          } else {
            this.seqSum(item.seqLength - num, item.startValue);
          }
        }
      });
    },
    // UUID拼接编码方法
    uuidCode(val) {
      // eslint-disable-next-line no-plusplus
      for (let index = 0; index < Number(val); index++) {
        this.uuidStr += "0";
      }
    },
    seqSum(val, str) {
      // eslint-disable-next-line no-plusplus
      for (let index = 0; index < Number(val); index++) {
        this.uuidStr += "0";
      }
      this.uuidStr += str;
    },
    confirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const params = {
            codeRuleDetails: this.tableData,
            ...this.ruleForm,
          };
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/sys/code-rule`, params)
            .then((res) => {
              this.$message.success(this.$t("EDIT_SUCCESS"));
              this.$store.dispatch("tagsView/jumpBeforeView", {
                to: { path: "/upms/system/setting/codeRules" },
                vm: this,
              });
            });
        } else {
          this.$message.error(this.$t("REQUIRED_INFO"));
        }
      });
    },
  },
};
</script>

<style lang="less">
@import (optional, once) "@/theme";

.systerm-edit {
  .ant-input,
  .ant-select {
    max-width: 400px;
  }
  .action-column {
    display: flex;
    align-items: center;
  }
  .table-action-button {
    border: none;
    background: none;
    color: @primary-color;
  }
}
.viewCodeRules {
  border: 1px solid #ccc;
  padding: 10px;
  background: #ecf8fc;
  color: #1faed3;
  margin: 5px 0;
}
</style>
