<template>
  <div class="step1">
    <div class="step1-form">
      <!-- 步骤一：基本配置 info 部分 -->
      <BasicForm @register="infoRegister" @change="formTypeValue" />
    </div>
    <Divider />
    <div class="p-4">
      <BasicTable
        title="添加数据库表（请先选择数据库）"
        @register="schemeTableRegister_1"
        :dataSource="schemeTable_data_1"
        :columns="getScheme_table_1()"
        :loading="loading"
        :bordered="border"
        :pagination="false"
        :canResize="false"
        v-if="publicOrView"
        maxHeight="1600px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <Tag v-if="record.type == 'main'" :color="'blue'">{{ $t('主表') }}</Tag>
            <Tag v-else :color="'red'" @click="changePrimaryKey(record)">{{ $t('子表') }}</Tag>
          </template>
          <template v-if="column.key === 'field' && record.type != 'main'">
            <Select
              v-model:value="record.field"
              :options="record.fieldSelect"
              size="large"
              :placeholder="$t('请选择')"
            />
          </template>
          <template v-if="column.key === 'relationName' && record.type != 'main'">
            <Select
              v-model:value="record.relationName"
              :options="record.relationNameSelect"
              size="large"
              :placeholder="$t('请选择')"
            />
          </template>
          <template v-if="column.key === 'relationField' && record.type != 'main'">
            <Select
              v-model:value="record.relationField"
              :options="getChooseRelationFieldList(record.relationName)"
              size="large"
              :placeholder="$t('请选择')"
              :ifShow="record.relationName"
            />
          </template>
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  label: '删除',
                  onClick: () => {
                    table_delete(1, record);
                  },
                },
              ]"
            />
          </template>
        </template>

        <template #toolbar>
          <a-button type="primary" class="my-4" @click="openPageChooseModal(1)">
            {{ '添加' }}
          </a-button>
        </template>
      </BasicTable>
      <BasicTable
        title="添加数据库关联表，只用来做数据权限设置（请先选择数据库）"
        @register="schemeTableRegister_2"
        :columns="getScheme_table_2()"
        :dataSource="schemeTable_data_2"
        :loading="loading"
        :bordered="border"
        :pagination="false"
        :canResize="false"
        v-if="publicOrView"
        maxHeight="1600px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'fname'">
            <Input v-model:value="record.fname" />
          </template>
          <template v-if="column.key === 'cfield'">
            <Select
              v-model:value="record.cfield"
              :options="record.cfieldSelect"
              size="large"
              :placeholder="$t('请选择')"
            />
          </template>
          <template v-if="column.key === 'field'">
            <Select
              v-model:value="record.field"
              :options="record.fieldSelect"
              size="large"
              :placeholder="$t('请选择')"
            />
          </template>
          <template v-if="column.key === 'relationName'">
            <Select
              v-model:value="record.relationName"
              :options="record.relationNameSelect"
              size="large"
              :placeholder="$t('请选择')"
            />
          </template>
          <template v-if="column.key === 'relationField'">
            <Select
              v-model:value="record.relationField"
              :options="getChooseRelationFieldList(record.relationName)"
              size="large"
              :placeholder="$t('请选择')"
            />
          </template>
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  label: '删除',
                  onClick: () => {
                    table_delete(2, record);
                  },
                },
              ]"
            />
          </template>
        </template>
        <template #toolbar>
          <a-button type="primary" class="my-4" @click="openPageChooseModal(2)">
            {{ '添加' }}
          </a-button>
        </template>
      </BasicTable>
      <BasicTable
        title="添加数据视图（请先选择数据库）"
        @register="schemeTableRegister_3"
        :columns="getScheme_table_3()"
        :dataSource="schemeTable_data_3"
        :loading="loading"
        :bordered="border"
        :pagination="false"
        :canResize="false"
        v-if="!publicOrView"
        maxHeight="1600px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <Tag v-if="record.type == 'main'" :color="'blue'">{{ $t('主') }}</Tag>
            <Tag v-else :color="'red'">{{ $t('子') }}</Tag>
          </template>
          <template v-if="column.key === 'name'">
            <a @click="showSqlModal(record)">{{ record.name }}</a>
          </template>
          <template v-if="column.key === 'relationField' && record.type != 'main'">
            <Select
              v-model:value="record.relationField"
              :options="record.relationFieldOptions"
              size="large"
              :placeholder="$t('请选择')"
            />
          </template>
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  label: '删除',
                  onClick: () => {
                    table_delete(3, record);
                  },
                },
              ]"
            />
          </template>
        </template>
        <template #toolbar>
          <a-button type="primary" class="my-4" @click="openViewModal">
            {{ '添加' }}
          </a-button>
        </template>
      </BasicTable>
    </div>
    <div style="display: flex; justify-content: center">
      <a-button type="primary" @click="customSubmitFunc">
        {{ '下一步' }}
      </a-button>
    </div>
    <!-- 三个表格的添加按钮弹窗 -->
    <PageTableChooseModal @register="pageTableChooseModalRegister" @choosedata="fun_choosedata" />
    <!-- 添加SQL -->
    <PageTableViewModal @register="pageTableViewModalRegister" @viewdata="fun_viewdata" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, defineProps, watch } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { Divider, Tag, Select, Input } from 'ant-design-vue';
  import PageTableChooseModal from './pageTableChooseModal.vue';
  import PageTableViewModal from './pageTableViewModal.vue';
  import {
    getStep1_Info,
    getScheme_table_1,
    getScheme_table_2,
    getScheme_table_3,
  } from './pageStepData';

  import {
    functionAddForm,
    functionUpdateForm,
    function_Get_GetForms,
  } from '@/api/demo/formScheme';

  const { createMessage } = useMessage();
  // 步骤一：基本配置 info 部分
  const [infoRegister, { getFieldsValue, setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 200,
    schemas: getStep1_Info,
    actionColOptions: {
      span: 14,
    },
    showResetButton: false,
    submitButtonOptions: {
      text: '暂存',
    },
    submitFunc: addAndUpdateFormInfoAndScheme,
  });

  // 声明schme三个表
  const [schemeTableRegister_1, { reload: reload_1, getDataSource: getDataSource_1 }] = useTable();
  const [schemeTableRegister_2, { reload: reload_2, getDataSource: getDataSource_2 }] = useTable();
  const [schemeTableRegister_3, { reload: reload_3, getDataSource: getDataSource_3 }] = useTable();
  // 声明schme第一、二个表的选择弹窗
  const [pageTableChooseModalRegister, { openModal: openChoose }] = useModal();
  // 声明schme第三个表的视图弹窗
  const [pageTableViewModalRegister, { openModal: openView }] = useModal();

  // 声明schme三个表的初始数据
  const schemeTable_data_1 = ref([]);
  const schemeTable_data_2 = ref([]);
  const schemeTable_data_3 = ref([]);

  // 第一、二个表和第三个表的显示隐藏
  const publicOrView = ref(true);
  function formTypeValue() {
    if (getFieldsValue().formType === 0) {
      publicOrView.value = true;
    } else if (getFieldsValue().formType === 1) {
      publicOrView.value = false;
    }
  }

  // 定义props
  const props = defineProps({
    editData: {
      type: Object,
      default: () => ({}), // 设置默认值为一个空对象
    },
  });
  // 监听props的变化
  watch(
    () => props.editData,
    () => {
      // 新值可用时执行相应逻辑
      // 新增
      if (props.editData && props.editData.isUpdate === false) {
        publicOrView.value = true;
        resetFields();
        schemeTable_data_1.value = null;
        schemeTable_data_2.value = null;
        schemeTable_data_3.value = null;
        reload_1();
        reload_2();
      }
      // 编辑
      if (props.editData.isUpdate) {
        if (props.editData.record.info.formType === 0) {
          publicOrView.value = true;
        }
        if (props.editData.record.info.formType === 1) {
          publicOrView.value = false;
        }
        setInfoAndScheme(props.editData.record);
      }
    },
    // { immediate: true }, // 设置immediate为true，会在初次绑定时执行回调
  );

  const primaryKey = ref<string>(null);
  const loading = ref(false);
  const border = ref(true);

  // 第一、二个表格打开
  let typeNum: number = 1;
  async function openPageChooseModal(type: number) {
    // 新增弹窗打开的第几个表格
    typeNum = type;
    openChoose(true);
  }

  // 检查是否重复加入
  function checkChooseData(rows) {
    let data1: [] = getDataSource_1() || [];
    let data2: [] = getDataSource_2() || [];
    const checkTable1 = [];
    const checkTable2 = [];
    data1.forEach((element) => {
      checkTable1.push(element.tableName);
    });
    data2.forEach((element) => {
      checkTable2.push(element.tableName);
    });

    const isPresent1 = rows.find((row) => {
      return checkTable1.includes(row.tableName);
    });

    if (isPresent1 && typeNum === 1) {
      createMessage.warn('重复添加表【' + isPresent1.tableName + '】');
      return false;
    }
    if (isPresent1 && typeNum === 2) {
      createMessage.warn('不能是表单已经绑定的表【' + isPresent1.tableName + '】');
      return false;
    }

    const isPresent2 = rows.find((row) => {
      return checkTable2.includes(row.tableName);
    });
    if (isPresent2 && typeNum === 1) {
      createMessage.warn(
        '不能是关联表表单已经绑定的表，请先删除关联表单的【' + isPresent2.tableName + '】',
      );
      return false;
    }
    if (isPresent2 && typeNum === 2) {
      createMessage.warn('重复添加表【' + isPresent2.tableName + '】');
      return false;
    }
    return true;
  }

  // 设置表1的外键和关联表
  let relationFieldList = [];
  function table1_setSelect(allData1, data) {
    // 关联主键
    let db_codecolumnsList = [];
    allData1.forEach((element) => {
      let tableName = element.db_codetable.tableName;
      element.db_codecolumnsList.forEach((e) => {
        db_codecolumnsList.push({
          key: e.dbColumnName,
          value: e.dbColumnName,
          label: e.dbColumnName,
        });
      });
      relationFieldList.push({ tableName, db_codecolumnsList });
    });

    for (let i = 0; allData1.length > i; i++) {
      // 外键
      const db_codecolumnsList_dbColumnName = [];

      // 关联表
      const db_codetable_temp = [];
      const db_codetable_tableName = [];
      allData1.forEach((element) => {
        db_codetable_temp.push(element.db_codetable.tableName);
      });

      allData1[i].db_codecolumnsList.forEach((e) => {
        db_codecolumnsList_dbColumnName.push({
          key: e.dbColumnName,
          value: e.dbColumnName,
          label: e.dbColumnName,
        });
      });

      data[i].fieldSelect = db_codecolumnsList_dbColumnName;

      db_codetable_temp.splice(i, 1);
      db_codetable_temp.forEach((tableName) => {
        db_codetable_tableName.push({
          key: tableName,
          value: tableName,
          label: tableName,
        });
      });
      data[i].relationNameSelect = db_codetable_tableName;
    }
    return data;
  }
  // 设置表2的比较字段、外键和关联表
  function table2_setSelect(allData1, allData2, data) {
    for (let i = 0; allData2.length > i; i++) {
      // 比较字段、外键
      const db_codecolumnsList_dbColumnName = [{}];
      allData2[i].db_codecolumnsList.forEach((e) => {
        db_codecolumnsList_dbColumnName.push({
          key: e.dbColumnName,
          value: e.dbColumnName,
          label: e.dbColumnName,
        });
      });
      data[i].cfieldSelect = db_codecolumnsList_dbColumnName;
      data[i].fieldSelect = db_codecolumnsList_dbColumnName;

      // 关联表
      const db_codetable_temp = [];
      const db_codetable_tableName = [];
      console.log(417, allData1);

      if (allData1) {
        allData1.forEach((element) => {
          db_codetable_temp.push(element.db_codetable.tableName);
        });

        db_codetable_temp.forEach((tableName) => {
          db_codetable_tableName.push({
            key: tableName,
            value: tableName,
            label: tableName,
          });
        });
      }
      data[i].relationNameSelect = db_codetable_tableName;
    }
    return data;
  }

  // 第一、二个表格的数据对象选择数据回传
  let allData1 = null;
  let allData2 = null;

  // 获取关联主键
  function getChooseRelationFieldList(tableName) {
    const table =
      relationFieldList.find((t) => {
        return t.tableName === tableName;
      }) || {};
    return table.db_codecolumnsList || [];
  }

  async function getAllData1() {
    let tableName = null;
    let data: [] = getDataSource_1() || [];
    data.forEach((row) => {
      tableName = (tableName ? tableName + ',' : '') + row.tableName;
    });
    var query = {
      dbcode: 'lrsystemdb',
      tableNames: tableName,
    };
    allData1 = await function_Get_GetForms(query);
    return allData1;
  }

  // 数据对象选择表的处理
  async function fun_choosedata(rows) {
    if (!rows) {
      return;
    }
    // 检查是否重复加入
    if (checkChooseData(rows)) {
      if (typeNum === 1) {
        // 第一、二个表格的数据对象选择数据回传时启动获取
        let tableName = null;
        let data: [] = getDataSource_1() || [];
        if (data) {
          data.forEach((row) => {
            tableName = (tableName ? tableName + ',' : '') + row.tableName;
          });
        }
        // 新数据
        rows.forEach((row) => {
          tableName = (tableName ? tableName + ',' : '') + row.tableName;
        });
        var query = {
          dbcode: 'lrsystemdb',
          tableNames: tableName,
        };
        allData1 = await function_Get_GetForms(query);
        rows.forEach((row) => {
          row.action = ''; // 添加操作栏
          data.push(row);
        });

        // 关联主键、外键和关联表
        data = table1_setSelect(allData1, data);
        // 主键
        if (primaryKey.value === null) {
          primaryKey.value = data[0].id;
          data[0].type = 'main';
        }
        data.forEach((element) => {
          if (element.type != 'main') {
            element.type = 'chlid';
          }
        });
        // ref的数据schemeTable_data_1
        schemeTable_data_1.value = data;
        reload_1();
        reload_2();
      }

      if (typeNum === 2) {
        // 第二个表格的数据对象选择数据回传时启动获取
        let tableName = null;
        let data: [] = getDataSource_2() || [];
        data.forEach((row) => {
          tableName = (tableName ? tableName + ',' : '') + row.tableName;
        });
        // 新数据
        rows.forEach((row) => {
          tableName = (tableName ? tableName + ',' : '') + row.tableName;
        });
        var query = {
          dbcode: 'lrsystemdb',
          tableNames: tableName,
        };
        allData1 = getAllData1() || [];
        allData2 = await function_Get_GetForms(query);
        rows.forEach((row) => {
          row.action = null; // 添加操作栏
          data.push(row);
        });

        data = table2_setSelect(allData1, allData2, data);
        schemeTable_data_2.value = data;
        reload_1();
        reload_2();
      }
    }
  }

  // 单击【子表】标签后变换为主键
  function changePrimaryKey(record) {
    primaryKey.value = record.id;
    const data = getDataSource_1() || [];

    data.forEach((element) => {
      if (element.id === record.id) {
        element.type = 'main';
      } else {
        element.type = 'chlid';
      }
    });
    schemeTable_data_1.value = data;
    reload_1();
  }

  // 删除表格内的一条数据
  function table_delete(num: number, record) {
    if (num === 1) {
      // 筛选
      const data = schemeTable_data_1.value.filter((t) => {
        return t.id != record.id;
      });
      // 删除的是主键，默认第一条是主键
      if (primaryKey.value === record.id && data.length != 0) {
        primaryKey.value = data[0].id;
        data[0].type = 'main';
      }
      // 全部删除时，主键设为null
      if (data.length === 0) {
        primaryKey.value = null;
      }
      schemeTable_data_1.value = data;
      reload_1();
    }
    if (num === 2) {
      // 筛选
      const data = schemeTable_data_2.value.filter((t) => {
        return t.id != record.id;
      });
      schemeTable_data_2.value = data;
      reload_2();
    }
    if (num === 3) {
      if (record.type === 'main') {
        createMessage.warn('主语句【' + record.name + '】无法删除');
      } else {
        const data = schemeTable_data_3.value.filter((t) => {
          return t.name != record.name;
        });
        schemeTable_data_3.value = data;
        reload_3();
      }
    }
  }

  // 第三个表格打开
  async function openViewModal() {
    openView(true);
  }
  // sql视图表赋值
  async function fun_viewdata(formdata) {
    if (!formdata) {
      return;
    }

    const data = getDataSource_3() || [];

    let sqlData = {};
    // 表的字段和关联字段
    const columns = [];
    const relationFieldOptions = [];

    if (data.length != 0) {
      data.columns.forEach((element) => {
        relationFieldOptions.push({
          key: element,
          value: element,
          label: element,
        });
      });
    }
    formdata.columns.forEach((element) => {
      columns.push({
        name: element,
      });
      if (relationFieldOptions.length === 0) {
        relationFieldOptions.push({
          key: element,
          value: element,
          label: element,
        });
      }
    });
    sqlData.relationField = null;
    sqlData.relationFieldOptions = relationFieldOptions;
    sqlData.columns = columns;
    // 表名
    sqlData.name = formdata.dbcode;
    // sql
    sqlData.sql = formdata.sql;
    // type
    if (data.length === 0) {
      sqlData.type = 'main';
    } else {
      sqlData.type = 'chlid';
    }
    // 操作
    sqlData.action = null;

    data.push(sqlData);
    schemeTable_data_3.value = data;
    reload_3();
  }
  function showSqlModal(record) {
    openView(true, { record });
  }

  // 获取当前的info和scheme
  async function getInfoAndScheme() {
    // try {

    return query;
  }

  // 暂存
  async function addAndUpdateFormInfoAndScheme() {
    // let query = getInfoAndScheme();

    // if (query) {
    //   console.log(query);
    //   console.log(query.info);
    console.log('暂存');

    let infoValues = await getFieldsValue();
    let schemeValues1 = null;
    let schemeValues2 = null;
    let schemeValues3 = null;
    if (infoValues.formType === 0) {
      schemeValues1 = await getDataSource_1();
      schemeValues2 = await getDataSource_2();
    }
    if (infoValues.formType === 1) {
      schemeValues3 = await getDataSource_3();
    }

    // 用于scheme的字段;
    var scheme_json = {};
    scheme_json.dbcode = infoValues.dbCode;
    delete infoValues.dbCode;

    // 传输数据修改格式和填补部分空缺
    if (infoValues.formType === 0) {
      var db = [];
      schemeValues1.forEach((element) => {
        var db_temp = {};
        db_temp.id = element.id;
        db_temp.tableName = element.tableName;
        db_temp.description = element.description;
        db_temp.type = element.type;
        if (element.type === 'chlid') {
          db_temp.field = element.field;
          db_temp.relationName = element.relationName;
          db_temp.relationField = element.relationField;
        }
        if (element.type === 'main') {
          delete db_temp.field;
          delete db_temp.relationName;
          delete db_temp.relationField;
        }
        db.push(db_temp);
      });
      scheme_json.db = db;

      var rdb = [];
      schemeValues2.forEach((element) => {
        var rdb_temp = {};
        rdb_temp.id = element.id;
        rdb_temp.tableName = element.tableName;
        rdb_temp.description = element.description;
        rdb_temp.fname = element.fname;
        rdb_temp.cfield = element.cfield;
        rdb_temp.field = element.field;
        rdb_temp.relationName = element.relationName;
        rdb_temp.relationField = element.relationField;
        rdb.push(rdb_temp);
      });
      scheme_json.rdb = rdb;
    }
    if (infoValues.formType === 1) {
      var db = [];
      schemeValues3.forEach((element) => {
        var db_temp = {};
        db_temp.id = element.id;
        db_temp.type = element.type;
        db_temp.name = element.name;
        db_temp.sql = element.sql;
        db_temp.columns = element.columns;
        console.log(element);

        if (element.type != 'main') {
          db_temp.relationField = element.relationField;
        }
        db.push(db_temp);
      });
      scheme_json.db = db;
      scheme_json.rdb = [];
    }
    if (infoValues.type === null || infoValues.type === undefined) {
      infoValues.type = 2;
    }
    if (infoValues.enabledMark) {
      infoValues.enabledMark = 1;
    } else {
      infoValues.enabledMark = 0;
    }

    // 参数;
    var info = infoValues;
    var scheme = {};
    scheme.scheme = JSON.stringify(scheme_json);

    var query = {
      info: info,
      scheme: scheme,
    };
    if (query.info.id) {
      await functionUpdateForm(query);
    } else {
      await functionAddForm(query);
    }
    // }
  }

  // 编辑设置值
  async function setInfoAndScheme(record) {
    // info
    const info = record.info;
    info.enabledMark = info.enabledMark === 1 ? true : false;
    info.dbcode = 'lrsystemdb';
    setFieldsValue(info);

    // scheme
    const scheme = record.scheme.scheme;
    let scheme_json = JSON.parse(scheme);
    if (info.formType === 0) {
      let tableName1 = null;
      let tableName2 = null;

      scheme_json.db.forEach((element) => {
        tableName1 = (tableName1 ? tableName1 + ',' : '') + element.tableName;
      });
      var query = {
        dbcode: 'lrsystemdb',
        tableNames: tableName1,
      };
      allData1 = await function_Get_GetForms(query);

      scheme_json.rdb.forEach((element) => {
        tableName2 = (tableName2 ? tableName2 + ',' : '') + element.tableName;
      });
      query = {
        dbcode: 'lrsystemdb',
        tableNames: tableName2,
      };
      allData2 = await function_Get_GetForms(query);

      let data1 = table1_setSelect(allData1, scheme_json.db);
      let data2 = table2_setSelect(allData1, allData2, scheme_json.rdb);

      schemeTable_data_1.value = data1;
      schemeTable_data_2.value = data2;
      reload_1();
      reload_2();
    }
    if (info.formType === 1) {
      schemeTable_data_3.value = scheme_json.db;
      let relationFieldOptions = [];
      if (schemeTable_data_3.value[0].columns) {
        schemeTable_data_3.value[0].columns.forEach((element) => {
          relationFieldOptions.push({
            key: element.name,
            value: element.name,
            label: element.name,
          });
        });
      }
      schemeTable_data_3.value.forEach((element) => {
        element.relationFieldOptions = relationFieldOptions;
      });
      // reload_3();
    }
  }
  // 下一步
  async function customSubmitFunc() {
    try {
      let values = getInfoAndScheme();
      console.log('values', values);

      emit('next', values);
    } catch (error) {
      //
    }
  }
</script>
<style lang="less" scoped>
  .step1 {
    &-form {
      width: 450px;
      margin: 0 auto;
    }

    h3 {
      margin: 0 0 12px;
      color: @text-color-base;
      font-size: 16px;
      line-height: 32px;
    }

    h4 {
      margin: 0 0 4px;
      color: @text-color-base;
      font-size: 14px;
      line-height: 22px;
    }

    p {
      color: @text-color-base;
    }
  }

  .pay-select {
    width: 20%;
  }

  .pay-input {
    width: 70%;
  }
</style>
