<template>
  <div class="step1-box">
    <a-modal
      :width="1200"
      v-model:visible="state.configDia"
      :title="t('填充表单配置')"
      :maskClosable="false"
      :bodyStyle="state.modalBodyStyle"
      destroyOnClose
      @ok="handleConfirm"
      @cancel="handleClose"
    >
      <div class="step1">
        <div class="flex justify-end mb-3">
          <a-button type="primary" @click="addInParams">添加填充配置</a-button>
        </div>
        <a-table :columns="intableColumns" :data-source="intableData" :pagination="false">
          <template #headerCell="{ column }">
            <div v-if="column.dataIndex === 'from'"
              >{{ column.title
              }}<a-tooltip>
                <template #title>
                  <div class="flex items-start">
                    <InfoCircleOutlined class="text-base mt-1" />
                    <div class="ml-3">
                      <div class="text-base">填充数据来源</div>
                      <div>指的是刷新组件中选择的表格组件，也可选择树形、查询组件。</div>
                    </div>
                  </div>
                </template>
                <QuestionCircleOutlined class="ml-2" /> </a-tooltip
            ></div>
          </template>
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex === 'sort'">
              <svg class="icon queryDraggable-icon" aria-hidden="true" style="cursor: move">
                <use xlink:href="#icon-paixu" />
              </svg>
            </template>
            <template v-if="column.dataIndex === 'name'">
              <a-select v-model:value="record.name" style="width: 180px" :options="optionsComp" />
            </template>
            <template v-else-if="column.dataIndex === 'type'">
              <a-select
                v-if="record.name"
                v-model:value="record.type"
                style="width: 100%"
                :options="options1"
                @change="record.value = null"
              />
              <div v-else class="text-[#999]">{{ t('请先选择组件') }}</div>
            </template>
            <template v-else-if="column.dataIndex === 'from'">
              <a-select
                v-if="record.name"
                v-model:value="record.from"
                style="width: 100%"
                :options="options3"
                @change="record.value = null"
              />

              <div v-else class="text-[#999]">{{ t('请先选择组件') }}</div>
            </template>
            <template v-else-if="column.dataIndex === 'value'">
              <template v-if="record.name">
                <a-select
                  v-model:value="record.value"
                  :options="options4"
                  style="width: 100%"
                  v-if="record.from == dataFromType.info"
                />
                <a-tree-select
                  v-if="record.from == dataFromType.table"
                  v-model:value="record.value"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="tableComp"
                />
                <a-tree-select
                  v-if="record.from == dataFromType.search"
                  v-model:value="record.value"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="searchComp"
                />
                <a-tree-select
                  v-if="record.from == dataFromType.tree"
                  v-model:value="record.value"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="treeComp"
                />
                <a-tree-select
                  v-if="record.from == dataFromType.form"
                  v-model:value="record.value"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择"
                  allow-clear
                  tree-default-expand-all
                  :tree-data="formsComp"
                />
              </template>
              <div v-else class="text-[#999]">{{ t('请先选择组件') }}</div>
            </template>
            <template v-else-if="column.dataIndex === 'isReset'">
              <a-select
                v-if="record.name"
                v-model:value="record.isReset"
                style="width: 100%"
                :options="options2"
              />
              <div v-else class="text-[#999]">{{ t('请先选择组件') }}</div>
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <a-button danger type="link" @click="deleteInData(index)">删除</a-button>
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>
    <ApiConfig
      v-if="apiConfigDialog"
      v-model:apiConfigDialog="apiConfigDialog"
      v-model:apiConfig="intableData[curTableidx].apiConfig"
      :title="t('API配置')"
      isQrcode
    />
    <StaticData
      v-if="dataDialog"
      v-model:configDialog="dataDialog"
      v-model:config="intableData[curDataidx].staticOptions"
    />
  </div>
</template>
<script lang="ts" setup>
  import { inject, onMounted, reactive, ref, watch } from 'vue';

  import { useI18n } from '/@/hooks/web/useI18n';
  import { ApiConfig } from '/@/components/ApiConfig';
  import StaticData from './staticData.vue';
  import type { TreeSelectProps } from 'ant-design-vue';
  import { notification, type SelectProps } from 'ant-design-vue';
  import { dataFromType, searchCompType } from '../../types';
  import { cloneDeep } from 'lodash-es';

  import { QuestionCircleOutlined, InfoCircleOutlined } from '@ant-design/icons-vue';

  import { getComponents, getCurPageComponents, getTableComponents } from '../../types/tool';
  const { t } = useI18n();
  const props = defineProps({
    configDialog: { type: Boolean },
    config: { type: Object },
    formProps: Array,
    refreshComponent: Array,
  });
  const state = reactive({
    configDia: props.configDialog as boolean,
    modalBodyStyle: {
      padding: '15px 15px 10px 10px',
      minHeight: '400px',
    },
  });
  const intableData = ref<any>(cloneDeep(props.config) || []);
  const apiConfigDialog = ref<boolean>(false);
  const curTableidx = ref(0);
  const optionsComp = ref<SelectProps['options']>([]);
  const tableComp = ref<TreeSelectProps['treeData']>([]);
  const searchComp = ref<TreeSelectProps['treeData']>([]);
  const formsComp = ref<TreeSelectProps['treeData']>([]);
  const treeComp = ref<TreeSelectProps['treeData']>([]);
  const dataDialog = ref<boolean>(false);
  const curDataidx = ref(0);

  const options1 = ref<SelectProps['options']>([
    {
      value: searchCompType.text,
      label: '文本',
    },
    {
      value: searchCompType.select,
      label: '下拉选择',
    },
    {
      value: searchCompType.time,
      label: '时间选择',
    },
    {
      value: searchCompType.radio,
      label: '单选框',
    },
    {
      value: searchCompType.finance,
      label: '财务组件',
    },
  ]);
  const options2 = ref<SelectProps['options']>([
    {
      value: '1',
      label: '是',
    },
    {
      value: '0',
      label: '否',
    },
  ]);
  const options3 = ref<SelectProps['options']>([
    {
      value: dataFromType.info,
      label: '当前登录人信息',
    },
    {
      value: dataFromType.table,
      label: '表格组件',
    },
    {
      value: dataFromType.search,
      label: '查询组件',
    },
    {
      value: dataFromType.tree,
      label: '树形组件',
    },
    {
      value: dataFromType.form,
      label: '表单组件',
    },
  ]);
  const options4 = ref<SelectProps['options']>([
    {
      label: t('当前人员名称'),
      value: 'name',
    },
    {
      label: t('当前人员ID'),
      value: 'id',
    },
    {
      label: t('当前人员编码'),
      value: 'code',
    },
    {
      label: t('当前人员手机号'),
      value: 'mobile',
    },
    {
      label: t('当前人员所属组织架构名称'),
      value: 'departmentName',
    },
    {
      label: t('当前人员所属组织架构ID'),
      value: 'departmentId',
    },
    {
      label: t('当前人员岗位ID'),
      value: 'postId',
    },
    {
      label: t('当前人员角色ID'),
      value: 'roles.id',
    },
  ]);

  const intableColumns = [
    { title: t('排序'), dataIndex: 'sort', align: 'center', width: 70 },
    {
      title: t('组件名称'),
      dataIndex: 'name',
      align: 'center',
      width: 200,
    },
    {
      title: t('组件类别'),
      dataIndex: 'type',
      align: 'center',
      width: 200,
    },
    {
      title: t('填充数据来源'),
      dataIndex: 'from',
      align: 'center',
      width: 260,
    },
    {
      title: t('填充数据值'),
      dataIndex: 'value',
      align: 'center',
      width: 260,
    },
    {
      title: t('是否覆盖已有数据'),
      dataIndex: 'isReset',
      align: 'center',
      width: 260,
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      align: 'center',
      width: 80,
    },
  ];
  const widgetForm = inject('widgetForm', ref<any>([]));
  const formList = ref([]);
  const emit = defineEmits(['update:configDialog', 'update:config', 'update:schemas']);
  onMounted(async () => {
    optionsComp.value = [];
    getComponents(props.formProps || [], optionsComp.value);

    tableComp.value = [];
    searchComp.value = [];
    formsComp.value = [];
    getTableComponents(widgetForm.value, formList.value);
    await getCurPageComponents(
      formList.value,
      tableComp.value,
      searchComp.value,
      formsComp.value,
      treeComp.value,
      props.refreshComponent,
    );
    intableData.value.forEach((o) => {
      if (o.from == dataFromType.search) {
        let value = JSON.parse(o.value);
        let isHas = false;
        if (searchComp.value?.length) {
          for (let i = 0; i < searchComp.value.length; i++) {
            let j = searchComp.value[i];
            let obj = j.children?.find((k) => {
              let field = JSON.parse(k.value).bindField;
              return field == value?.bindField;
            });
            if (obj) {
              isHas = true;
              break;
            }
          }
        }
        if (!isHas) {
          o.value = null;
        }
      }
    });
  });
  watch(
    () => props.formProps,
    (list) => {
      optionsComp.value = [];
      getComponents(list, optionsComp.value);
    },
    { deep: true },
  );

  //验证当前步骤的数据
  const validateStep = async (): Promise<boolean> => {
    const inarray = findDuplicates(intableData.value);

    if (inarray.length > 0) {
      let msg = t(`${inarray.length > 0 ? '查询名称' + inarray.join(',') + '重复;' : ''} `);
      notification.warning({
        message: t('提示'),
        description: msg,
      });
      return false;
    }
    return true;
  };
  function findDuplicates(arr) {
    let seen = new Set();
    let duplicates: string[] = [];

    arr.forEach((item) => {
      if (seen.has(item.name)) {
        duplicates.push(item.name);
      } else {
        seen.add(item.name);
      }
    });

    return duplicates;
  }

  function addInParams() {
    intableData.value.push({
      name: '',
      type: null,
      from: null,
      value: null,
      isReset: true,
    });
  }
  function deleteInData(idx) {
    intableData.value.splice(idx, 1);
  }
  const handleClose = () => {
    state.configDia = false;
    emit('update:configDialog', false);
  };
  const handleConfirm = async () => {
    let res = await validateStep();

    if (res) {
      emit('update:config', intableData.value);
      handleClose();
    }
  };
</script>
<style lang="less" scoped>
  :deep(.ant-input-affix-wrapper) {
    height: auto;
  }

  .icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentcolor;
    overflow: hidden;
    display: inline-block;
  }
</style>
