<template>
  <div class="h-full list-config">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="dashed" @click="addDetailRow()"> 添加 </a-button>
      </template>
      <template #headerCell="{ column }">
        <template v-if="column.key === 'sort'">
          <Icon size="14" icon="mingcute:move-line" />
        </template>
      </template>
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '删除',
                color: 'error',
                onClick: handleDelete.bind(null, index),
              },
            ]"
          />
        </template>

        <template v-if="column.key === 'field'">
          <Select
            style="width: 100%"
            v-model:value="record[column.key]"
            placeholder="请选择字段"
            show-search
            :filterOption="filterOption"
            @change="handleChange(index, $event)"
            :options="ledgerConfig.tableFieldConfigs"
            :fieldNames="{ label: 'fieldComment', value: 'fieldName' }"
          />
        </template>

        <template v-if="column.key === 'label'">
          <a-input v-model:value="record[column.key]" placeholder="输入显示名称" />
        </template>
        <template v-if="column.key === 'component'">
          <Select
            style="width: 100%"
            v-model:value="record[column.key]"
            placeholder="请控件类型"
            :options="fieldTypeList"
          />
        </template>
        <template v-if="column.key === 'bindObject'">
          <template v-if="record['component'] === 'ApiSelect'">
            <Select
              style="width: 100%"
              v-model:value="record[column.key]"
              placeholder="绑定对象"
              show-search
              :options="bindObjectList"
            />
          </template>
          <template v-else>
            <div></div>
          </template>
        </template>
        <template v-if="column.key === 'bindValue'">
          <template v-if="record['bindObject'] === 'api' && record['component'] === 'ApiSelect'">
            <a-input
              v-model:value="record['apiInfo'].path"
              placeholder="点击进行接口配置"
              @click="showApiConfig(index)"
            >
              <template #suffix>
                <Icon icon="ant-design:ellipsis-outlined" />
              </template>
            </a-input>
          </template>
          <template
            v-else-if="record['bindObject'] === 'dic' && record['component'] === 'ApiSelect'"
          >
            <DicTreeSelect v-model:value="record[column.key]" @change="handleDicChange" />
          </template>
          <template v-else>
            <div></div>
          </template>
        </template>
        <template v-if="column.key === 'defaultValue'">
          <a-input v-model:value="record[column.key]" placeholder="输入默认值" />
        </template>
        <template v-if="column.key === 'sort'">
          <Icon size="14" class="columnDraggable-icon" icon="tabler:arrows-move-vertical" />
        </template>
      </template>
    </BasicTable>

    <ApiConfig
      v-if="apiConfigDialog"
      v-model:apiConfigDialog="apiConfigDialog"
      v-model:apiConfig="apiConfigValue"
      :isCascader="isCascader"
      :isQrcode="isQrcode"
      :isSubForm="true"
      :title="isCascader ? '级联配置-API' : 'API配置'"
      @success="handelSuccess"
    />
  </div>
</template>
<script lang="ts" setup>
  import { Ref, inject, ref, unref, computed, provide, onMounted, nextTick, watch } from 'vue';
  import { BasicTable, useTable, BasicColumn, TableAction } from '/@/components/Table';
  import { LedgerConfig, LedgerSerachConfigs } from '/@/model/generator/ledgerConfig';
  import { buildUUID } from '/@/utils/uuid';
  import { Select } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ApiConfig } from '/@/components/ApiConfig';
  import { Icon } from '/@/components/Icon';
  import { DicTreeSelect } from '/@/components/DicTreeSelect';
  import { getDicDetailList } from '/@/api/system/dic';
  import { cloneDeep } from 'lodash-es';
  import Sortable from 'sortablejs';
  import { isNullAndUnDef } from '/@/utils/is';

  const ledgerConfig = inject<LedgerConfig>('ledgerConfig') as LedgerConfig;
  const { createMessage, notification } = useMessage();

  const columns: BasicColumn[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 40,
    },
    {
      title: '参数字段',
      dataIndex: 'field',
      align: 'left',
    },
    {
      title: '显示名称',
      dataIndex: 'label',
      align: 'left',
      width: 250,
    },
    {
      title: '控件类型',
      dataIndex: 'component',
      align: 'left',
      width: 150,
    },
    {
      title: '绑定对象',
      dataIndex: 'bindObject',
      align: 'left',
      width: 150,
    },
    {
      title: '绑定值',
      dataIndex: 'bindValue',
      align: 'left',
      width: 250,
    },
    {
      title: '默认值',
      dataIndex: 'defaultValue',
      align: 'left',
      width: 150,
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'left',
      width: 120,
      fixed: 'right',
    },
  ];

  const fieldTypeList = [
    {
      label: '文本',
      value: 'Input',
    },
    {
      label: '下拉框',
      value: 'ApiSelect',
    },
    {
      label: '日期',
      value: 'DatePicker',
    },
  ];

  const bindObjectList = [
    {
      label: '接口',
      value: 'api',
    },
    {
      label: '字典',
      value: 'dic',
    },
  ];
  const dataSource: Ref<LedgerSerachConfigs[]> = ref([]);

  const [registerTable] = useTable({
    title: '查询条件配置',
    rowKey: 'key',
    columns: columns,
    dataSource: dataSource,
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    immediate: false,
    canResize: true,
    showIndexColumn: false,
    pagination: false,
  });

  const apiConfigDialog = ref<boolean>(false);
  const isCascader = ref<boolean>(false);
  const isQrcode = ref<boolean>(false);
  const apiConfigValue = ref<Recordable>({});
  const editIndex = ref(-1);
  const remoteDefaultOptions = ref<Recordable[]>([]);

  const widgetForm = computed(() => {
    const list = dataSource.value.map((item) => {
      return {
        key: buildUUID(),
        bindField: item.field,
        label: item.label,
        type: item.component,
      };
    });
    return { list: list };
  });

  provide('widgetForm', widgetForm);

  const showApiConfig = (index: number) => {
    apiConfigDialog.value = true;
    isCascader.value = false;
    apiConfigValue.value = dataSource.value[index].apiInfo;
    editIndex.value = index;
  };

  const handleDelete = (index: number) => {
    dataSource.value.splice(index, 1);
  };

  const validateStep = () => {
    try {
      const tableConfigs = unref(dataSource);

      if (tableConfigs!.length === 0) {
        notification.error({
          message: '提示',
          description: '数据表配置不能为空！',
        });
        return false;
      }

      for (const config of tableConfigs!) {
        if (!config.field) {
          notification.error({
            message: '提示',
            description: '列表字段未选择！',
          });
          return false;
        }

        if (!config.label) {
          notification.error({
            message: '提示',
            description: '显示名称未设置！',
          });
          return false;
        }
      }

      ledgerConfig.serachConfigs = cloneDeep(tableConfigs);
    } catch {
      return false;
    }
    return true;
  };

  const filterOption = (input: string, option: any) => {
    return (
      option.fieldName.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
      option.fieldComment.toLowerCase().indexOf(input.toLowerCase()) >= 0
    );
  };

  const handleChange = (index: number, value: string) => {
    if (dataSource.value.filter((item) => item.field === value).length > 1) {
      createMessage.error('字段已经存在！');
      dataSource.value[index].field = '';
    } else {
      const filterItem = ledgerConfig?.tableFieldConfigs.filter((item) => item.fieldName === value);
      if (filterItem?.length > 0) {
        dataSource.value[index].label = filterItem[0].fieldComment;
      }
    }
  };

  const handleDicChange = async (value: string) => {
    const result = await getDicDetailList({ itemId: value });

    remoteDefaultOptions.value = result.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  };

  const addDetailRow = () => {
    const newData: LedgerSerachConfigs = {
      key: buildUUID(),
      field: '',
      label: '',
      component: 'Input',
      bindObject: '',
      sort: 10,
      bindValue: '',
      defaultValue: '',
      apiInfo: { path: '' },
    };
    dataSource.value.push(newData);
  };

  const setTableData = (ledgerSerachConfigs: LedgerSerachConfigs[]) => {
    dataSource.value = cloneDeep(ledgerSerachConfigs);
  };

  const handelSuccess = (data) => {
    dataSource.value[editIndex.value].apiInfo = data;
  };

  const setDefaultData = (values) => {
    const data: LedgerSerachConfigs[] = [];
    values.forEach((item) => {
      const filterItem = ledgerConfig.tableFieldConfigs.filter((fl) => fl.fieldName === item.name);
      if (filterItem.length > 0) {
        const dataRow: LedgerSerachConfigs = {
          key: buildUUID(),
          field: item.name,
          label: filterItem[0].fieldComment,
          component: 'Input',
          bindObject: '',
          sort: 10,
          bindValue: '',
          defaultValue: item.defaultValue,
          apiInfo: { path: '' },
        };
        data.push(dataRow);
      }
    });
    if (data.length > 0) {
      dataSource.value = cloneDeep(data);
    }
  };

  watch(
    () => ledgerConfig?.apiInfo?.apiParams,
    (val) => {
      if (val && val[0]?.tableInfo && val[0]?.tableInfo.length) {
        setDefaultData(val[0]?.tableInfo);
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );

  onMounted(() => {
    nextTick(() => {
      const tbody: any = document.querySelector('.list-config .ant-table-tbody');
      Sortable.create(tbody, {
        handle: '.columnDraggable-icon',
        onEnd: ({ oldIndex, newIndex }) => {
          if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
            return;
          }
          const columns = cloneDeep(dataSource.value);
          if (oldIndex > newIndex) {
            columns.splice(newIndex - 1, 0, columns[oldIndex - 1]);
            columns.splice(oldIndex, 1);
          } else {
            columns.splice(newIndex - 1, 0, columns[oldIndex - 1]);
            columns.splice(oldIndex - 1, 1);
          }
          dataSource.value = cloneDeep(columns);
        },
      });
    });
  });

  defineExpose({ validateStep, setTableData });
</script>
<style lang="less" scoped>
  .icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentcolor;
    overflow: hidden;
  }
</style>
