<template>
  <span>
    <span @click="showModal">
      <slot>
        <a-button>
          <i class="iconfont icon-tianjia" />
          {{ $t("FIELD_EXTENSION") }}
        </a-button>
      </slot>
    </span>
    <MegaModal
      wrap-class-name="field-extend-modal"
      :width="1260"
      :title="$t('FIELD_EXTENSION')"
      :visible="visible"
      :mask-closable="false"
      @close="handleCancel"
      @cancel="handleCancel"
      @ok="handleSave"
    >
      <a-card
        :tab-list="tableNameList"
        :bordered="false"
        :active-tab-key="activeTabKey"
        @tabChange="(key) => onTabChange(key)"
      >
        <a-table
          ref="table"
          :key="activeTabKey"
          row-key="key"
          :columns="columns"
          :data-source="tabData[activeTabKey]"
          :pagination="false"
          :bordered="true"
          :scroll="{ y: 320 }"
        >
          <template slot="enableFlag" slot-scope="text, record, index, col">
            <a-checkbox
              :checked="[1, 'Y'].includes(text)"
              @change="
                (e) => handleCellChange(e.target.checked, index, col.dataIndex)
              "
            />
          </template>
          <template slot="fieldName" slot-scope="text, record, index, col">
            <div
              v-if="index > 9"
              :class="{
                'has-error': !fieldNameValidate(record),
              }"
            >
              <a-input
                :value="text"
                @change="
                  (e) => handleCellChange(e.target.value, index, col.dataIndex)
                "
              />
            </div>
            <span v-else>{{ text }}</span>
          </template>
          <template slot="fieldType" slot-scope="text, record, index, col">
            <a-select
              :value="text"
              style="width: 100%"
              @change="(e) => handleCellChange(e, index, col.dataIndex)"
            >
              <a-select-option
                v-for="item in fieldTypeList"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </template>
          <template slot="i18nCode" slot-scope="text, record, index, col">
            <div
              :class="{
                'has-error': !i18nCodeValidate(record),
              }"
            >
              <I18nSelect
                v-if="Boolean(clientTypeList.length && i18nTypeList.length)"
                ref="select"
                :value="text"
                :rules="rules"
                :client-type-list="clientTypeList"
                :i18n-type-list="i18nTypeList"
                @change="(e) => handleCellChange(e, index, col.dataIndex)"
              ></I18nSelect>
            </div>
          </template>
          <template slot="remark" slot-scope="text, record, index, col">
            <a-input
              :value="text"
              :placeholder="$t('PLACEENTER')"
              @change="
                (e) => handleCellChange(e.target.value, index, col.dataIndex)
              "
            />
          </template>
          <template slot="listFlag" slot-scope="text, record, index, col">
            <a-switch
              :checked="[1, 'Y'].includes(text)"
              size="small"
              @change="(e) => handleCellChange(e, index, col.dataIndex)"
            />
          </template>
          <template slot="searchFlag" slot-scope="text, record, index, col">
            <a-switch
              :checked="[1, 'Y'].includes(text)"
              :disabled="index > 9"
              size="small"
              @change="(e) => handleCellChange(e, index, col.dataIndex)"
            />
          </template>
          <template slot="searchRule" slot-scope="text, record, index, col">
            <a-select
              :value="text"
              style="width: 100%"
              :disabled="index > 9"
              @change="(e) => handleCellChange(e, index, col.dataIndex)"
            >
              <a-select-option
                v-for="item in fieldSearchRuleList"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </template>
          <template slot="operation" slot-scope="text, record, index">
            <a-icon
              v-if="index > 9"
              type="delete"
              class="text-error cursor-pointer"
              @click="() => handleDeleteField(index)"
            />
          </template>
        </a-table>

        <div class="add-field-btn" @click="handleAddField">
          <a-icon type="plus" class="mr-6" />
          <span>{{ $t("ADD_TO") }}</span>
        </div>
      </a-card>
    </MegaModal>
  </span>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";
import { Modal as MegaModal } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import I18nSelect from "@/components/I18nSelect";

const data = [];
for (let i = 1; i <= 10; i += 1) {
  data.push({
    enableFlag: "N",
    fieldName: `ext${i < 10 ? `0${i}` : i}`,
    fieldType: "TEXT",
    i18nCode: undefined,
    remark: undefined,
    listFlag: "N",
    searchFlag: "N",
    searchRule: "=",
    type: "STATIC",
    key: i - 1,
  });
}

export default {
  components: {
    MegaModal,
    I18nSelect,
  },
  props: {
    tableNameList: {
      type: Array,
      default: () => [],
    },
    rules: Boolean,
  },
  data() {
    return {
      clientTypeList: [],
      i18nTypeList: [],
      fieldTypeList: [],
      fieldExtendTypeList: [],
      fieldSearchRuleList: [],
      visible: false,
      activeTabKey: "",
      tabData: {},
    };
  },
  computed: {
    columns() {
      return [
        {
          title: this.$t("IS_ENABLE"), // 是否启用
          dataIndex: "enableFlag",
          align: "center",
          width: 90,
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          title: this.$t("FIELD"), // 字段
          dataIndex: "fieldName",
          align: "center",
          width: 140,
          scopedSlots: { customRender: "fieldName" },
        },
        {
          title: this.$t("TYPE"), // 类型
          dataIndex: "fieldType",
          align: "center",
          width: 120,
          scopedSlots: { customRender: "fieldType" },
        },
        {
          title: this.$t("INTERNATIONAL_CODING"), // 国际化编码
          dataIndex: "i18nCode",
          align: "center",
          width: 280,
          scopedSlots: { customRender: "i18nCode" },
        },
        {
          title: this.$t("REMARK"), // 备注
          dataIndex: "remark",
          align: "center",
          scopedSlots: { customRender: "remark" },
        },
        {
          title: this.$t("IS_SHOW"), // 是否显示
          dataIndex: "listFlag",
          align: "center",
          width: 90,
          scopedSlots: { customRender: "listFlag" },
        },
        {
          title: this.$t("IS_QUERY"), // 是否查询
          dataIndex: "searchFlag",
          align: "center",
          width: 90,
          scopedSlots: { customRender: "searchFlag" },
        },
        {
          title: this.$t("QUERY_RULES"), // 查询规则
          dataIndex: "searchRule",
          align: "center",
          width: 100,
          scopedSlots: { customRender: "searchRule" },
        },
        {
          title: this.$t("OPERATION"), // 查询规则
          dataIndex: "operation",
          align: "center",
          width: 62,
          scopedSlots: { customRender: "operation" },
        },
      ];
    },
  },
  watch: {
    "tableNameList.length": {
      handler() {
        this.queryExtendFieldDetail();
      },
      immediate: true,
    },
  },
  created() {
    this.activeTabKey = this.tableNameList?.[0]?.key;
    this.initDict();
  },
  methods: {
    initDict() {
      this.getDictByCode("DIC:CORE:MOM_VERSION").then((res) => {
        this.clientTypeList = res.data.data || [];
      });
      this.getDictByCode("DIC:CORE:I18N_TYPE").then((res) => {
        this.i18nTypeList = res.data.data || [];
      });
      return Promise.all([
        this.getDictByCode("DIC:CORE:FIELD_EXTEND_FIELD_TYPE"),
        this.getDictByCode("DIC:CORE:FIELD_EXTEND_TYPE"),
        this.getDictByCode("DIC:CORE:FIELD_EXTEND_SEARCH_RULE"),
      ]).then(([fieldTypeRes, fieldExtendTypeRes, fieldSearchRuleRes]) => {
        this.fieldTypeList = fieldTypeRes.data.data;
        this.fieldExtendTypeList = fieldExtendTypeRes.data.data;
        this.fieldSearchRuleList = fieldSearchRuleRes.data.data;
      });
    },
    queryExtendFieldDetail() {
      this.tableNameList.length &&
        this.$axios({
          method: "get",
          url: `${ApiConstant.PREFIX_CORE}/api/sys/filed-extend-config/detail-batch`,
          params: {
            tableNameList: this.tableNameList.map((item) => item.key).join(","),
            moduleCode: this.$store.state.activatedModule,
          },
        }).then((res) => {
          this.tableNameList.forEach((item) => {
            const resData = res.data.data?.fieldExtendConfigList?.find(
              (e) => e.tableName === item.key
            );
            const dataSource = (resData && resData.items) || [];

            const staticData = dataSource.filter((e) => e.type === "STATIC");
            const value = cloneDeep(data);
            value.forEach((e) => {
              const tmp = staticData.find((d) => d.fieldName === e.fieldName);

              if (tmp) {
                // eslint-disable-next-line no-param-reassign
                e = Object.assign(e, tmp);
              }
            });

            const dynamicData = dataSource.filter((e) => e.type === "DYNAMIC");
            dynamicData.forEach((e) => {
              value.push(cloneDeep(e));
            });

            this.$set(this.tabData, item.key, value);
          });
        });
    },
    onTabChange(key) {
      this.activeTabKey = key;
    },
    showModal() {
      this.visible = true;
    },
    handleCancel() {
      this.visible = false;
    },
    validateReqData() {
      const items = [];
      for (let i = 0; i < this.tabData[this.activeTabKey].length; i += 1) {
        const record = this.tabData[this.activeTabKey][i];

        const valid =
          this.i18nCodeValidate(record) && this.fieldNameValidate(record);
        if (valid) {
          if (record.i18nCode) {
            const tmp = cloneDeep(record);
            delete tmp.key;
            items.push(tmp);
          }
        } else {
          return false;
        }
      }
      return items;
    },
    handleSave() {
      const items = this.validateReqData();
      if (typeof items === "object") {
        this.$axios({
          method: "post",
          url: `${ApiConstant.PREFIX_CORE}/api/sys/filed-extend-config/save`,
          data: {
            tableName: this.activeTabKey,
            items,
            moduleCode: this.$store.state.activatedModule,
          },
        }).then(() => {
          this.$message.success(this.$t("EDIT_SUCCESS"));
          this.visible = false;
          this.$emit("update", "exField");
        });
      } else {
        this.$message.error(this.$t("RED_AREA_DATA_PLACE_ENTER"));
      }
    },
    handleAddField() {
      this.$set(
        this.tabData[this.activeTabKey],
        this.tabData[this.activeTabKey].length,
        {
          enableFlag: "N",
          fieldName: undefined,
          fieldType: "TEXT",
          i18nCode: undefined,
          remark: undefined,
          listFlag: "N",
          searchFlag: "N",
          searchRule: undefined,
          type: "DYNAMIC",
          key: this.tabData[this.activeTabKey].length,
        }
      );
      // 滚动到表格底部
      this.$nextTick(() => {
        const tableEl = this.$refs.table?.$el;
        const scrollEl = tableEl?.querySelector(".ant-table-body");
        if (scrollEl) {
          const tableHeadHeight = 46;
          const { offsetHeight = 0, scrollHeight = 0 } = scrollEl;
          const scrollTop = scrollHeight - offsetHeight;
          scrollEl.scrollTop =
            scrollTop > tableHeadHeight
              ? scrollTop + tableHeadHeight
              : tableHeadHeight;
        }
      });
    },
    handleDeleteField(index) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.tabData[this.activeTabKey].splice(index, 1);
        },
      });
    },
    handleCellChange(value, index, attr) {
      if (["enableFlag", "listFlag", "searchFlag"].includes(attr)) {
        this.tabData[this.activeTabKey][index][attr] = value ? "Y" : "N";
      } else {
        this.tabData[this.activeTabKey][index][attr] = value;
      }
    },
    fieldNameValidate(record) {
      if (record.fieldName) {
        const dynamicData = this.tabData[this.activeTabKey].filter(
          (e) => e.type === "DYNAMIC"
        );
        const repeat = [];
        dynamicData.reduce(function (_value, item) {
          const value = _value;
          if (item.fieldName) {
            if (value[item.fieldName]) {
              value[item.fieldName] += 1;
              repeat.push(item.fieldName);
            } else {
              value[item.fieldName] = 1;
            }
          }
          return value;
        }, {});

        return !repeat.includes(record.fieldName);
      }

      return ![1, "Y"].includes(record.enableFlag);
    },
    i18nCodeValidate(record) {
      if (record.type === "STATIC") {
        return !([1, "Y"].includes(record.enableFlag) && !record.i18nCode);
      }

      return !([1, "Y"].includes(record.enableFlag) && !record.i18nCode);
    },
    renderButton() {
      return (
        <a-button>
          <i class="iconfont icon-tianjia" />
          {this.$t("FIELD_EXTENSION")}
        </a-button>
      );
    },
  },
};
</script>
