<template>
  <div class="query-component">
    <!-- 传入的title -->
    <div class="query-component__title">{{ t(componentTitle) }}</div>
    <h-divider></h-divider>
    <div class="query-component-content">
      <!-- 左侧全部字段 -->
      <div class="query-component-content-all">
        <h-form layout="vertical" ref="formRef" class="query-component-content-all-form">
          <h-form-item :label="t('queryConfiguration.configCreate.queryConditions.allFields')">
            <h-input
              :placeholder="t('queryConfiguration.configCreate.queryConditions.placeholder')"
              class="query-component-content-all-form__input"
              v-model:value="allFieldsSearch"
              :allowClear="true"
            ></h-input>
          </h-form-item>
        </h-form>
        <div class="query-component-content-all-table">
          <h-b-table
            v-bind="tableProps"
            ref="gridRef"
            :data-source="showFieldsList"
            :columns="allFieldsColumns"
            :pagination="false"
            :showExport="false"
            size="small"
            :scroll="{ y: 200 }"
            :row-class-name="rowClassName"
            :customRow="allFieldsRowClick"
            rowKey="key"
            :row-selection="{
              type: 'checkbox',
              memory: true,
              clickSelectTrigger: 'row',
              unSelectable: true,
            }"
          ></h-b-table>
        </div>
      </div>
      <div>
        <h-button
          type="dashed"
          shape="circle"
          style="margin-left: -3px; margin-top: 32px"
          @click="transfer2Right"
        >
          <h-icon name="hoteam-arrow-right" width="19px" height="19px"></h-icon>
        </h-button>
      </div>
      <!-- 右侧所选查询字段 -->
      <div class="query-component-content-selected">
        <h-form layout="vertical" ref="formRef" class="query-component-content-selected-form">
          <h-form-item :label="t(`${searchLable}`)">
            <h-input
              :placeholder="t('queryConfiguration.configCreate.queryConditions.placeholder')"
              class="query-component-content-selected-form__input"
              v-model:value="queryDisplayField"
              :allowClear="true"
            ></h-input>
          </h-form-item>
        </h-form>
        <div class="query-component-content-selected-table">
          <h-table
            :data-source="queryDisplaySearchFieldsList"
            :columns="queryDisplayFieldsColumns"
            :pagination="false"
            size="small"
            :scroll="{ y: 200 }"
            :row-class-name="rowClassName"
          >
            <template #bodyCell="{ column, index, record }">
              <template v-if="column.dataIndex === 'fieldDefaultValue'">
                <!-- :selfUpdate="true" -->
                <h-input
                  v-model:value="record.fieldDefaultValue"
                  :title="record.fieldDefaultValue"
                  :placeholder="
                    t('queryConfiguration.configCreate.queryConditions.placeholderName')
                  "
                  :bordered="false"
                  :disabled="queryDisable"
                  @change="fieldChange"
                />
              </template>
              <template v-else-if="column.dataIndex === 'operator'">
                <h-select
                  v-model:value="record.operator"
                  :optionLabelProp="null"
                  :showSearch="false"
                  :bordered="false"
                  :disabled="queryDisable"
                >
                  <h-select-option value="=">=</h-select-option>
                  <h-select-option value="!=">!=</h-select-option>
                  <h-select-option value=">">></h-select-option>
                  <h-select-option value=">=">>=</h-select-option>
                  <h-select-option value="<">&lt;</h-select-option>
                  <h-select-option value="<=">&lt;=</h-select-option>
                  <h-select-option value="like">like</h-select-option>
                </h-select>
              </template>
              <template v-else-if="column.dataIndex === 'operation' && !queryDisable">
                <h-popconfirm
                  :title="t('queryConfiguration.configCreate.queryConditions.deleteConfirm')"
                  placement="topLeft"
                  @confirm="deleteItem(record.key)"
                >
                  <a>{{ t('queryConfiguration.configCreate.queryConditions.delete') }}</a>
                </h-popconfirm>
                <!-- <span @click="deleteItem(record.key)">
                  {{ t('queryConfiguration.configCreate.queryConditions.delete') }}
                </span> -->
              </template>
            </template>
          </h-table>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, computed, watch, onBeforeMount } from 'vue';
import { getUuid } from '@remote/icpx-platform/utils';
/* import { getUuid } from '@/utils/uuid'; */
import { useI18n } from '@crami/locale';
import { useHttp } from '@crami/http';
import { cloneDeep } from 'lodash-es';
import { useTable } from '@crami/bui-platform';

export default defineComponent({
  name: 'QueryComponent',
  props: {
    title: {
      type: String,
      default: '',
    },
    searchLable: {
      type: String,
      default: '',
    },
    action: {
      type: String,
      default: '',
    },
    queryDisable: {
      type: Boolean,
    },
    modelGroup: {
      type: Object,
    },
    storedData: {
      type: String,
    },
  },
  setup(props) {
    const { t, locale } = useI18n();
    const { action, queryDisable, title: componentTitle } = props;
    // const action=toRef(props)
    const [gridRef, tableProps, tableMethods] = useTable({});
    // 行样式
    const rowClassName = index => {
      return index % 2 === 1 ? 'table-striped' : null;
    };
    // 全部字段输入框的值
    const allFieldsSearch = ref('');
    // 全部字段的列表显示的数据   todo全部加类型
    const allSearchFieldsList = ref([]);

    const showFieldsList = ref([]);
    // 查询显示字段输入框的值
    const queryDisplayField = ref('');
    // 查询显示字段字段的列表
    const queryDisplayFieldsList = ref([]);
    // 查询显示字段的列表显示的数据
    const queryDisplaySearchFieldsList = ref([]);
    // const storedData = props.storedData; // toRef(props, 'storedData');

    // 全部字段表格的columns
    const allFieldsColumns = ref<Array<any>>([
      {
        dataIndex: 'tableDesc',
        title: t('queryConfiguration.configCreate.queryConditions.tableColumns.objectModel'),
        align: 'left',
      },
      {
        dataIndex: 'fieldDesc',
        title: t('queryConfiguration.configCreate.queryConditions.tableColumns.fieldName'),
        align: 'left',
      },
      {
        dataIndex: 'fieldName',
        title: t('queryConfiguration.configCreate.queryConditions.tableColumns.field'),
        align: 'left',
      },
    ]);

    const queryModelFields = (modelGroup, dealFields, needSet) => {
      let params = {
        tableCode: modelGroup.masterModel?.value,
        children: modelGroup?.children,
      };
      useHttp({
        url: '/api/commonquery/commonQuery/manage/getFieldsByModels',
        method: 'post',
        params: {
          ...params,
        },
      }).then(res => {
        dealFields(res, modelGroup.masterModel?.value, needSet);
        console.log(res);
      });
    };

    // 获字段列表
    function fetchAllFields(modelGroup) {
      let params = {
        tableCode: modelGroup.masterModel?.value,
        children: modelGroup?.children,
      };
      async function fetchData() {
        const result = await useHttp({
          url: '/api/commonquery/commonQuery/manage/getFieldsByModels',
          method: 'post',
          params: {
            ...params,
          },
        });

        if (result.code == 200 && result.data) {
          allSearchFieldsList.value.length = 0;
          let tempFieldList = [];
          for (let fieldItem of result.data) {
            tempFieldList.push({
              key: fieldItem.belongTable + '.' + fieldItem.fieldName,
              ...fieldItem,
            });
          }
          allSearchFieldsList.value = tempFieldList;
          showFieldsList.value = tempFieldList;

          console.log('fetchAllFields length:' + allSearchFieldsList.value.length);
        }
      }
      if (modelGroup.masterModel != null) {
        fetchData();
      }
    }

    //fetchAllFields(props.modelGroup);
    let tempArray = cloneDeep(allFieldsColumns.value);
    tempArray[0].rowDrag = true;
    const queryColumns = ref([
      ...tempArray,
      {
        dataIndex: 'fieldDefaultValue',
        title: t('queryConfiguration.configCreate.queryConditions.tableColumns.displayName'),
        align: 'left',
        key: 'fieldDefaultValue',
      },
      {
        dataIndex: 'operation',
        title: t('queryConfiguration.configCreate.queryConditions.tableColumns.operation'),
        align: 'left',
        key: 'operation',
      },
    ]);
    watch(
      () => locale,
      () => {
        queryColumns.value = queryColumns.value.slice();
        conditionsColumns.value = conditionsColumns.value.slice();
      },
    );

    const travelChildren = (curNode, tempArray) => {
      if (
        typeof curNode.children !== 'undefined' &&
        curNode.children != null &&
        curNode.children.length > 0
      ) {
        curNode.children.forEach(element => {
          if (element.tableCode) {
            tempArray.push(element.tableCode);
          }
          travelChildren(element, tempArray);
        });
      }
    };

    const loadFields = (res, masterModel, needSetDefault) => {
      if (res.code == 200 && res.data) {
        allSearchFieldsList.value.length = 0;
        let tempFieldList = [];
        for (let fieldItem of res.data) {
          tempFieldList.push({
            key: fieldItem.belongTable + '.' + fieldItem.fieldName,
            ...fieldItem,
          });
        }
        allSearchFieldsList.value = tempFieldList;
        showFieldsList.value = tempFieldList;
      }

      if (needSetDefault) {
        showFieldsList.value.forEach(item => {
          if (
            item.belongTable === masterModel &&
            (['名称', '编码', '创建人', '所属人', '创建时间'].includes(item.fieldDesc) ||
              ['EID', 'ECODE', 'ENAME'].includes(item.fieldName))
          ) {
            let list = queryDisplayFieldsList.value || [];
            let exist = false;
            for (let i = 0; i < list.length; i++) {
              let litem = list[i];
              if (litem.belongTable == masterModel && litem.fieldName == item.fieldName) {
                exist = true;
                break;
              }
            }
            if (exist) {
              return;
            }
            const newData = {
              ...item,
              key: getUuid(5, 5),
              fieldDefaultValue: item.fieldDesc || item.fieldName,
              operator: '=',
            };

            list.push(newData);
            queryDisplayFieldsList.value = [].concat(list);
            queryDisplaySearchFieldsList.value = [].concat(list);
          }
        });
      }
    };

    watch(
      () => ({ ...props.modelGroup }),
      (newVal, oldVal) => {
        console.log('queryComponent newVal:' + JSON.stringify(newVal));
        console.log('queryComponent oldVal:' + JSON.stringify(oldVal));
        console.log('queryComponent modelGroup:' + JSON.stringify(props.modelGroup));
        let needSetDefault =
          newVal.masterModel?.value !== oldVal.masterModel?.value &&
          props.modelGroup?.loaded != true &&
          action === 'query';
        queryModelFields(props.modelGroup, loadFields, needSetDefault);
        let tempArray = [];
        if (typeof newVal.masterModel !== 'undefined') {
          tempArray.push(newVal.masterModel.value);
        }
        travelChildren(newVal, tempArray);
        queryDisplayFieldsList.value = queryDisplayFieldsList.value.filter(item => {
          if (
            tempArray.includes(item.tableCode) ||
            tempArray.includes(item.tableName) ||
            tempArray.includes(item.belongTable)
          ) {
            return item;
          }
        });

        queryDisplaySearchFieldsList.value = queryDisplayFieldsList.value;
        /*if (newVal?.masterModel?.value !== oldVal?.masterModel?.value) {
          if (typeof oldVal.masterModel !== 'undefined' && oldVal.masterModel != null) {
            queryDisplayFieldsList.value = [];
            queryDisplaySearchFieldsList.value = [];
          }
        } */
      },
    );

    watch(
      () => props.storedData,
      (newVal, oldVal) => {
        console.log('queryComponent storedData newVal:' + JSON.stringify(newVal));
        console.log('queryComponent storedData oldVal:' + JSON.stringify(oldVal));
        if (typeof newVal !== 'undefined' && newVal.length > 0) {
          let storedDataJson = JSON.parse(newVal);
          let tempArray = [];
          storedDataJson.forEach((element, index) => {
            element.key = element.id;
            if (!element.key) element.key = index;
            if (element.tableName) element.belongTable = element.tableName;

            tempArray.push(element);
          });
          queryDisplaySearchFieldsList.value = tempArray;
          queryDisplayFieldsList.value = tempArray;
        }
      },
    );

    const conditionsColumns = ref([
      ...tempArray,
      {
        dataIndex: 'fieldDefaultValue',
        title: t('queryConfiguration.configCreate.queryConditions.tableColumns.displayName'),
        align: 'left',
        key: 'fieldDefaultValue',
        ellipsis: 'true',
      },
      {
        dataIndex: 'operator',
        title: t('queryConfiguration.configCreate.queryConditions.tableColumns.conditions'),
        align: 'left',
        key: 'operator',
      },
      {
        dataIndex: 'operation',
        title: t('queryConfiguration.configCreate.queryConditions.tableColumns.operation'),
        align: 'left',
        key: 'operation',
      },
    ]);

    // 查询显示字段字段表格的columns
    const queryDisplayFieldsColumns = computed(() => {
      return action === 'query' ? queryColumns.value : conditionsColumns.value;
    });
    const allFieldsRowClick = record => {
      return {
        onDblclick: () => {
          if (queryDisable) {
            return;
          }
          queryDisplayField.value = '';
          let list = queryDisplayFieldsList.value || [];
          let exist = false;
          if (action === 'query') {
            for (let i = 0; i < list.length; i++) {
              let lItem = list[i];
              if (
                lItem.belongTable === record.belongTable &&
                lItem.fieldName === record.fieldName
              ) {
                exist = true;
                break;
              }
            }
          }
          if (!exist) {
            const newData = {
              ...record,
              key: getUuid(5, 5),
              fieldDefaultValue: record.fieldDesc || record.fieldName,
              operator: '=',
            };
            list.push(newData);
            queryDisplayFieldsList.value = [].concat(list);
            queryDisplaySearchFieldsList.value = [].concat(list);
          }
        },
      };
    };
    const deleteItem = key => {
      // 所选择的所有字段的列表
      queryDisplayFieldsList.value = queryDisplayFieldsList.value.filter(item => item.key != key);
      queryDisplayFieldsList.value = [].concat(queryDisplayFieldsList.value);
      // [...queryDisplayFieldsList.value];
      // 所选择的并筛选过的字段的列表
      queryDisplaySearchFieldsList.value = queryDisplaySearchFieldsList.value.filter(
        item => item.key != key,
      );
      queryDisplaySearchFieldsList.value = [].concat(queryDisplaySearchFieldsList.value);
    };
    // 全部字段表格的筛选监听
    watch(allFieldsSearch, () => {
      console.log('allFieldsSearch:' + allFieldsSearch.value);
      showFieldsList.value = [];
      if (allFieldsSearch.value == '') {
        showFieldsList.value = [].concat(allSearchFieldsList.value);
      } else {
        let tempArray = allSearchFieldsList.value.filter(item => {
          if (
            item.fieldDesc.indexOf(allFieldsSearch.value) > -1 ||
            item.fieldName.indexOf(allFieldsSearch.value) > -1
          ) {
            return item;
          }
        });
        showFieldsList.value = [].concat(tempArray);
      }
    });
    // 查询显示字段和结果自断监听
    watch(queryDisplayField, val => {
      let list = queryDisplayFieldsList.value;
      console.log('list', list[0]);
      if (queryDisplayField.value == '') {
        queryDisplaySearchFieldsList.value = [].concat(queryDisplayFieldsList.value);
      } else {
        queryDisplaySearchFieldsList.value = list.filter(item => {
          // todo 此处需要添加类型判断===
          if (item.fieldDesc.indexOf(val) > -1 || item.fieldName.indexOf(val) > -1) {
            return true;
          } else {
            return false;
          }
        });
      }
    });
    const fieldChange = () => {
      queryDisplaySearchFieldsList.value = [].concat(queryDisplaySearchFieldsList.value);
    };
    onBeforeMount(() => {
      console.log('props storedData:' + props.storedData);
      if (typeof props.storedData !== 'undefined' && props.storedData.length > 0) {
        console.log('storedData:' + props.storedData);
        let storedDataJson = JSON.parse(props.storedData);
        storedDataJson.forEach(element => {
          element.key = element.id;
          if (!element.key) {
            element.key = getUuid(5, 5);
          }
          queryDisplaySearchFieldsList.value.push(element);
        });
      }
    });
    const transfer2Right = () => {
      if (queryDisable) {
        return;
      }
      let selectedRows = tableMethods.getSelectedRows();
      if (selectedRows.length > 0) {
        queryDisplayField.value = '';
        let list = queryDisplayFieldsList.value || [];
        selectedRows.forEach(item => {
          let exist = false;
          if (action === 'query') {
            for (let i = 0; i < list.length; i++) {
              let lItem = list[i];
              if (lItem.belongTable === item.belongTable && lItem.fieldName === item.fieldName) {
                exist = true;
                break;
              }
            }
          }
          if (!exist) {
            const newData = {
              ...item,
              key: getUuid(5, 5),
              fieldDefaultValue: item.fieldDesc || item.fieldName,
              operator: '=',
            };
            list.push(newData);
          }
        });
        queryDisplayFieldsList.value = [].concat(list);
        queryDisplaySearchFieldsList.value = [].concat(list);
        tableMethods.resetSelectedRow();
      }
    };

    return {
      allFieldsSearch,
      queryDisplayField,
      allFieldsColumns,
      showFieldsList,
      allSearchFieldsList,
      queryDisplaySearchFieldsList,
      queryDisplayFieldsColumns,
      allFieldsRowClick,
      deleteItem,
      rowClassName,
      componentTitle,
      t,
      fetchAllFields,
      fieldChange,
      queryModelFields,
      gridRef,
      tableProps,
      tableMethods,
      transfer2Right,
    };
  },
});
</script>
<style lang="less" scoped>
.query-component {
  background: #fff;
  border-radius: 8px;
  padding: 20px 24px;
  width: 100%;
  &__title {
    margin-top: 0;
    font-size: 18px;
    font-weight: 550;
  }
  &-content {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 100%;
    height: 320px;
    &-all {
      width: 30%;
      margin-right: 20px;
      height: 100%;
    }
    &-selected {
      width: 70%;
      height: 100%;
    }
  }
}
:deep(.table-striped) {
  background-color: #fafafa !important;
}
:deep(div.hoteam-b-table-list-toolbar.hoteam-b-table-list-toolbar-show-bottom) {
  display: none;
}
</style>
