<template>
  <!-- <div class="content"> -->
  <!-- //基础信息 -->
  <div class="main-content main-content-padding">
    <h-card class="margin-bottom list-query-form">
      <h-b-form ref="formRef" name="use" id="query-config-form" v-bind="props" :is-query="false">
        <template #header>
          <p class="card-title">
            <span style="font-size: 18px; font-weight: 550">
              {{ t('queryConfiguration.configCreate.form.title') }}
            </span>
          </p>
        </template>
        <template #queryPermissions>
          <h-input
            :disabled="_.disabled"
            :title="queryPermissionsVal"
            v-model:value="queryPermissionsVal"
            @click="baseCheckEvent"
          ></h-input>
        </template>
      </h-b-form>
    </h-card>
    <!-- </div> -->
    <!-- 查询条件 -->
    <div class="query-config-component">
      <div class="query-config-component__conditions">
        <query-component
          id="query-config-queryConditions"
          ref="conditionsComponentRef"
          action="conditions"
          :title="'queryConfiguration.configCreate.queryConditions.queryConditions'"
          :searchLable="
            t('queryConfiguration.configCreate.queryConditions.queryConditionsDisplayField')
          "
          :queryDisable="_.disabled"
          :modelGroup="modelGroup"
          :storedData="queryConditionStoredData"
        ></query-component>
      </div>
      <div class="query-config-component__conditions">
        <query-component
          id="query-config-queryResult"
          ref="queryComponentRef"
          action="query"
          :title="'queryConfiguration.configCreate.queryConditions.queryResults'"
          :searchLable="
            t('queryConfiguration.configCreate.queryConditions.queryResultDisplayField')
          "
          :queryDisable="_.disabled"
          :modelGroup="modelGroup"
          :storedData="queryResultStoredData"
        ></query-component>
      </div>
      <!-- </div> -->
      <!-- 隐藏查询规则 -->
      <div class="query-config-component__bottom">
        <hidden-rules-query
          ref="hiddenRulesQueryRef"
          :hiddenDisable="_.disabled"
          :modelGroup="modelGroup"
          :storedData="hiddenConditionStoredData"
        ></hidden-rules-query>
      </div>
    </div>
    <!-- 取消保存按钮实现 -->
    <div v-if="!_.disabled" class="permission-pllicy-btn">
      <h-button :loading="loading" @click="cancelPage">{{ t('platform.common.cancel') }}</h-button>
      <h-button :loading="loading" type="primary" @click="savePermissionData">
        {{ t('platform.common.save') }}
      </h-button>
    </div>
    <div v-if="_.disabled" class="permission-pllicy-btn">
      <h-button type="primary" @click="closePage">{{ t('platform.common.close') }}</h-button>
    </div>
  </div>
  <!-- 主模型 -->
  <master-model-select
    ref="MasterModelSelectRef"
    @permissionSubTypeFunSuccess="permissionSubTypeFunSuccess"
  ></master-model-select>
  <!-- 查询权限 -->
  <search-auth-model
    ref="SearchAuthModelRef"
    @searchAuthModelFunSuccess="searchAuthModelFunSuccess"
    @dataPerInfo="dataPerInfo"
  ></search-auth-model>
</template>

<script lang="ts">
import { useForm } from '@crami/bui-platform';
import { defineComponent, ref, reactive, onBeforeMount, toRef } from 'vue';
import { useI18n } from '@crami/locale';
// import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
// import { useHttp } from '@crami/http';
import MasterModelSelect from './Components/MasterModelSelect.vue';
import SearchAuthModel from './Components/SearchAuthModel.vue';
import HiddenRulesQuery from './Components/HiddenRulesQuery.vue';
import { useHttp } from '@crami/http';
import { message } from '@crami/ui';
import QueryComponent from './Components/QueryComponent.vue';
import ModelSelector from './Components/ModelSelector.vue';
import { useComponentRegister } from '@crami/bui';
import { useRouter } from 'vue-router';
// TODO: 去掉关闭页签
// import { useMultiTab } from '@/components/multi-tab';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';

export default defineComponent({
  name: 'QueryConfig',
  components: {
    MasterModelSelect,
    SearchAuthModel,
    HiddenRulesQuery,
    QueryComponent,
    ModelSelector,
  },
  props: {
    disabled: {
      type: Boolean,
    },
    config_eid: {
      type: String,
    },
  },
  emits: ['success'],
  setup(_) {
    const { t } = useI18n();
    const router = useRouter();
    // const [{ close, refresh }] = useMultiTab();
    const loading = ref(false);
    const queryPermissions = ref([]);
    // 隐藏查询规则
    const hiddenRulesQueryRef = ref(null);
    // 查询条件REF
    const conditionsComponentRef = ref(null);
    // 查询结果REF
    const queryComponentRef = ref(null);
    // 主模型ref
    const MasterModelSelectRef = ref(null);
    // 查询权限
    const SearchAuthModelRef = ref(null);

    const modelGroup = ref({ masterModel: null, children: [], loaded: false });

    const config_eid = _?.config_eid || '';
    const disabledBoolean = toRef(_, 'disabled');

    const queryConditionStoredData = ref('');
    const queryResultStoredData = ref('');
    const hiddenConditionStoredData = ref('');

    const dataPerInfo = ref({ dataPerObjectVO: null });

    // 查询通用查询配置历史配置信息
    const queryCommonQueryConfig = configEid => {
      let params = {
        eid: configEid,
      };
      async function fetchData() {
        const result = await useHttp({
          url: '/api/commonquery/commonQuery/front/getConfigListById',
          method: 'get',
          params: {
            ...params,
          },
        });
        if (result.code == 200 && result.data) {
          let configData = result.data[0];
          let refModelCode = JSON.parse(configData?.refModelCode);
          methodsMain.setData({ name: configData?.ename });
          modelGroup.value.masterModel = {
            label: configData?.majorModelDesc,
            value: configData?.majorModelCode,
          };
          modelGroup.value.children = refModelCode;

          methodsMain.setData({ masterModel: modelGroup.value.masterModel });

          modelGroup.value.loaded = true;

          // 切换主模型更新关联模型参数
          methodsMain.updateSchema([
            {
              dataIndex: 'correlationModel',
              fieldProps: {
                params: modelGroup.value.masterModel,
              },
            },
          ]);

          methodsMain.setData({ correlationModel: modelGroup.value.children });

          queryConditionStoredData.value = configData.queryCondition;
          let queryStr = '';
          if (configData.queryResult) {
            queryStr = JSON.stringify(
              JSON.parse(configData.queryResult).map(item => {
                const temp = { ...item };
                if (item.valueType) {
                  temp['fieldType'] = item.valueType;
                }
                return temp;
              }),
            );
          }
          queryResultStoredData.value = queryStr;
          hiddenConditionStoredData.value = configData.hiddenQueryCondition;
          methodsMain.setData({ queryPermissions: configData.permissionDesc });
          queryPermissionsVal.value = configData.permissionDesc;
        }
      }
      fetchData();
    };

    onBeforeMount(() => {
      if (typeof config_eid !== 'undefined' && config_eid !== '') {
        queryCommonQueryConfig(config_eid);
      }
    });

    // 注册自定义组件
    useComponentRegister('ModelSelector', ModelSelector);
    // 基本信息配置
    const schemasMain: {
      dataIndex?: string;
      title?: string;
      locale?: string;
      valueType?: string;
      width?: string;
      fieldProps?: unknown;
      formItemProps?: unknown;
    }[] = reactive([
      // todo 具体类型
      {
        dataIndex: 'name',
        title: t('queryConfiguration.configCreate.form.name'),
        locale: 'queryConfiguration.configCreate.form.name',
        valueType: 'Input',
        width: '25%',
        fieldProps: {
          // placeholder: t('permission.common.inputPlaceholder'),
          disabled: _.disabled,
        },
        formItemProps: {
          // labelCol: { span: 8 },
          // wrapperCol: { span: 18 },
          rules: [
            {
              pattern: '^([\\s\\S]{0,25})?$',
              message: t('queryConfiguration.configCreate.form.nameTipLength'),
              locale: 'queryConfiguration.configCreate.form.nameTipLength',
              trigger: 'change',
            },
            {
              message: t('queryConfiguration.configCreate.form.nameTip'),
              locale: 'queryConfiguration.configCreate.form.nameTip',
              pattern: '^\\s*(\\S+\\s*)+$',
              required: true,
              trigger: 'change',
            },
          ],
        },
      },
      {
        dataIndex: 'masterModel',
        title: t('queryConfiguration.configCreate.form.masterModel'),
        locale: 'queryConfiguration.configCreate.form.masterModel',
        valueType: 'Select',
        width: '25%',
        fieldProps: {
          // placeholder: t('permission.common.selectPlaceholder'),
          notFoundContent: null,
          open: false,
          disabled: _.disabled,
          showSearch: false,
        },
        formItemProps: {
          // labelCol: { span: 24, style: { width: '160px' } },
          // wrapperCol: { span: 18 },
          rules: [
            {
              required: true,
              pattern: /^\s*(\S+\s*)+$/,
              message: t('queryConfiguration.configCreate.form.permissionSubType.warningTip'),
              locale: 'queryConfiguration.configCreate.form.permissionSubType.warningTip',
              trigger: ['change'],
            },
          ],
        },
      },
      {
        dataIndex: 'correlationModel',
        title: t('queryConfiguration.configCreate.form.correlationModel'),
        locale: 'queryConfiguration.configCreate.form.correlationModel',
        valueType: 'ModelSelector',
        width: '25%',
        fieldProps: {
          placeholder: 'permission.common.selectPlaceholder',
          disabled: _.disabled,
          showSearch: false,
          params: {
            // value: 'P_MSG_GROUP',
            value: '', // 默认传入的参数
          },
          onChange: dataList => {
            modelGroup.value.children = dataList;
          },
        },
        formItemProps: {
          // labelCol: { span: 24, style: { width: '160px' } },
          // wrapperCol: { span: 18 },
        },
      },
      {
        dataIndex: 'queryPermissions',
        title: t('queryConfiguration.configCreate.form.queryPermissions'),
        locale: 'queryConfiguration.configCreate.form.queryPermissions',
        valueType: 'Input',
        width: '25%',
        slot: 'queryPermissions',
        formItemProps: {
          // labelCol: { span: 8 },
          // wrapperCol: { span: 21 },
          hidden: !config_eid,
          // rules: [{ required: true, pattern: /^\s*(\S+\s*)+$/, message: '请选择授权客体' }],
        },
        fieldProps: {
          // placeholder: t('permission.common.selectPlaceholder'),
          mode: 'multiple',
          showSearch: false,
          options: [],
          notFoundContent: null,
          labelInValue: true,
          open: false,
          class: 'permission-pllicy-select-sub',
          // maxTagTextLength: 3,
          // maxTagCount: 3,
          disabled: _.disabled,
        },
      },
    ]);
    const baseCheckEvent = () => {
      if (config_eid) {
        SearchAuthModelRef.value?.show({
          EID: config_eid,
          ENAME: methodsMain.getData().name,
        });
      }
    };
    const [formRef, props, methodsMain] = useForm(
      {
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
                showResetButton: false,
                showSubmitButton: false,
                showAdvancedButton: false,
                showActionButtonGroup: false,
              },
              autoSubmitOnEnter: true,
              column: 4,
              title: ' ',
              schemas: schemasMain,
              //   initialValue: {这里设置查询条件初始值},
            };
            methodsMain?.setProps(_props, props);
            methodsMain.updateSchema(
              [
                {
                  dataIndex: 'masterModel',
                  fieldProps: {
                    onDropdownVisibleChange: open => {
                      const options =
                        methodsMain.getFormSchemas('masterModel')[0]?.fieldProps?.options || [];
                      open && MasterModelSelectRef.value?.show(options[0]);
                    },
                  },
                },
                {
                  dataIndex: 'queryPermissions',
                  fieldProps: {
                    onDropdownVisibleChange: open => {
                      const options =
                        methodsMain.getFormSchemas('queryPermissions')[0]?.fieldProps?.options ||
                        [];
                      open && SearchAuthModelRef.value?.show(options[0], queryPermissions.value);
                    },
                  },
                },
              ],
              props,
            );
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );
    const queryPermissionsVal = ref();
    //保存按钮实现
    const savePermissionData = async () => {
      const getData = methodsMain.getData();
      let refModelCode = '';
      const queryDisplaySearchFieldsList =
        conditionsComponentRef.value.queryDisplaySearchFieldsList;
      const queryComponentRefs = queryComponentRef.value.queryDisplaySearchFieldsList;
      const hiddenRulesQueryRefs = hiddenRulesQueryRef.value.attrValidateForm;
      const queryCondition = [];
      const queryResult = [];
      const refModelDescs = [];
      const attrValidateForm = [];
      refModelCode = JSON.stringify(getData.correlationModel);
      refModelDescs.join(';');
      queryDisplaySearchFieldsList.forEach(item => {
        queryCondition.push({
          id: item.key,
          tableDesc: item.tableDesc,
          tableName: item.belongTable,
          fieldDesc: item.fieldDesc,
          fieldName: item.fieldName,
          fieldType: item.fieldType,
          fieldDefaultValue: item.fieldDefaultValue,
          operator: item.operator,
          dictList: item.dictList,
        });
      });
      queryComponentRefs.forEach(item => {
        queryResult.push({
          tableDesc: item.tableDesc,
          tableName: item.belongTable,
          fieldDesc: item.fieldDesc,
          fieldName: item.fieldName,
          valueType: item.fieldType,
          fieldDefaultValue: item.fieldDefaultValue,
          dictList: item.dictList,
        });
      });
      hiddenRulesQueryRefs.custom.forEach(item => {
        attrValidateForm.push({
          splicer: item.operator,
          tableDesc: item.modelKey,
          tableName: item.model,
          fieldDesc: item.FieldKey,
          fieldName: item.field,
          operator: item.condition,
          // fieldType: '',
          conditionType: 'hidden',
          actualValueDesc: item.val,
          id: item.key,
        });
      });

      // if (loading.value) return;
      formRef.value?.validate().then(async () => {
        const addInterface = '/api/commonquery/commonQuery/manage/save';
        const updateInterface = '/api/commonquery/commonQuery/manage/update';
        let apiInterface = addInterface;
        let params = {
          EID: '',
          ENAME: getData.name,
          MAJOR_MODEL_CODE: getData.masterModel.value,
          MAJOR_MODEL_DESC: getData.masterModel.label,
          REF_MODEL_CODE: refModelCode,
          QUERY_CONDITION: queryCondition,
          QUERY_RESULT: queryResult,
          TYPE: '0',
          REF_MODEL_DESC: refModelDescs.toString(),
          HIDDEN_QUERY_CONDITION: attrValidateForm,
          companyId: getInfo(ICP_CONFIG).companyId,
        };
        if (typeof config_eid !== 'undefined' && config_eid != '') {
          apiInterface = updateInterface;
          params.EID = config_eid;
        }
        const result = await useHttp({
          url: apiInterface,
          method: 'post',
          params,
        });
        if (result.code == 200) {
          message.success(result.msg);
          // TODO: 去掉关闭页签
          // if (typeof config_eid !== 'undefined' && config_eid != '' && !disabledBoolean.value) {
          //   close(
          //     '/platform/queryConfiguration/GeneralQueryConfig/GeneralQueryConfigEdit',
          //     '/platform/QueryConfiguration/GeneralQueryConfig/GeneralQueryConfigIndex',
          //   );
          // } else {
          //   close(
          //     '/platform/queryConfiguration/GeneralQueryConfig/GeneralQueryConfigCreate',
          //     '/platform/QueryConfiguration/GeneralQueryConfig/GeneralQueryConfigIndex',
          //   );
          // }
          // refresh('/platform/QueryConfiguration/GeneralQueryConfig/GeneralQueryConfigIndex');
        } else {
          message.warning(result.msg);
        }
      });
    };
    //关闭按钮实现
    // const closePage = () => {
    //   close(
    //     '/platform/queryConfiguration/GeneralQueryConfig/GeneralQueryConfigView',
    //     '/platform/QueryConfiguration/GeneralQueryConfig/GeneralQueryConfigIndex',
    //   );
    // };
    // // 取消
    // const cancelPage = () => {
    //   if (typeof config_eid !== 'undefined' && config_eid != '' && !disabledBoolean.value) {
    //     close(
    //       '/platform/queryConfiguration/GeneralQueryConfig/GeneralQueryConfigEdit',
    //       '/platform/QueryConfiguration/GeneralQueryConfig/GeneralQueryConfigIndex',
    //     );
    //   } else {
    //     close(
    //       '/platform/queryConfiguration/GeneralQueryConfig/GeneralQueryConfigCreate',
    //       '/platform/QueryConfiguration/GeneralQueryConfig/GeneralQueryConfigIndex',
    //     );
    //   }
    // };
    // TODO: 重写关闭和取消按钮
    const closePage = () => {
      router.push('/GeneralQueryConfig');
    };
    const cancelPage = () => {
      router.push('/GeneralQueryConfig');
    };
    const permissionSubTypeFunSuccess = data => {
      methodsMain.setData({ masterModel: data });
      modelGroup.value.masterModel = data;
      modelGroup.value.loaded = false;
      queryPermissions.value = [];
      methodsMain.setData({
        queryPermissions: [],
      });
      // 切换主模型更新关联模型参数
      methodsMain.updateSchema([
        {
          dataIndex: 'correlationModel',
          fieldProps: {
            params: data,
          },
        },
      ]);
    };
    // 查询权限保存
    const searchAuthModelFunSuccess = () => {
      if (typeof config_eid !== 'undefined' && config_eid !== '') {
        queryCommonQueryConfig(config_eid);
      }
    };

    return {
      t,
      savePermissionData,
      closePage,
      cancelPage,
      loading,
      queryPermissionsVal,
      _,
      formRef,
      props,
      MasterModelSelectRef,
      SearchAuthModelRef,
      permissionSubTypeFunSuccess,
      searchAuthModelFunSuccess,
      queryComponentRef,
      conditionsComponentRef,
      hiddenRulesQueryRef,
      modelGroup,
      queryCommonQueryConfig,
      queryConditionStoredData,
      queryResultStoredData,
      hiddenConditionStoredData,
      dataPerInfo,
      baseCheckEvent,
    };
  },
});
</script>

<style lang="less" scoped>
@import '@/theme/default/variables.less';

// .content {
//   flex: 1;
//   height: 100% !important;
//   margin-bottom: 40px;
.query-config-component {
  margin: 24px 0;
  &__conditions {
    margin-bottom: 24px;
  }
  &__bottom {
    margin-bottom: 50px;
  }
}
// }
.top {
  background: #fff;
  padding: 20px 24px;
  margin-top: 0;
  border-radius: 8px;
}
.bottom {
  margin-top: 24px;
  background: #fff;
  border-radius: 8px;
}
.exclamation-icon {
  color: @normal-color;
  margin-left: 4px;
  font-size: 16px;
  &:hover {
    color: @info-color;
  }
}
.permission-pllicy-btn {
  text-align: right;
  padding-right: 15px;
  position: fixed;
  background: #fff;
  border: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  box-shadow: 0px -9px 16px 0px rgba(74, 85, 107, 0.07);
  padding: 18px 20px 18px 0;
  button {
    margin-left: 24px;
  }
}
:deep(.permission-pllicy-select-sub .ant-select-selector .ant-select-selection-overflow) {
  flex-wrap: nowrap !important;
  overflow: hidden !important;
}
:deep(.permission-subject-select) {
  .ant-select-arrow {
    display: none;
  }
}
</style>
