<template>
  <div class="page-wrapper attr systerm-add">
    <i-dialog-form
      ref="drawerForm"
      :title="title"
      :visible="drawerVisible"
      @save="saveNewRule"
      @close="close"
    >
      <a-form-model
        slot="iDialogForm"
        ref="newRuleForm"
        :model="newRuleForm"
        :rules="subRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <!-- 类型 -->
        <a-form-model-item :label="$t('DATA_TYPE')" prop="dataType">
          <i-table-select
            v-model="newRuleForm.dataType"
            :options="selectData.dataTypes"
            @change="dataTypeChange"
          />
        </a-form-model-item>
        <!-- 固定值 -->
        <a-form-model-item
          v-if="newRuleForm.dataType === 'FIXED'"
          :label="$t('FIXED_VALUE')"
          prop="conditions.FIXED_VALUE"
        >
          <a-input
            v-model="newRuleForm.conditions['FIXED_VALUE']"
            allow-clear
          />
        </a-form-model-item>
        <!-- 参数名 -->
        <a-form-model-item
          v-if="newRuleForm.dataType === 'PARAM'"
          :label="$t('PARAMETER_NAME')"
          prop="conditions.PARAM_NAME"
        >
          <a-select
            v-model="newRuleForm.conditions['PARAM_NAME']"
            show-search
            option-filter-prop="children"
            :filter-option="filterOption"
          >
            <a-select-option
              v-for="item in selectData.params"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label + `(${item.value})` }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 特殊处理 -->
        <a-form-model-item
          v-if="newRuleForm.dataType === 'PARAM'"
          :label="$t('TREAT_TYPE')"
        >
          <i-table-select
            v-model="newRuleForm.conditions['PARAM_TREAT_TYPE']"
            :options="selectData.paramTreatTypes"
            @change="paramTreatTypeChange"
          />
        </a-form-model-item>
        <!-- 截取范围 -->
        <a-form-model-item
          v-if="
            newRuleForm.dataType === 'PARAM' &&
            newRuleForm.conditions['PARAM_TREAT_TYPE'] === 'SUBSTRING'
          "
          :label="$t('SUB_RANGE')"
          prop="conditions.PARAM_SUB_RANGE"
        >
          <i-position
            v-model="newRuleForm.conditions['PARAM_SUB_RANGE']"
            class="i-position"
            :min="1"
            :is-strict="true"
          />
        </a-form-model-item>
        <!-- 截取长度 -->
        <a-form-model-item
          v-if="
            newRuleForm.dataType === 'PARAM' &&
            ['PRESUB', 'SUFSUB'].indexOf(
              newRuleForm.conditions['PARAM_TREAT_TYPE']
            ) !== -1
          "
          :label="$t('SUB_LENGTH')"
          prop="conditions.PARAM_SUB_LENGTH"
        >
          <a-input-number
            v-model="newRuleForm.conditions['PARAM_SUB_LENGTH']"
            :min="1"
            allow-clear
          />
        </a-form-model-item>
        <!-- 去除长度 -->
        <a-form-model-item
          v-if="
            newRuleForm.dataType === 'PARAM' &&
            ['REMOVERIGHT', 'REMOVELEFT'].indexOf(
              newRuleForm.conditions['PARAM_TREAT_TYPE']
            ) !== -1
          "
          :label="
            newRuleForm.conditions['PARAM_TREAT_TYPE'] === 'REMOVERIGHT'
              ? $t('REMOVE_LENGTH_LEFT')
              : $t('REMOVE_LENGTH_LEFT')
          "
          :prop="`conditions.${removeLengthParamName}`"
        >
          <a-input-number
            v-model="newRuleForm.conditions[removeLengthParamName]"
            :min="1"
            allow-clear
          />
        </a-form-model-item>
        <!-- 长度 -->
        <a-form-model-item
          v-if="
            newRuleForm.dataType === 'PARAM' &&
            ['PREFIX', 'SUFFIX'].indexOf(
              newRuleForm.conditions['PARAM_TREAT_TYPE']
            ) !== -1
          "
          :label="$t('LENGTH')"
          prop="conditions.PARAM_FIX_LENGTH"
        >
          <a-input-number
            v-model="newRuleForm.conditions['PARAM_FIX_LENGTH']"
            :min="1"
            allow-clear
          />
        </a-form-model-item>
        <!-- 补值 -->
        <a-form-model-item
          v-if="
            newRuleForm.dataType === 'PARAM' &&
            ['PREFIX', 'SUFFIX'].indexOf(
              newRuleForm.conditions['PARAM_TREAT_TYPE']
            ) !== -1
          "
          :label="$t('FIXCHAR')"
          prop="conditions.PARAM_FIX_CHAR"
        >
          <a-input
            v-model="newRuleForm.conditions['PARAM_FIX_CHAR']"
            maxlength="1"
            allow-clear
          />
        </a-form-model-item>
        <!-- 检查长度 -->
        <a-form-model-item
          v-if="
            newRuleForm.dataType === 'PARAM' &&
            newRuleForm.conditions['PARAM_TREAT_TYPE'] === 'CHECKLENGTH'
          "
          :label="$t('CHECK_LENGTH')"
          prop="conditions.PARAM_CHECK_LENGTH"
        >
          <a-input-number
            v-model="newRuleForm.conditions['PARAM_CHECK_LENGTH']"
            :min="1"
          />
        </a-form-model-item>
        <!-- 日期增加(天) -->
        <a-form-model-item
          v-if="newRuleForm.dataType === 'DATE'"
          :label="$t('ADD_DAYS')"
        >
          <a-input-number
            v-model="newRuleForm.conditions['DATE_ADD']"
            style="width: 100%"
          />
        </a-form-model-item>
        <!-- 日期格式 -->
        <a-form-model-item
          v-if="newRuleForm.dataType === 'DATE'"
          :label="$t('DATE_FORMATE')"
          prop="conditions.DATE_FORMAT"
        >
          <i-table-select
            v-model="newRuleForm.conditions['DATE_FORMAT']"
            :options="selectData.dateFormats"
          />
        </a-form-model-item>
        <!-- 自定编码 -->
        <a-form-model-item
          v-if="
            newRuleForm.dataType === 'DATE' &&
            ['d'].indexOf(newRuleForm.conditions['DATE_FORMAT']) !== -1
          "
          :label="$t('SERIAL_TRANSFER')"
          prop="conditions.DATE_TRANSFER"
        >
          <!-- 默认去除IOQU -->
          <a-input
            v-model="newRuleForm.conditions['DATE_TRANSFER']"
            :placeholder="$t('EXCLUDE_IQQU')"
            allow-clear
            maxlength="32"
            show-word-limit
          />
        </a-form-model-item>
        <!-- 字典名称 -->
        <a-form-model-item
          v-if="newRuleForm.dataType === 'DICTIONARY'"
          :label="$t('DICT_LABEL')"
          prop="conditions.PARAM_NAME"
        >
          <a-select
            v-model="newRuleForm.conditions['PARAM_NAME']"
            :placeholder="$t('PLACESELECT')"
            @change="changeDictionaryName"
          >
            <a-select-option
              v-for="item in options"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label + `(${item.value})` }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          v-if="newRuleForm.dataType === 'DICTIONARY'"
          :label="$t('DEFAULT_VALUE')"
          prop="conditions.DICTIONARY_DEFAULT"
        >
          <a-select
            v-model="newRuleForm.conditions['DICTIONARY_DEFAULT']"
            :placeholder="$t('PLACESELECT')"
          >
            <a-select-option
              v-for="item in options2"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label + `(${item.value})` }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 规则 -->
        <a-form-model-item
          v-if="newRuleForm.dataType === 'SERIAL_NO'"
          :label="$t('SERIAL_RULE')"
          prop="conditions.SERIAL_RULE"
        >
          <i-table-select
            v-model="newRuleForm.conditions['SERIAL_RULE']"
            multiple
            semicolon
            :options="ruleConditions"
          />
        </a-form-model-item>
        <!-- 进制 -->
        <a-form-model-item
          v-if="newRuleForm.dataType === 'SERIAL_NO'"
          :label="$t('SERIAL_MODE')"
          prop="conditions.SERIAL_MODE"
        >
          <i-table-select
            v-model="newRuleForm.conditions['SERIAL_MODE']"
            :options="selectData.serialModes"
          />
        </a-form-model-item>
        <!-- 自定编码 -->
        <a-form-model-item
          v-if="
            newRuleForm.dataType === 'SERIAL_NO' &&
            newRuleForm.conditions['SERIAL_MODE'] === 'OTHER'
          "
          :label="$t('SERIAL_TRANSFER')"
          prop="conditions.SERIAL_TRANSFER"
        >
          <a-input
            v-model="newRuleForm.conditions['SERIAL_TRANSFER']"
            allow-clear
          />
        </a-form-model-item>
        <!-- 码数 -->
        <a-form-model-item
          v-if="newRuleForm.dataType === 'SERIAL_NO'"
          :label="$t('SERIAL_LENGTH')"
          prop="conditions.SERIAL_LENGTH"
        >
          <a-input-number
            v-model="newRuleForm.conditions['SERIAL_LENGTH']"
            :min="1"
            style="width: 100%"
            allow-clear
          />
        </a-form-model-item>
      </a-form-model>
    </i-dialog-form>
    <MomTable
      row-key="id"
      :columns="tableColumns"
      :data-source="formData.parts"
      :action-buttons="actionButtons"
      :whole="false"
      :scroll="{ x: 2300, y: 500 }"
      @delete="handleDelete"
      @edit="handleEdit"
    >
      <template slot="dataType" slot-scope="dataType">
        {{ dictCodeFormat(dataType, selectData.dataTypes) }}
      </template>
      <template slot="conditions.PARAM_NAME" slot-scope="conditions">
        <template v-if="newRuleForm.dataType === 'DICTIONARY'">
          {{ dictParamsFormat(conditions, options) }}
        </template>
        <template v-else>
          {{ dictParamsFormat(conditions, parameterNameOptions) }}
        </template>
      </template>
      <template slot="conditions.PARAM_TREAT_TYPE" slot-scope="conditions">
        {{ dictCodeFormat(conditions, selectData.paramTreatTypes) }}
      </template>
      <template slot="conditions.PARAM_REMOVE_LEFT" slot-scope="text, record">
        {{
          record.conditions.PARAM_REMOVE_LEFT
            ? record.conditions.PARAM_REMOVE_LEFT
            : record.conditions.PARAM_REMOVE_RIGHT
        }}
      </template>
      <template slot="conditions.SERIAL_MODE" slot-scope="conditions">
        {{ dictCodeFormat(conditions, selectData.serialModes) }}
      </template>
      <a-row slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('LABEL_ATTRIBUTES:ADD')"
          :disabled="!paramName"
          @click="handleAdd"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('LABEL_ATTRIBUTES:ADD')"
          type="primary"
          :disabled="!paramName"
          @click="handleSave"
        >
          <Icon type="icon-cur-save_1" :size="16" /> {{ $t("SAVE") }}
        </a-button>
        <a-alert
          style="margin-left: 15px"
          :message="$t('AFTER_ADDING_RULES_EFFECT')"
          banner
        />
      </a-row>
    </MomTable>
  </div>
</template>
<script>
import uniqBy from "lodash/uniqBy";
import { Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  name: "AttrTable",
  components: {
    Icon,
  },
  props: {
    labelCode: {
      type: String,
      default: "",
    },
    paramName: {
      type: String,
      default: "",
    },
    parameterNameData: {
      type: Array,
      default: () => [],
    },
    labelIds: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      // 表单数据
      formData: {
        labelCode: "",
        labelVersion: "",
        paramName: "",
        parts: [],
      },
      // 数据字典选项
      options: [],
      // 数据字典默认值选项
      options2: [],
      title: "",
      activeName: "a",
      activeNameB: "b",
      newRuleForm: {
        seq: "",
        dataType: "", // 	类型
        conditions: {
          FIXED_VALUE: "",
          PARAM_NAME: "",
          PARAM_SUB_RANGE: "",
          PARAM_SUB_LENGTH: "",
          PARAM_FIX_CHAR: "",
          PARAM_CHECK_LENGTH: "",
          DATE_FORMAT: "",
          DATE_ADD: "",
          DATE_TRANSFER: "",
          SERIAL_RULE: "",
          SERIAL_MODE: "",
          SERIAL_TRANSFER: "",
          PARAM_FIX_LENGTH: "",
          SERIAL_LENGTH: "",
        },
      },
      actionButtons: [
        this.hasAuth(`LABEL_ATTRIBUTES:EDIT`) && "edit",
        this.hasAuth(`LABEL_ATTRIBUTES:DELETE`) && "delete",
      ],
      selectData: {
        dataTypes: [
          // 固定值
          {
            label: this.$t("FIXED_VALUE"),
            value: "FIXED",
          },
          // 传值
          { label: this.$t("PARAM"), value: "PARAM" },
          // 日期
          { label: this.$t("DATE"), value: "DATE" },
          // 流水码
          { label: this.$t("SERIAL_NO"), value: "SERIAL_NO" },
          // 数据字典
          {
            label: this.$t("DICTIONARY_MANAGEMENT"),
            value: "DICTIONARY",
          },
        ],
        paramTreatTypes: [
          // 子字符串
          { label: "SUBSTRING", value: "SUBSTRING" },
          // 左边取值
          { label: "PRESUB", value: "PRESUB" },
          // 右边取值
          { label: "SUFSUB", value: "SUFSUB" },
          // 左边补值
          { label: "PREFIX", value: "PREFIX" },
          // 右边补值
          { label: "SUFFIX", value: "SUFFIX" },
          // 检查长度
          { label: "CHECK_LENGTH", value: "CHECKLENGTH" },
          // 右边去除
          { label: "PARAM_REMOVE_RIGHT", value: "REMOVERIGHT" },
          // 左边去除
          { label: "PARAM_REMOVE_LEFT", value: "REMOVELEFT" },
        ],
        dateFormats: [
          { label: "yyyy", value: "yyyy" },
          { label: "yy", value: "yy" },
          { label: "y", value: "y" },
          { label: "MM", value: "MM" },
          { label: "M", value: "M" },
          { label: "dd", value: "dd" },
          { label: "d", value: "d" },
          { label: "WW", value: "WW" },
          { label: "HH24", value: "HH24" },
          { label: "HH12", value: "HH12" },
          { label: "E", value: "E" },
          { label: "EEEE", value: "EEEE" },
        ],
        serialModes: [
          // 10进制
          { label: this.$t("DEC"), value: "DEC" },
          // 16进制
          { label: this.$t("HEX"), value: "HEX" },
          // 32进制(去IOQU)
          { label: this.$t("BASE32_IOQU"), value: "BASE32_IOQU" },
          // 32进制(去BDIO)
          { label: this.$t("BASE32_BDIO"), value: "BASE32_BDIO" },
          // 36进制
          { label: this.$t("BASE36"), value: "BASE36" },
          // 自定进制
          { label: this.$t("OTHER"), value: "OTHER" },
        ],
        params: [],
        parameterNames: [],
        addFlag: true, // 新增标志
      },
      tableData: [],
      drawerVisible: false,
    };
  },
  computed: {
    tableColumns() {
      return [
        {
          dataIndex: "dataType",
          sorter: false,
          scopedSlots: { customRender: "dataType" },
          title: () => this.$t("DATA_TYPE"), // 类型
          width: 120,
        },
        {
          dataIndex: "conditions.FIXED_VALUE",
          sorter: false,
          width: 120,
          title: () => this.$t("FIXED_VALUE"), // 固定值
        },
        {
          dataIndex: "conditions.PARAM_NAME",
          sorter: false,
          scopedSlots: { customRender: "conditions.PARAM_NAME" },
          title: () => this.$t("PARAMETER_NAME"), // 参数名
          minWidth: 260,
        },
        {
          dataIndex: "conditions.PARAM_TREAT_TYPE",
          scopedSlots: { customRender: "conditions.PARAM_TREAT_TYPE" },
          width: 120,
          sorter: false,
          title: () => this.$t("TREAT_TYPE"), // 特殊处理
        },
        {
          dataIndex: "conditions.PARAM_REMOVE_LEFT",
          sorter: false,
          width: 160,
          scopedSlots: { customRender: "conditions.PARAM_REMOVE_LEFT" },
          title: () => this.$t("REMOVE_LENGTH_LEFT"), // 左移除长度
        },
        {
          dataIndex: "conditions.PARAM_CHECK_LENGTH",
          sorter: false,
          width: 120,
          title: () => this.$t("CHECK_LENGTH"), // 检查长度
        },
        {
          dataIndex: "conditions.PARAM_SUB_RANGE",
          sorter: false,
          width: 120,
          title: () => this.$t("SUB_RANGE"), // 截取范围
        },
        {
          dataIndex: "conditions.PARAM_SUB_LENGTH",
          sorter: false,
          width: 120,
          title: () => this.$t("SUB_LENGTH"), // 截取长度
        },
        {
          dataIndex: "conditions.PARAM_FIX_CHAR",
          sorter: false,
          width: 120,
          title: () => this.$t("FIXCHAR"), // 补值
        },
        {
          dataIndex: "conditions.PARAM_FIX_LENGTH",
          sorter: false,
          width: 120,
          title: () => this.$t("LENGTH"), // 长度
        },
        {
          dataIndex: "conditions.DATE_ADD",
          sorter: false,
          width: 140,
          title: () => this.$t("ADD_DAYS"), // 日期增加()天)
        },
        {
          dataIndex: "conditions.DATE_FORMAT",
          sorter: false,
          width: 120,
          title: () => this.$t("DATE_FORMATE"), // 日期格式
        },
        {
          dataIndex: "conditions.SERIAL_RULE",
          sorter: false,
          minWidth: 120,
          title: () => this.$t("SERIAL_RULE"), // 规则
        },
        {
          dataIndex: "conditions.SERIAL_MODE",
          scopedSlots: { customRender: "conditions.SERIAL_MODE" },
          width: 160,
          sorter: false,
          title: () => this.$t("SERIAL_MODE"), // 进制
        },
        {
          dataIndex: "conditions.SERIAL_TRANSFER",
          sorter: false,
          width: 120,
          title: () => this.$t("SERIAL_TRANSFER"), // 自定编码
        },
        {
          dataIndex: "conditions.DATE_TRANSFER",
          sorter: false,
          minWidth: 280,
          title: () => this.$t("DATE_TRANSFER"), // 自定编码
        },
        {
          dataIndex: "conditions.SERIAL_LENGTH",
          sorter: false,
          minWidth: 120,
          title: () => this.$t("SERIAL_LENGTH"), // 码数
        },
      ];
    },
    subRules() {
      return {
        dataType: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.FIXED_VALUE": [
          {
            max: 256,
            required: true,
            message: this.$t("PLACEENTER") + 256 + this.$t("LENGTH_TIP"),
            trigger: "change",
          },
        ],
        "conditions.PARAM_NAME": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        "conditions.PARAM_SUB_RANGE": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.PARAM_SUB_LENGTH": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.PARAM_REMOVE_LEFT": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.PARAM_REMOVE_RIGHT": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.PARAM_FIX_LENGTH": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.PARAM_FIX_CHAR": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            required: true,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        "conditions.PARAM_CHECK_LENGTH": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.DATE_FORMAT": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.DATE_TRANSFER": [
          {
            min: 32,
            max: 32,
            message: this.$t("LENGTH_WARNINFO"),
            trigger: "blur",
          },
        ],
        "conditions.SERIAL_RULE": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.SERIAL_MODE": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.SERIAL_TRANSFER": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        "conditions.SERIAL_LENGTH": [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
    // 流水码规则条件
    ruleConditions() {
      const obj = [];
      this.formData.parts.forEach((item, idx) => {
        if (item.dataType !== "SERIAL_NO") {
          if (item.dataType !== "DATE") {
            const fixVal = item.conditions.FIXED_VALUE
              ? ` - ${item.conditions.FIXED_VALUE}`
              : "";
            const paramsVal = item.conditions.PARAM_NAME
              ? ` - ${this.dictParamsFormat(
                  item.conditions.PARAM_NAME,
                  this.parameterNameOptions
                )}`
              : "";
            obj.push({
              label: `${this.dictCodeFormat(
                item.dataType,
                this.selectData.dataTypes
              )}${fixVal}${paramsVal}`,
              value: `${idx + 1}`,
            });
          } else {
            obj.push({
              label: `${this.dictCodeFormat(
                item.dataType,
                this.selectData.dataTypes
              )}-${item.conditions.DATE_FORMAT}`,
              value: `${idx + 1}`,
            });
          }
        }
      });
      return obj;
    },
    // 移除长度的参数
    removeLengthParamName() {
      const list = ["REMOVERIGHT", "REMOVELEFT"];
      const paramsList = ["PARAM_REMOVE_RIGHT", "PARAM_REMOVE_LEFT"];
      const result =
        paramsList[list.indexOf(this.newRuleForm.conditions.PARAM_TREAT_TYPE)];
      return result || paramsList[0];
    },
  },
  watch: {
    paramName(newVal, oldVal) {
      if (!newVal) {
        this.formData.parts = [];
        return;
      }
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/print/attribute/get-by/${this.labelCode}/${this.paramName}`
        )
        .then((res) => {
          this.$set(this, "formData", this.transApiToLocal(res.data.data));
          if (this.formData.parts.length === 0) {
            this.formData.parts.push({
              ...res.data.data,
              id: 0,
              dataType: "PARAM",
              conditions: {
                DATE_ADD: "",
                DATE_FORMAT: "",
                DATE_TRANSFER: "",
                FIXED_VALUE: "",
                PARAM_CHECK_LENGTH: "",
                PARAM_FIX_CHAR: "",
                PARAM_FIX_LENGTH: "",
                PARAM_NAME: this.paramName,
                PARAM_SUB_LENGTH: "",
                PARAM_SUB_RANGE: "",
                SERIAL_LENGTH: "",
                SERIAL_MODE: "",
                SERIAL_RULE: "",
                SERIAL_TRANSFER: "",
              },
            });
          }
          this.formData.labelCode = this.labelCode;
          this.formData.paramName = newVal;
          this.addFlag = !!res.data.data.id;
        });
    },
    labelIds(oldVal, newVal) {
      this.selectData.labelIds = oldVal;
    },
    parameterNameData(oldVal, newVal) {
      this.selectData.params = oldVal;
      this.parameterNameOptions = oldVal;
    },
  },
  created() {
    // 获取所有数据字典的数据
    this.$axios
      .get(`${ApiConstant.PREFIX_CORE}/api/sys/dict/list`, {
        params: {
          dictCategory: "U",
        },
      })
      .then((res) => {
        const arr = [];
        if (res.data.data.length > 0) {
          res.data.data.forEach((item, index) => {
            arr.push({
              label: item.dictName,
              value: item.dictCode,
            });
          });
          this.options = arr;
        } else {
          this.options = [];
        }
      });
  },
  mounted() {},
  methods: {
    changeDictionaryName(e) {
      this.options2 = [];
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/dict-data/${e}`)
        .then((res) => {
          this.options2 = res.data.data;
        });
    },
    dictCodeFormat(value, options) {
      if (!value) return "";
      const result = options.find((item) => item.value === value)?.label;
      return result ? this.$t(result) : value;
    },
    dictParamsFormat(value, options) {
      if (!value) return "";
      const result = options.find((item) => item.value === value);
      return result ? `${this.$t(result.label)}(${result.value})` : value;
    },
    dataTypeChange() {
      this.newRuleForm.conditions = {
        FIXED_VALUE: "",
        PARAM_NAME: "",
        PARAM_SUB_RANGE: "",
        PARAM_SUB_LENGTH: "",
        PARAM_FIX_CHAR: "",
        PARAM_CHECK_LENGTH: "",
        DATE_FORMAT: "",
        DATE_ADD: "",
        DATE_TRANSFER: "",
        SERIAL_RULE: "",
        SERIAL_MODE: "",
        SERIAL_TRANSFER: "",
        PARAM_FIX_LENGTH: "",
        SERIAL_LENGTH: "",
        PARAM_REMOVE_LEFT: "",
        PARAM_REMOVE_RIGHT: "",
      };
      this.$refs.newRuleForm.clearValidate();
    },
    close(visible) {
      this.newRuleForm.dataType = "";
      this.newRuleForm.conditions = {
        FIXED_VALUE: "",
        PARAM_NAME: "",
        PARAM_SUB_RANGE: "",
        PARAM_SUB_LENGTH: "",
        PARAM_FIX_CHAR: "",
        PARAM_CHECK_LENGTH: "",
        DATE_FORMAT: "",
        DATE_ADD: "",
        DATE_TRANSFER: "",
        SERIAL_RULE: "",
        SERIAL_MODE: "",
        SERIAL_TRANSFER: "",
        PARAM_FIX_LENGTH: "",
        SERIAL_LENGTH: "",
        PARAM_REMOVE_LEFT: "",
        PARAM_REMOVE_RIGHT: "",
      };
      this.drawerVisible = visible;
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text
        .toLowerCase()
        .includes(input.toLowerCase());
    },
    saveNewRule() {
      this.$refs.newRuleForm.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.newRuleForm));
          if (this.add) {
            params.seq = this.formData.parts.length;
            this.formData.parts.push(params);
            this.$message.success(this.$t("ADD_SUCCESS"));
          } else {
            const index = this.formData.parts.findIndex(
              (item) => item.seq === params.seq
            );
            this.formData.parts.splice(index, 1, params);
            this.$message.success(this.$t("EDIT_SUCCESS"));
          }
          this.drawerVisible = false;
          this.newRuleForm.dataType = "";
          this.newRuleForm.conditions = {
            FIXED_VALUE: "",
            PARAM_NAME: "",
            PARAM_SUB_RANGE: "",
            PARAM_SUB_LENGTH: "",
            PARAM_FIX_CHAR: "",
            PARAM_CHECK_LENGTH: "",
            DATE_FORMAT: "",
            DATE_ADD: "",
            DATE_TRANSFER: "",
            SERIAL_RULE: "",
            SERIAL_MODE: "",
            SERIAL_TRANSFER: "",
            PARAM_FIX_LENGTH: "",
            SERIAL_LENGTH: "",
            PARAM_REMOVE_LEFT: "",
            PARAM_REMOVE_RIGHT: "",
          };
        }
      });
    },
    handleAdd() {
      this.title = this.$t("ADD");
      this.drawerVisible = true;
      this.add = true;
      this.$nextTick(() => {
        this.$refs.newRuleForm.clearValidate();
      });
    },
    handleEdit(row) {
      this.title = this.$t("EDIT");
      this.newRuleForm = JSON.parse(JSON.stringify(row));
      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.formData.parts.findIndex(
            (item) => item.seq === row.seq
          );
          this.formData.parts.splice(index, 1);
          this.$message.success(this.$t("DELETE_SUCCESS"));
        },
      });
    },
    handleSave() {
      // 将本地数据转为接口支持的格式
      const requestData = this.transLocalToApi(this.formData);
      if (this.addFlag) {
        this.$axios
          .post(`${ApiConstant.PREFIX_CORE}/api/print/attribute`, requestData)
          .then((res) => {
            this.$message.success(this.$t("ADD_SUCCESS"));
            this.$emit("saved");
          });
      } else {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/print/attribute`, requestData)
          .then((res) => {
            this.$message.success(this.$t("ADD_SUCCESS"));
            this.$emit("saved");
          });
      }
    },
    // 将本地数据转为接口数据格式
    transLocalToApi(obj) {
      const res = JSON.parse(JSON.stringify(obj));
      res.parts.forEach((item, idx) => {
        const conditions = [];
        // eslint-disable-next-line
        for (const i in item.conditions) {
          conditions.push({
            paramName: i,
            paramValue: item.conditions[i],
          });
        }
        // eslint-disable-next-line
        item.seq = idx + 1;
        // eslint-disable-next-line
        item.conditions = conditions;
      });
      return res;
    },
    // 将接口数据转为本地格式
    transApiToLocal(obj) {
      const res = JSON.parse(JSON.stringify(obj));
      res.parts.forEach((item, index) => {
        const conditions = {};
        item.conditions.forEach((cond) => {
          conditions[cond.paramName] = cond.paramValue;
        });
        // eslint-disable-next-line
        item.seq = index + 1;
        // eslint-disable-next-line
        item.conditions = conditions;
      });
      return res;
    },
    paramTreatTypeChange() {
      this.newRuleForm.conditions.PARAM_SUB_LENGTH = "";
      this.newRuleForm.conditions.PARAM_SUB_RANGE = "";
      this.newRuleForm.conditions.PARAM_FIX_LENGTH = "";
      this.newRuleForm.conditions.PARAM_FIX_CHAR = "";
      this.newRuleForm.conditions.PARAM_CHECK_LENGTH = "";
      this.newRuleForm.conditions.PARAM_REMOVE_LEFT = "";
      this.newRuleForm.conditions.PARAM_REMOVE_RIGHT = "";
      this.$refs.newRuleForm.clearValidate();
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.ant-input-number {
  width: 100%;
}
.button-top-table {
  display: flex;
  align-items: center;
}
/deep/.ant-table td {
  white-space: nowrap;
}
</style>
