import cloneDeep from "lodash/cloneDeep";
import { Modal as MegaModal } from "@mega-design/ui-vue";
import ApiConstant from "~/api/ApiConstant";

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 {
  props: {
    tableNameList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      fieldTypeList: [],
      fieldExtendTypeList: [],
      fieldSearchRuleList: [],
      visible: false,
      activeTabKey: "",
      tabData: {},
      i18nDialogVisible: false, // 国际化弹框
      i18nCodeList: [], // 国际化列表
      dialogForm: {
        id: null,
        clientType: "",
        i18nCode: "",
        type: "",
      },
      oldI18nCode: null,
      // 表单的配置项详情
      dialogFormItem: {
        i18nCode: {
          i18n: "CODE", // 编码
          isRequired: true,
          rule: {
            max: 128,
            required: true,
            message: this.$t("PLACEENTER") + 128 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        },
        clientType: {
          itemType: "select",
          isRequired: true,
          i18n: "MOM_VERSION",
          width: 80,
          options: this.momVersionList,
        },
        type: {
          itemType: "select",
          isRequired: true,
          i18n: "TYPE",
          width: 80,
          options: this.typeList,
        },
      },
      momVersionList: [], // mom 版本列表
      typeList: [],
      curIndex: 0,
    };
  },
  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: 260,
          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,
    },
    momVersionList: {
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 0) {
          this.dialogFormItem.clientType.options = newVal;
        }
      },
      deep: true,
      immediate: true,
    },
    typeList: {
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 0) {
          this.dialogFormItem.type.options = newVal;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  async created() {
    this.activeTabKey = this.tableNameList?.[0]?.key;
    await this.initDict();
  },
  beforeMount() {
    this.$store.state.app.languages.forEach((item) => {
      this.$set(this.dialogFormItem, item.value, {
        inputType: "textarea",
        i18n: item.label,
      });
    });
  },
  methods: {
    initDict() {
      const params = {
        size: 20,
        page: 1,
        clientType: "MOM",
        keyword: "",
      };
      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"),
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/sys/i18n/search`, {
          params,
        }),
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:CORE:MOM_VERSION`
        ), // mom版本数据字典
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:CORE:I18N_TYPE`
        ), // 国际化类型数据字典
      ]).then(
        ([
          fieldTypeRes,
          fieldExtendTypeRes,
          fieldSearchRuleRes,
          i18nRes,
          momVersionRes,
          typeRes,
        ]) => {
          this.fieldTypeList = fieldTypeRes.data.data || [];
          this.fieldExtendTypeList = fieldExtendTypeRes.data.data || [];
          this.fieldSearchRuleList = fieldSearchRuleRes.data.data || [];
          this.i18nCodeList = i18nRes.data.data.records || [];
          this.momVersionList = momVersionRes.data.data || [];
          this.typeList = typeRes.data?.data || [];
        }
      );
    },
    queryExtendFieldDetail() {
      this.tableNameList.length &&
        this.$axios
          .get(
            `${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
          .post(`${ApiConstant.PREFIX_CORE}/api/sys/filed-extend-config/save`, {
            tableName: this.activeTabKey,
            items,
            moduleCode: this.$store.state.activatedModule,
          })
          .then(() => {
            this.$message.success("扩展字段修改成功");
            this.visible = false;
            this.$emit("refresh");
          });
      } else {
        this.$message.error("请完善或修改红色区域数据");
      }
    },
    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,
        }
      );
    },
    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);
        },
      });
    },
    remoteMethod(val) {
      const params = {
        size: 20,
        page: 1,
        clientType: "MOM",
        keyword: val,
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/i18n/search`, {
          params,
        })
        .then((res) => {
          this.i18nCodeList = res.data?.data?.records || [];
        });
    },
    changeI18n(index) {
      this.curIndex = index;
      this.dialogForm.id = null;
      this.$store.state.app.languages.forEach((item) => {
        this.$store.state.app.languages.forEach((code) => {
          this.dialogForm[code.value] = "";
          this.$set(this.dialogForm, code.value, "");
        });
      });
      this.$set(this.dialogForm, "i18nCode", "");
      this.$set(this.dialogForm, "clientType", this.momVersionList[0].value);
      this.$forceUpdate();
      this.i18nDialogVisible = true;
    },
    i18nSave() {
      const { id, i18nCode, type, clientType } = this.dialogForm;
      const params = {
        i18nCode,
        type,
        clientType,
        items: this.$store.state.app.languages.map((item) => {
          const { label, value } = item;
          return {
            dataValue: this.dialogForm[value],
            i18nCode,
            languageCode: value,
            languageName: label,
          };
        }),
      };
      this.$refs.drawerForm.$refs.iForm.validate((valid) => {
        if (valid) {
          if (this.dialogForm.i18nCode === this.oldI18nCode && id) {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/sys/i18n`, {
                id,
                ...params,
              })
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                // this.$set(this.menuForm, 'menuName', this.dialogForm.i18nCode)
                this.$emit("saveMenuCodeI18n", this.dialogForm.i18nCode);
                this.i18nDialogVisible = false;
                this.$emit("refreshTable");
                this.$parent.handleRefreshI18n();
              });
          } else {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/sys/i18n`, params)
              .then((res) => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.tabData[this.activeTabKey][this.curIndex].i18nCode =
                  this.dialogForm.i18nCode;
                this.$forceUpdate();
                this.i18nDialogVisible = false;
              });
          }
        }
      });
    },
    i18nSaveCancel() {
      this.i18nDialogVisible = false;
      this.i18nCodeList = [];
    },
    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>
      );
    },
  },
  render() {
    const defaultButton = this.$scopedSlots.default
      ? this.$scopedSlots.default()
      : this.renderButton();
    return (
      <span>
        <span onClick={this.showModal}>{defaultButton}</span>
        <MegaModal
          class={"dictDialog"}
          title={this.$t("I18N_INFO")}
          visible={this.i18nDialogVisible}
          centered={true}
          mask-closable={false}
          destroy-on-close={true}
          onCancel={(e) => this.i18nSaveCancel}
          onClose={(e) => this.i18nSaveCancel}
        >
          <i-form
            ref={"drawerForm"}
            label-width={100}
            form-item={this.dialogFormItem}
            search-form={this.dialogForm}
            span={1}
          />
          <template slot="footer">
            <a-button type="primary" onClick={(e) => this.i18nSave()}>
              <i class={"iconfont icon-baocun"}></i> {this.$t("SAVE")}
            </a-button>
            <a-button
              class={"iconfont icon-quxiao"}
              onClick={(e) => this.i18nSaveCancel()}
            >
              <i class={"iconfont icon-quxiao"}></i> {this.$t("CANCEL")}
            </a-button>
          </template>
        </MegaModal>
        <MegaModal
          width={1260}
          wrapClassName="field-extend-modal"
          title={this.$t("FIELD_EXTENSION")}
          visible={this.visible}
          maskClosable={false}
          onClose={this.handleCancel}
          onCancel={this.handleCancel}
          onOk={this.handleSave}
        >
          <a-card
            tab-list={this.tableNameList}
            bordered={false}
            active-tab-key={this.activeTabKey}
            onTabChange={(key) => this.onTabChange(key)}
          >
            <a-table
              key={this.activeTabKey}
              rowKey="key"
              columns={this.columns}
              data-source={this.tabData[this.activeTabKey]}
              pagination={false}
              bordered={true}
              scopedSlots={{
                enableFlag: (text, record, index, col) => {
                  const checked = [1, "Y"].includes(text);
                  return (
                    <a-checkbox
                      checked={checked}
                      onChange={(e) =>
                        this.handleCellChange(
                          e.target.checked,
                          index,
                          col.dataIndex
                        )
                      }
                    />
                  );
                },
                fieldName: (text, record, index, col) => {
                  return index > 9 ? (
                    <div
                      class={{
                        "has-error": !this.fieldNameValidate(record),
                      }}
                    >
                      <a-input
                        value={text}
                        onChange={(e) =>
                          this.handleCellChange(
                            e.target.value,
                            index,
                            col.dataIndex
                          )
                        }
                      />
                    </div>
                  ) : (
                    text
                  );
                },
                fieldType: (text, record, index, col) => {
                  return (
                    <a-select
                      value={text}
                      style="width: 100%"
                      onChange={(e) =>
                        this.handleCellChange(e, index, col.dataIndex)
                      }
                    >
                      {this.fieldTypeList.map((item) => (
                        <a-select-option key={item.value} value={item.value}>
                          {item.label}
                        </a-select-option>
                      ))}
                    </a-select>
                  );
                },
                i18nCode: (text, record, index, col) => {
                  return (
                    <div
                      class={{
                        "has-error": !this.i18nCodeValidate(record),
                      }}
                    >
                      <a-row>
                        <a-col span={"20"}>
                          <a-select
                            value={text}
                            style="width: 100%"
                            show-search
                            filter-option={false}
                            default-active-first-option={false}
                            onSearch={(e) =>
                              this.remoteMethod(e, index, col.dataIndex)
                            }
                            onChange={(e) =>
                              this.handleCellChange(e, index, col.dataIndex)
                            }
                          >
                            {this.i18nCodeList.map((item) => (
                              <a-select-option
                                key={item.id}
                                value={item.i18nCode}
                              >
                                {item.i18nCode}
                              </a-select-option>
                            ))}
                          </a-select>
                        </a-col>
                        <a-col span={"4"}>
                          <a-button
                            icon={"plus"}
                            onClick={(e) => this.changeI18n(index)}
                          ></a-button>
                        </a-col>
                      </a-row>
                    </div>
                  );
                },
                remark: (text, record, index, col) => {
                  return (
                    <a-input
                      value={text}
                      onChange={(e) =>
                        this.handleCellChange(
                          e.target.value,
                          index,
                          col.dataIndex
                        )
                      }
                    />
                  );
                },
                listFlag: (text, record, index, col) => {
                  const checked = [1, "Y"].includes(text);
                  return (
                    <a-switch
                      checked={checked}
                      size="small"
                      onChange={(e) =>
                        this.handleCellChange(e, index, col.dataIndex)
                      }
                    />
                  );
                },
                searchFlag: (text, record, index, col) => {
                  const checked = [1, "Y"].includes(text);
                  return (
                    <a-switch
                      checked={checked}
                      size="small"
                      disabled={index > 9}
                      onChange={(e) =>
                        this.handleCellChange(e, index, col.dataIndex)
                      }
                    />
                  );
                },
                searchRule: (text, record, index, col) => {
                  return (
                    <a-select
                      value={text}
                      style="width: 100%"
                      disabled={index > 9}
                      onChange={(e) =>
                        this.handleCellChange(e, index, col.dataIndex)
                      }
                    >
                      {this.fieldSearchRuleList.map((item) => (
                        <a-select-option key={item.value} value={item.value}>
                          {item.label}
                        </a-select-option>
                      ))}
                    </a-select>
                  );
                },
                operation: (text, record, index, col) => {
                  if (index > 9) {
                    return (
                      <a-icon
                        type="delete"
                        class="text-error cursor-pointer"
                        onClick={() => this.handleDeleteField(index)}
                      />
                    );
                  }
                  return null;
                },
              }}
            />

            <div class="add-field-btn" onClick={this.handleAddField}>
              <a-icon type="plus" class="mr-6" />
              <span>{this.$t("ADD_TO")}</span>
            </div>
          </a-card>
        </MegaModal>
      </span>
    );
  },
};
