import uniq from "lodash/uniq";
import ApiConstant from "~/api/ApiConstant";
import { getObjByString } from "~/utils/util";

export default {
  data() {
    return {
      fieldExForm: {},
      fieldExFormItem: {},
      dynamicExFieldNames: {},
    };
  },
  methods: {
    queryExtend() {
      return 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,
        },
      });
    },
    queryAuth() {
      return this.$axios({
        method: "get",
        url: `${ApiConstant.PREFIX_CORE}/api/sys/field-visible/list-column-batch-by-module`,
        params: {
          tableNameList: this.tableNameList[0]?.key,
          moduleCode: this.$store.state.activatedModule,
        },
      });
    },
    queryField() {
      return new Promise((resolve, reject) => {
        Promise.all([this.queryExtend(), this.queryAuth()])
          .then((res) => {
            const [extendRes, authRes] = res;
            const { fieldExtendConfigList = [], fieldHiddenConfigList = [] } =
              extendRes.data.data;
            fieldExtendConfigList.forEach((item, index) => {
              // 扩展字段隐藏(禁用)字段
              const exHiddenField = item.items
                ?.filter((e) => e.enableFlag !== "Y")
                ?.map((e) => e.fieldName);
              // 运维授权隐藏的表字段
              const opHiddenFieldName = fieldHiddenConfigList
                .filter((e) => e.tableName === item.tableName)
                .map((e) => e.fieldName);
              // 页面授权表字段
              const pageAuthData = authRes.data.data.find(
                (e) => e.tableName === item.tableName
              );
              // 页面授权隐藏的表字段
              const pageHiddenFieldName = pageAuthData?.fieldList
                ?.filter((e) => e.enableFlag !== "Y")
                ?.map((e) => e.fieldName);
              // 隐藏字段
              const hiddenFieldName = uniq(
                [].concat(exHiddenField, opHiddenFieldName, pageHiddenFieldName)
              );
              // 表扩展字段
              this.$set(this.fieldExForm, item.tableName, {});
              this.$set(this.fieldExFormItem, item.tableName, {});
              this.$set(this.dynamicExFieldNames, item.tableName, []);
              // 列表，搜索，form添加扩展字段
              item.items.forEach((e) => {
                // 列表页搜索条件
                if ([1, "Y"].includes(e.searchFlag)) {
                  this?.[this?.dataAttr?.queryFormItem] &&
                    this.$set(this[this.dataAttr.queryFormItem], e.fieldName, {
                      label: () => this.$t(e.i18nCode),
                    });
                  this?.[this?.dataAttr?.queryForm] &&
                    this.$set(this[this.dataAttr.queryForm], e.fieldName, "");
                }
                // 列表展示
                if ([1, "Y"].includes(e.listFlag)) {
                  if (this?.[this?.dataAttr?.tableColumns]) {
                    const columnKeys =
                      this[[this.dataAttr.tableColumns]]?.map(
                        (column) => column.dataIndex
                      ) || [];
                    if (!columnKeys.includes(e.fieldName)) {
                      this[this.dataAttr.tableColumns].push({
                        title: () => this.$t(e.i18nCode),
                        dataIndex: e.fieldName,
                        width: 200,
                      });
                    }
                  }
                }
                // 新增、编辑页 form
                e.type === "DYNAMIC" &&
                  this.dynamicExFieldNames[item.tableName].push(e.fieldName);
                // 设置页面的扩展数据
                this?.[this?.dataAttr?.form] &&
                  this.$set(
                    this[this.dataAttr.form],
                    e.fieldName,
                    this[this.dataAttr.form]?.[e.fieldName] || undefined
                  );
                this.$set(
                  this.fieldExForm[item.tableName],
                  e.fieldName,
                  undefined
                );
                this.$set(this.fieldExFormItem[item.tableName], e.fieldName, {
                  label: e.i18nCode,
                  type: e.type,
                });
              });
              // 列表，搜索，form隐藏字段
              hiddenFieldName.forEach((e) => {
                this?.[this?.dataAttr?.queryForm] &&
                  delete this[this.dataAttr.queryForm][e];
                this?.[this?.dataAttr?.queryFormItem] &&
                  delete this[this.dataAttr.queryFormItem][e];
                if (this?.[this?.dataAttr?.tableColumns]) {
                  const columnIndex = this?.[
                    this?.dataAttr?.tableColumns
                  ].findIndex((column) => column.dataIndex === e);
                  columnIndex > -1 &&
                    this?.[this?.dataAttr?.tableColumns].splice(columnIndex, 1);
                }
                const dynamicFieldIndex = this.dynamicExFieldNames[
                  item.tableName
                ].findIndex((dynamicField) => dynamicField === e);
                if (dynamicFieldIndex > -1) {
                  this.dynamicExFieldNames[item.tableName].splice(
                    dynamicFieldIndex,
                    1
                  );
                }
                this?.[this?.dataAttr?.form] &&
                  delete this?.[this?.dataAttr?.form][e];
                this.fieldExForm[item.tableName] &&
                  delete this.fieldExForm[item.tableName][e];
                this.fieldExFormItem[item.tableName] &&
                  delete this.fieldExFormItem[item.tableName][e];
              });
            });

            resolve([extendRes, authRes]);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    fieldExReqDataFn(tableName, request = {}) {
      const req = {
        ...(this?.[this.dataAttr?.form] || {}),
        ...request,
      };

      const extJson = {};

      this.dynamicExFieldNames[tableName]?.forEach((item) => {
        req[item] && (extJson[item] = req[item]);

        delete req[item];
      });

      req.extJson = JSON.stringify(extJson);

      return req;
    },
    fieldExResDataFn(response) {
      if (Array.isArray(response)) {
        return response.map((item) => {
          const { extJson, ...rest } = item || {};
          const extJsonData = getObjByString(extJson);
          return {
            ...rest,
            ...(extJsonData || {}),
          };
        });
      }
      if (response instanceof Object) {
        const { extJson, ...rest } = response || {};
        const extJsonData = getObjByString(extJson);
        return {
          ...rest,
          ...(extJsonData || {}),
        };
      }
      return null;
    },
    fieldExRenderFn(h, tableName, config = {}) {
      let {
        layout = "standard", // layout: standard 与 grid
        itemSpan = 24,
      } = config;

      // 判断布局
      if (!["standard", "grid"].includes(layout)) {
        layout = "standard"; // layout: standard 与 grid
        itemSpan = 24;
      }
      const items = Object.keys(this.fieldExForm[tableName] || {});
      const EXTENDED_FIELD = this.$t("EXTENDED_FIELD");
      if (items.length) {
        const dom =
          layout === "grid" ? (
            <a-collapse
              default-active-key="fieldExCollapseKey"
              expand-icon-position="right"
              class="collapse-header-divide"
              bordered={false}>
              <a-collapse-panel
                key="fieldExCollapseKey"
                header={EXTENDED_FIELD}>
                <a-row gutter={30}>
                  {items.map((key) => (
                    <a-col key={key} span={itemSpan}>
                      <a-form-model-item
                        prop={key}
                        label={this.$t(
                          this.fieldExFormItem[tableName]?.[key].label
                        )}>
                        {{ key }}
                        <a-input
                          v-model={this[this.dataAttr.form][key]}
                          placeholder={this.$t("PLACEENTER")}
                          clearable
                        />
                      </a-form-model-item>
                    </a-col>
                  ))}
                </a-row>
              </a-collapse-panel>
            </a-collapse>
          ) : (
            items.map((key) => (
              <a-form-model-item
                key={key}
                prop={key}
                label={this.fieldExFormItem[tableName]?.[key].label}>
                <a-input
                  v-model={this[this.dataAttr.form][key]}
                  placeholder={this.$t("PLACEENTER")}
                  clearable
                />
              </a-form-model-item>
            ))
          );

        this.$slots.RenderFieldExtendDom = dom;
      } else {
        this.$slots.RenderFieldExtendDom = null;
      }
    },
    // 字段扩展刷新
    handleRefresh(isExField) {
      this.fieldExForm = {};
      this.fieldExFormItem = {};
      this.dynamicExFieldNames = {};
      this.queryField();

      if (
        isExField === "exField" &&
        this.$refs.FieldAuthComp?.queryAuthFieldDetail instanceof Function
      ) {
        this.$refs.FieldAuthComp?.queryAuthFieldDetail();
      }
    },
  },
};
