<template>
  <div class="step1-box">
    <div class="step1">
      <div class="step1-form">
        <BasicForm @register="register" />
      </div>
      <Divider />
      <div class="database-title">
        <span>
          添加数据库表（请先选择数据库-第一个选择的为主库，次表为附表的附表，仅能用作关联附表使用）
        </span>
        <a-button type="primary" @click="add">
          <PlusOutlined />
          {{ t('新增') }}
        </a-button>
      </div>
      <div>
        <a-table
          rowKey="tableName"
          :columns="columns"
          :data-source="generatorConfig!.tableConfigs"
          :pagination="false"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'order'">
              <span>
                {{ index + 1 }}
              </span>
            </template>
            <template v-if="column.key === 'isMain'">
              <span>
                <a-tag v-if="record.isMain" color="blue"> 主表 </a-tag>
                <a-select
                  v-else
                  v-model:value="record.isSubForm"
                  class="w-4/5"
                  @change="handleTableForm(record)"
                >
                  <a-select-option :value="true">附表</a-select-option>
                  <a-select-option :value="false">次表</a-select-option>
                </a-select>
              </span>
            </template>
            <template v-else-if="column.key === 'relationField'">
              <template v-if="record.isSubForm">
                <Select
                  style="width: 200px"
                  v-model:value="record[column.key]"
                  :placeholder="t('请选择附表关联主表字段')"
                  show-search
                >
                  <SelectOption
                    v-for="(name, idx) in selectOptions[record.tableName]"
                    :key="idx"
                    :value="name"
                  >
                    {{ name }}
                  </SelectOption>
                </Select>
              </template>
            </template>
            <template v-else-if="column.key === 'relationTableField'">
              <template v-if="record.isSubForm">
                <Select
                  style="width: 200px"
                  v-model:value="record[column.key]"
                  :placeholder="t('请选择主表字段')"
                  show-search
                >
                  <SelectOption
                    v-for="(name, idx) in selectOptions[mainTableName]"
                    :key="idx"
                    :value="name"
                  >
                    {{ name }}
                  </SelectOption>
                </Select>
              </template>
            </template>
            <template v-else-if="column.key === 'action'">
              <span @click="remove(index, record.tableName)" class="delete-span">删除</span>
            </template>
          </template>
          <template #expandedRowRender="{ record }" v-if="!isUpdate">
            <a-table
              style="margin: 0"
              v-if="record.isMain"
              :columns="fieldColumns"
              :data-source="innerData[record.tableName]"
              :pagination="false"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'name'">
                  <div>{{ record.name }}</div>
                </template>
                <template v-else-if="column.dataIndex === 'length'">
                  <div>{{ record.length }}</div>
                </template>
                <template v-else-if="column.dataIndex === 'columnComment'">
                  <a-input
                    v-model:value.number="record.columnComment"
                    :placeholder="t('请填写备注')"
                  />
                </template>
                <template v-else-if="column.dataIndex === 'type'">
                  <div>{{ handleTypeChange(record.type) }}</div>
                </template>
              </template>
            </a-table>
          </template>
        </a-table>
      </div>
      <SelectDatabase @register="registerModal" @success="handleSelectSuccess" />
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { getDatabaselinkMultiTableColumns } from '/@/api/system/databaselink';
  import { getAuthList } from '/@/api/system/authorize';
  import { Divider } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { useModal } from '/@/components/Modal';
  import SelectDatabase from './components/SelectDatabase.vue';
  import { computed, inject, nextTick, onMounted, Ref, ref, toRaw } from 'vue';
  import { Select } from 'ant-design-vue';
  import { cloneDeep, debounce, uniqBy } from 'lodash-es';
  import { TableConfig } from '/@/model/generator/tableConfig';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    TableInfo,
    FieldInfo,
    fieldTypeList,
    fieldTypeCompMap,
    ColumnType,
  } from '/@/components/Designer';
  import { JavaTypeConvertTsType } from '/@/utils/helper/designHelper';
  import { useI18n } from '/@/hooks/web/useI18n';
  import * as antd from '/@/components/Designer/src/types';
  import { buildUUID } from '/@/utils/uuid';
  import { FormJson } from '/@/model/generator/codeGenerator';
  const props = defineProps({
    isUpdate: Boolean,
  });
  const { t } = useI18n();
  const SelectOption = Select.Option;

  const { notification } = useMessage();
  const generatorConfig = inject<GeneratorConfig>('generatorConfig');
  const widgetForm = inject('widgetForm') as any;
  const curDataBase = ref();
  const dataAuthPlaceholder = computed(() => {
    return generatorConfig!.outputConfig!.isDataAuth
      ? t('请选择已有通用数据权限')
      : t('请先启用数据权限');
  });

  const dataAuthHelpMessage = `
    1.启用数据权限会判断主表是否包含RuleUserlD字段如果存在，则不进行表结构修改，如果不存在，则会对主表进行字段添加。
    2.RuleUserlD主要用来控制每一条记录的权限所属人新增时，默认将当前登录认作为权限所属人。
    3.在表单设计中会添加“批量设置权限所属人”功能启用后，拥有该按钮权限的人员可以设置每一条记录的权限所属人。
      `;

  const formSchema: FormSchema[] = [
    {
      field: 'className',
      label: t('功能名称'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能名称'),
        onChange: debounce((val: ChangeEvent) => {
          generatorConfig!.outputConfig!.className = val.target.value;
        }, 200),
      },
    },
    {
      field: 'comment',
      label: t('功能描述'),
      required: true,
      component: 'Input',
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写功能描述'),
        onChange: debounce((val: ChangeEvent) => {
          generatorConfig!.outputConfig!.comment = val.target.value;
        }, 200),
      },
    },
    {
      field: 'outputArea',
      label: t('功能模块'),
      component: 'DicSelect',
      required: true,
      componentProps: {
        placeholder: t('请选择功能模块'),
        itemId: '1419276800524423333',
        onChange: debounce((_, obj) => {
          if (obj) {
            generatorConfig!.outputConfig!.outputArea = obj.id;
            generatorConfig!.outputConfig!.outputValue = obj.value;
          }
        }, 200),
        getPopupContainer: () => document.body,
      },
      colProps: { span: 12 },
    },
    {
      field: 'remarks',
      label: t('备注'),
      component: 'Input',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        placeholder: t('请填写备注'),
        onChange: debounce((val) => {
          generatorConfig!.outputConfig!.remarks = val.target.value;
        }, 200),
      },
    },
    {
      field: 'isDataAuth',
      label: t('数据权限'),
      component: 'Switch',
      required: false,
      colProps: { span: 12 },
      helpMessage: dataAuthHelpMessage,
      helpComponentProps: { maxWidth: '400px' },
      componentProps: {
        checkedValue: true,
        unCheckedValue: false,
        onChange: (val) => {
          if (!val) {
            setFieldsValue({ dataAuthList: [] });
            generatorConfig!.outputConfig!.dataAuthList = [];
          }
          generatorConfig!.outputConfig!.isDataAuth = val;
        },
      },
    },
    {
      field: 'dataAuthList',
      label: t('权限选择'),
      component: 'ApiSelect',
      required: false,
      colProps: { span: 12 },
      componentProps: {
        mode: 'multiple',
        placeholder: dataAuthPlaceholder,
        api: getAuthList,
        labelField: 'name',
        valueField: 'id',
        getPopupContainer: () => document.body,
        onChange: (val) => {
          generatorConfig!.outputConfig!.dataAuthList = val;
        },
      },
      dynamicDisabled: ({ values }) => {
        return !values.isDataAuth;
      },
    },
    {
      field: 'databaseId',
      label: t('数据库'),
      component: 'DbSelect',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: t('请选择数据库'),
        onChange: debounce((val) => {
          generatorConfig!.databaseId = val;
          if (curDataBase.value && curDataBase.value !== val) {
            generatorConfig!.tableConfigs = [];
          }

          curDataBase.value = val;
        }, 200),
      },
    },
  ];

  const columns = [
    {
      title: '#',
      dataIndex: 'order',
      key: 'order',
      width: 80,
      align: 'center',
    },
    {
      title: t('类别'),
      dataIndex: 'isMain',
      key: 'isMain',
      width: 120,
      align: 'center',
    },
    {
      title: t('表名'),
      dataIndex: 'tableName',
      key: 'tableName',
      align: 'center',
    },
    {
      title: t('关联字段'),
      dataIndex: 'relationField',
      key: 'relationField',
      align: 'center',
    },
    {
      title: t('关联表字段'),
      key: 'relationTableField',
      dataIndex: 'relationTableField',
      align: 'center',
    },
    {
      title: t('操作'),
      key: 'action',
      width: 80,
      align: 'center',
    },
  ];

  const fieldColumns = [
    {
      title: t('字段名'),
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: t('字段长度'),
      dataIndex: 'length',
      align: 'center',
    },
    {
      title: t('数据格式'),
      dataIndex: 'type',
      align: 'center',
    },
    {
      title: t('备注'),
      dataIndex: 'columnComment',
      align: 'center',
    },
  ];
  const allComponents = [
    ...antd.basicComponents,
    ...antd.advanceComponents,
    ...antd.buttonComponents,
    ...antd.layoutComponents,
    ...antd.workFlowComponents,
    ...antd.infoComponents,
    ...antd.financeComponents,
  ];
  const [registerModal, { openModal }] = useModal();

  const [register, { validate, getFieldsValue, setFieldsValue, clearValidate }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    layout: 'vertical',
    rowProps: { gutter: 32 },
  });
  const selectOptions = ref({});
  const selectTableName = computed(() =>
    generatorConfig!.tableConfigs!.map((item) => item.tableName),
  );
  const innerData = ref({});
  const mainTableName = computed(
    () => generatorConfig!.tableConfigs!.find((item) => item.isMain)!.tableName,
  );

  defineEmits(['register']);

  const tableInfo = inject<Ref<TableInfo[]>>('tableInfo', ref([]));

  onMounted(() => {
    const { tableConfigs, databaseId, outputConfig } = generatorConfig!;

    setFieldsValue({
      className: outputConfig?.className,
      comment: outputConfig?.comment,
      outputArea: outputConfig?.outputArea,
      databaseId: databaseId,
      isDataAuth: outputConfig?.isDataAuth || false,
      dataAuthList: outputConfig?.dataAuthList || [],
    });

    if (tableConfigs && tableConfigs.length > 0) {
      getDatabaselinkMultiTableColumns({
        id: databaseId,
        tableNames: selectTableName.value.join(','),
      }).then((result) => {
        for (const key in result) {
          const columnInfo = result[key];
          //如果已经写入过的表格 不再添加
          if (!tableInfo?.value.find((x) => x.name === key)) {
            const fields = columnInfo.map((field) => {
              const filedInfo: FieldInfo = {
                name: field.column,
                length: field.dataLength,
                type: JavaTypeConvertTsType(field.dataType),
                isPk: field.primaryKey,
                isNullable: field.nullable,
              };
              return filedInfo;
            });
            const info = generatorConfig!.tableConfigs!.find((x) => x.tableName === key);

            tableInfo?.value.push({
              name: key,
              isMain: info?.isMain as boolean,
              isSubForm: info?.isSubForm as boolean,
              fields: fields,
            });
            innerData.value[key] = fields;
          }

          selectOptions.value[key] = columnInfo.map((x) => x.column);
        }
      });
    }
    nextTick(() => {
      clearValidate();
    });
  });

  const add = async () => {
    try {
      const values = await validate();
      openModal(true, {
        databaseId: values.databaseId,
        selectTableName: selectTableName.value,
      });
    } catch (error) {}
  };

  const handleTableForm = (info) => {
    tableInfo?.value.forEach((item) => {
      if (item.name === info.tableName) item.isSubForm = info.isSubForm;
    });
    if (info.isSubForm === false) {
      info.relationField = '';
      info.relationTableField = '';
    }
  };
  const handleTypeChange = (value) => {
    let obj = fieldTypeList.find((o) => {
      return o.value == value;
    });
    if (obj) return obj.label;
    return '';
  };
  const handleSelectSuccess = (selectRows: TableConfig[]) => {
    if (generatorConfig?.tableConfigs && generatorConfig?.tableConfigs.length === 0) {
      tableInfo.value!.length = 0;
      generatorConfig!.tableConfigs = [...toRaw(selectRows)];
    } else {
      generatorConfig!.tableConfigs = uniqBy(
        generatorConfig!.tableConfigs!.concat([...selectRows]),
        'tableName',
      );
    }
    const formData = getFieldsValue();

    getDatabaselinkMultiTableColumns({
      id: formData.databaseId,
      tableNames: selectTableName.value.join(','),
    }).then((result) => {
      for (const key in result) {
        const columnInfo = result[key];

        //如果已经写入过的表格 不再添加
        if (!tableInfo?.value.find((x) => x.name === key)) {
          const fields = columnInfo.map((field) => {
            const filedInfo: FieldInfo = {
              name: field.column,
              length: field.dataLength,
              type: JavaTypeConvertTsType(field.dataType),
              isPk: field.primaryKey,
              isNullable: field.nullable,
            };
            return filedInfo;
          });
          const info = generatorConfig!.tableConfigs!.find((x) => x.tableName === key);

          tableInfo?.value.push({
            name: key,
            isMain: info?.isMain as boolean,
            isSubForm: info?.isSubForm as boolean,
            fields: fields,
          });
          const thisTableConfig = generatorConfig!.tableConfigs!.find((x) => x.tableName === key);
          const col = columnInfo.find((x) => x.primaryKey);
          thisTableConfig!.pkField = col.column;
          thisTableConfig!.pkType = col.dataType;
          innerData.value[key] = fields;
        }

        selectOptions.value[key] = columnInfo.map((x) => x.column);
      }
    });
  };

  const remove = (index, tableName) => {
    // TODO 这里删除 可能会引起 表单设计步骤所有的设计 出错。3个解决方案
    //1 删除后提示用户 表单设计全部清空！
    //2 删除之后根据所删除的表名  去表单设计Json匹配 所绑定的组件 全部将绑定表置空！
    //3 表单设计后 不允许删除表配置！
    //如果删除的数据是主表 并且还有其他表  默认顺序 找下一张表 将其设为主表
    if (generatorConfig!.tableConfigs![index].isMain && generatorConfig!.tableConfigs!.length > 1) {
      const nextObj = generatorConfig!.tableConfigs![index + 1];
      nextObj.isMain = true;
      nextObj.relationField = '';
      nextObj.relationTableField = '';

      const nextTable = tableInfo!.value![index + 1];
      nextTable.isMain = true;
    }
    generatorConfig!.tableConfigs!.splice(index, 1);
    tableInfo!.value = tableInfo?.value.filter((x) => x.name !== tableName);
  };

  //验证当前步骤的数据
  const validateStep = async (): Promise<boolean> => {
    try {
      await validate();
      const { tableConfigs, outputConfig } = generatorConfig as GeneratorConfig;

      //判断tableconfig 是否为空 或者 一条数据都没有
      if (!tableConfigs || tableConfigs!.length === 0) {
        notification.error({
          message: t('提示'),
          description: t('数据表配置不能为空！'),
        }); //提示消息
        return false;
      }
      if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(outputConfig.className!)) {
        notification.error({
          message: t('提示'),
          description: t('功能名称只能是数字和字母组成，必须以英文字母开头'),
        }); //提示消息
        return false;
      }

      for (const config of tableConfigs!) {
        //如果是主表 可以不需要关联字段等
        if (config.isMain || !config.isSubForm) {
          if (!config.tableName) {
            notification.error({
              message: t('提示'),
              description: t('主表表名未能配置成功！'),
            }); //提示消息
            return false;
          }
        } else {
          //子表需要验证关联字段 已经关联表 是否选择好
          if (!config.tableName) {
            notification.error({
              message: t('提示'),
              description: t('子表表名未能配置成功！'),
            }); //提示消息
            return false;
          }

          if (!config.relationField) {
            notification.error({
              message: t('提示'),
              description: t(`{name} 表 关联字段未选中`, { name: config.tableName }),
            }); //提示消息
            return false;
          }

          if (!config.relationTableField) {
            notification.error({
              message: t('提示'),
              description: t(`{name} 表 关联表字段未选中`, { name: config.tableName }),
            }); //提示消息
            return false;
          }
        }
      }
      if (!props.isUpdate) {
        let formJson: FormJson = {
          list: [],
          config: {
            formType: 'modal',
            size: 'default',
            layout: 'vertical',
            labelAlign: 'right',
            labelCol: {
              span: 3,
              offset: 0,
            },
            formWidth: 900,
          },
          hiddenComponent: [],
        };
        for (const config of tableConfigs!) {
          if (config.isMain) {
            let fields = innerData.value[config.tableName];
            const list: any = [];
            fields.forEach((f) => {
              if (
                !(
                  (f.type == ColumnType.KEY && f.length < 19) ||
                  (f.type == ColumnType.LONGTEXT && f.length < 200)
                )
              ) {
                let obj: any = allComponents.find((a) => {
                  return a.type == (f.isPk ? 'input' : fieldTypeCompMap[f.type]);
                });
                if (obj) {
                  let form = cloneDeep(obj);
                  if (f.columnComment) form.label = f.columnComment;
                  form.options.placeholder = t(
                    ([4, 5, 6, 8].includes(f.type) ? '请选择' : '请输入') + form.label,
                  );
                  form.key = buildUUID();
                  form.model = fieldTypeCompMap[f.type] + '_' + form.key;
                  form.bindField = f.name;
                  form.bindTable = config.tableName;
                  list.push(form);
                }
              }
            });
            formJson.list = list;
            generatorConfig.formJson = formJson;
            widgetForm.value = formJson;
          }
        }
      }
    } catch (error) {
      return false;
    }

    return true;
  };

  function editFieldsValue() {
    const { databaseId, outputConfig, tableConfigs } = generatorConfig!;

    setFieldsValue({
      className: outputConfig?.className,
      comment: outputConfig?.comment,
      outputArea: outputConfig?.outputArea,
      databaseId: databaseId,
      isDataAuth: outputConfig?.isDataAuth || false,
      dataAuthList: outputConfig?.dataAuthList || [],
    });

    if (tableConfigs && tableConfigs.length > 0) {
      getDatabaselinkMultiTableColumns({
        id: databaseId,
        tableNames: selectTableName.value.join(','),
      }).then((result) => {
        for (const key in result) {
          const columnInfo = result[key];
          //如果已经写入过的表格 不再添加
          if (!tableInfo?.value.find((x) => x.name === key)) {
            const fields = columnInfo.map((field) => {
              const filedInfo: FieldInfo = {
                name: field.column,
                length: field.dataLength,
                type: JavaTypeConvertTsType(field.dataType),
                isPk: field.primaryKey,
                isNullable: field.nullable,
              };
              return filedInfo;
            });

            tableInfo?.value.push({
              name: key,
              isMain: generatorConfig!.tableConfigs!.find((x) => x.tableName === key)
                ?.isMain as boolean,
              fields: fields,
            });
          }

          selectOptions.value[key] = columnInfo.map((x) => x.column);
        }
      });
    }
  }
  defineExpose({ validateStep, setFieldsValue, editFieldsValue });
</script>
<style lang="less" scoped>
  :deep(.ant-tag-orange),
  :deep(.ant-tag-blue) {
    background: #fff;
    font-size: 13px;
  }

  :deep(.ant-tooltip-inner) {
    white-space: pre-wrap !important;
  }
</style>
