<template>
  <div class="main-content main-content-padding" id="SimpleQuery">
    <!-- //查询表单 -->
    <h-card class="margin-bottom list-query-form">
      <h-b-form
        ref="formRef"
        name="use"
        v-bind="props"
        :submitter="{
          isQuery: true,
          searchConfig: {
            resetText: t('platform.common.reset'),
            submitText: t('queryConfiguration.common.search'),
          },
        }"
        id="SimpleQuery-queryForm"
        @finish="onFinish"
        @reset="onReset"
      ></h-b-form>
    </h-card>
    <!-- 表格，操作按钮和按钮组插槽实现 -->
    <h-card class="list-table">
      <h-b-pro-table
        v-if="inited"
        id="SimpleQuery-queryTable"
        v-bind="tableProps"
        rowKey="EID"
        :needRowIndex="false"
        :show-size="false"
        :animateRows="false"
        :show-export="false"
        :title="t('queryConfiguration.simpleQuery.tableTitle')"
        :row-selection="{
          type: 'checkbox',
          memory: true,
          clickSelectTrigger: 'row',
          unSelectable: true,
        }"
        ref="gridRef"
        :scroll="{
          extra: 24,
          y: true,
        }"
      >
        <!-- 按钮组插槽 -->
        <template #headerContent>
          <h-b-button-group v-bind="menuProps" ref="menuRef" id="SimpleQuery-buttonGroup" />
        </template>
        <template #SS_KEYWORD_MATCH="{ record }">
          <h-tooltip placement="top" overlayClassName="simplyQuery-listTable-keyword-tooltip">
            <template #title>
              <!-- 目前同意提示框的文本为红色的样式 -->
              <div v-html="record.SS_KEYWORD_MATCH"></div>
            </template>
            <div class="table-cell-keyword-text" v-html="record.SS_KEYWORD_MATCH"></div>
          </h-tooltip>
        </template>
        <!-- 行内操作按钮 -->
        <template #action="{}">
          <h-b-button-group
            v-bind="menuPropsTable"
            ref="menuRefTable"
            id="SimpleQuery-buttonGroup-inline"
          />
        </template>
      </h-b-pro-table>
    </h-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, ref, watchEffect, reactive, watch } from 'vue';
import { useProTable, useForm, useButtonGroup } from '@crami/bui-platform';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { message, HModal } from '@crami/ui';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import router from '@/router';
import { Http, useHttp } from '@crami/http';
import { useI18n } from '@crami/locale';
// import type { IBFormSchema } from '@crami/bui-types';
import { useStore } from 'vuex';
import { SET_TRIGGER, SET_PARAMS } from '@/store/modules/simplyQuery/index';

export default defineComponent({
  name: 'SimpleQuery',
  setup() {
    // 多语言
    const { t } = useI18n();
    const store = useStore();

    //参数设置
    const schemasParams = reactive([
      {
        dataIndex: 'QUERYSCOPE',
        title: t('queryConfiguration.common.selectLabel'),
        locale: 'queryConfiguration.common.selectLabel',
        valueType: 'Select',
        width: '25%',
        formItemProps: {
          rules: [
            {
              required: true,
              message: t('queryConfiguration.common.selectPlaceholder'),
              locale: 'queryConfiguration.common.selectPlaceholder',
            },
          ],
        },
        fieldProps: {
          // placeholder: t('queryConfiguration.common.selectPlaceholder'),
          mode: 'multiple',
          options: [],
          filterOption: (text: string, option: any) => option.label.indexOf(text) >= 0,
          maxTagCount: 3,
          allowClear: true,
        },
      },
      {
        dataIndex: 'KEYWORD',
        title: t('queryConfiguration.common.inputLabel'),
        locale: 'queryConfiguration.common.inputLabel',
        valueType: 'Input',
        width: '25%',
        formItemProps: {
          // rules: [
          //   {
          //     required: true,
          //     message: t('queryConfiguration.common.inputPlaceholder'),
          //     locale: 'queryConfiguration.common.inputPlaceholder',
          //   },
          // ],
          help: t('queryConfiguration.common.keywordTip'),
        },
        fieldProps: {
          // placeholder: t('queryConfiguration.common.inputPlaceholder'),
        },
      },
    ]);
    const commonParams = computed(() => {
      return {
        ...getInfo(ICP_CONFIG),
        listViewName: 'ICPX_ES_SIMPLEQUERY_LISTVIEW',
        menuName: 'ICPX_ES_SIMPLEQUERY_MENU',
      };
    }); //按钮组

    const options = ref();
    const selectValue = ref();
    const keyword = ref();
    const formModel = ref();
    const isEnableEs = ref(0);

    const inited = ref(false);

    const getEnableEs = () => {
      useHttp({
        method: 'get',
        url: '/bizrule/bizRule/getByRuleID/SIMPLE_QUERY_ENABLE_ES',
        params: undefined,
      })
        .then(res => {
          if (res.code === 200) {
            let ruleValue = res.data.ruleValue;
            if (ruleValue === 'true') {
              isEnableEs.value = 1;
            } else if (ruleValue === 'false') {
              isEnableEs.value = 0;
            }
          }
        })
        .finally(() => {
          inited.value = true;
          getObjType();
        });
    };

    const getObjType = async () => {
      const result = await Http.post({
        url: '/api/index/fastSearch/queryScope',
        params: {
          companyId: commonParams.value?.companyId,
          searchValue: '',
          isEnableEs: isEnableEs.value,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      const { data, code } = result;
      if (code == 200) {
        schemasParams[0].fieldProps.options = data.data.map(item => {
          return {
            label: item.ENAME,
            value: item.EID,
          };
        });
      } else {
        message.error(result.msg);
      }
    };

    const [formRef, props, methods] = useForm(
      {
        saveApi: {
          url: '/api/index/fastSearch/search',
          method: 'post',
          type: 'json',
        },
        beforeSetData: (type, props) => {
          if (type === 'config') {
            const _props: any = {
              submitter: {
                isQuery: true,
              },
              column: 2,
              schemas: schemasParams,
            };

            methods?.setProps(_props, props);
          }
          return props;
        },
        immediate: true,
      },
      '',
      '',
      {},
    );

    const onFinish = () => {
      // 处理data数据
      const formData = formRef.value.getFilterData();
      search(formData);
    };

    const [gridRef, tableProps, tableMethods] = useProTable({
      // 表头数据
      configApi: {
        url: commonApi().system.getData.url,
        method: commonApi().system.getData.method,
        params: {
          type: 'gridTitle',
          data: {
            ...commonApi().system.getData.params,
            viewName: commonParams.value?.listViewName,
          },
        },
      },
      // 数据接口
      dataSourceApi: {
        url: '/api/index/fastSearch/search',
        method: 'post',
        studioParams: {
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          connect: commonParams.value?.connect,
          userId: commonParams.value?.user_id,
          timeZone: commonParams.value?.TIME_ZONE,
        },
        // 这里监听返回的接口数据
        afterRequest: data => {
          if (!data || data.code !== 200) {
            message.error(data.msg);
          }
        },
      },
      beforeRequest: (type, params: any) => {
        if (type == 'column') {
          if (params && params.data && typeof params.data == 'object') {
            params.data = JSON.stringify(params.data);
          }
        }
        return {
          ...params,
          filter: params.filter || [],
        };
      },
      afterRequest: (type, params) => {
        if (type === 'column') {
          let columns = params.columns;
          let watcher = watch(
            inited,
            val => {
              if (val) {
                // 异步执行确保能获取到watcher
                Promise.resolve().then(() => {
                  watcher && watcher();
                });

                // 根据isEnableEs值确定是否显示关键词匹配内容列
                if (isEnableEs.value === 1) return;

                // 获取关键词匹配内容列
                let index = columns.findIndex(column => column.dataIndex === 'SS_KEYWORD_MATCH');
                if (index > -1) {
                  let column = columns.splice(index, 1)[0];

                  // 调整其它列宽度
                  if (column.width && column.width > 0) {
                    let validIndexList = columns.reduce((list, column, index) => {
                      if (column.width && column.width > 0) {
                        list.push(index);
                        return list;
                      }
                    }, []);
                    let widthUnit = column.width / validIndexList.length;
                    validIndexList.forEach(index => {
                      columns[index].width += widthUnit;
                    });
                  }
                }

                tableMethods.setColumns(columns);
              }
            },
            { immediate: true },
          );
        }
      },
      // 必须设置2个筛选条件才能查询列表
      initialLoad: false,
      operation: {
        dataIndex: 'action',
        title: t('queryConfiguration.common.operate'),
        width: 105,
        show: true,
        customSlot: 'action',
        fixed: 'right',
      },
      columnExtra: {
        SS_KEYWORD_MATCH: {
          customSlot: 'SS_KEYWORD_MATCH',
        },
      },
    });

    const search = async (params: any) => {
      const allParam = {
        filter: params,
        isEnableEs: isEnableEs.value,
      };
      tableMethods.query(allParam, true);
    };
    const [menuRef, menuProps, { getRowMenu }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'default',
      pageName: 'SimpleQuery',
      dataSourceApi: {
        url: commonApi().studioCache.getMetaInfo.url,
        params: {
          ...commonApi().studioCache.getMetaInfo.params,
          ...{
            type: 'menuv2',
            name: commonParams.value?.menuName,
          },
        },
        method: 'post',
      },
    });
    const [menuRefTable, menuPropsTable, { load }] = useButtonGroup({
      checkPermission: false,
      sortRule: 'computedByNumber',
      computedByNumber: 3,
      pageName: 'SimpleQuery',
      items: [],
      moreItem: {
        trigger: ['click'],
      },
    });

    const newJsFun = (event: any) => {
      if (event.result?.code == 200) {
        message.success(event.result.msg);
        RefreshTable();
        HModal.destroyAll();
      } else {
        if (undefined == event?.result) {
          //TODO：后期可能会有处理
        } else {
          message.warning(event.result.msg);
        }
      }
    };
    //处理行内操作按钮
    watchEffect(async () => {
      const rowData = getRowMenu('link');
      load(rowData);
    });
    const RefreshTable = () => {
      const formFilter = formRef.value?.getFilterData();
      search(formFilter);
    };

    const onReset = () => {
      selectValue.value = [];
      keyword.value = '';
      // search([]);
    };

    // 查看
    const check = () => {
      const selectData = tableMethods.getSelectRows();
      router.push({
        path: '/plm/containManagement/bomCheck/bomCheck',
        query: {
          eid: selectData[0].EID,
        },
      });
    };

    // 查看模型功能
    const viewModal = async ({ EID }) => {
      let row = EID[0];
      let res = await useHttp({
        method: 'post',
        url: '/api/index/fastSearch/detail',
        params: {
          lang: commonParams.value?.lang,
          companyId: commonParams.value?.companyId,
          connect: commonParams.value?.connect,
          userId: commonParams.value?.user_id,
          modelName: row.SS_OBJTYPE_CODE,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      });
      if (res.code === 200) {
        router.push({
          path: res.msg,
          query: {
            objectEID: row.EID,
          },
        });
      } else {
        message.error(res.msg);
      }
    };

    // TODO:没有导航数据，暂时去掉监听
    // 监听导航搜索值
    // const triggerSearch = computed(() => store.state.simplyQuery.triggerSearch);
    // watch(
    //   // 不能直接监听state数据，不然会触发2次监听
    //   // () => store.state.simplyQuery.triggerSearch,
    //   triggerSearch,
    //   val => {
    //     if (val) {
    //       const searchForm = store.state.simplyQuery.params;
    //       // 延迟一会，不然table不会发送请求
    //       setTimeout(() => {
    //         methods.setData({
    //           QUERYSCOPE: searchForm.queryScope,
    //           KEYWORD: searchForm.keyword,
    //         });
    //         onFinish();

    //         // 重置数据
    //         store.commit(`simplyQuery/${SET_TRIGGER}`, false);
    //         store.commit(`simplyQuery/${SET_PARAMS}`, undefined);
    //       }, 300);
    //     }
    //   },
    //   { immediate: true },
    // );

    getEnableEs();

    return {
      t,
      inited,
      onFinish,
      onReset,
      options,
      selectValue,
      keyword,
      formModel,
      formRef,
      props,
      methods,
      menuRef,
      menuProps,
      menuRefTable,
      menuPropsTable,
      newJsFun,
      RefreshTable,
      gridRef,
      tableProps,
      commonParams,
      check,
      schemasParams,
      viewModal,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.surely-table-expanded-row) {
  .surely-table-cell {
    background-color: #fff !important;
  }

  .surely-table-cell-inner {
    .surely-table-cell-content {
      padding: 15px 16px;
    }
  }
}

:deep(.table-cell-keyword-text) p {
  margin-bottom: 0;
}
</style>

<style lang="less">
.simplyQuery-listTable-keyword-tooltip {
  max-width: 560px;
  min-width: 120px;
  .ant-tooltip-content {
    // width: auto;
    // max-width: 560px;
    // min-width: 120px;

    p {
      margin-bottom: 0;
    }
  }
}
</style>
