<template>
  <a-modal
    v-model:open="props.openModal"
    :title="getTitle"
    style="top: 50px"
    :width="1200"
    :maskClosable="false"
    @ok="handleOk"
    @cancle="handleCancle"
  >
    <template #closeIcon>
      <CloseOutlined :style="{ fontSize: '20px' }" @click="handleCancle" />
    </template>
    <template #footer>
      <a-button v-if="!isDetail" @click="handleCancle">取消</a-button>
      <a-button v-if="!isDetail" type="primary" @click="handleOk">确认</a-button>
    </template>
    <div class="box-container">
      <div class="flex mb-3">
        <div class="tab-label"><span class="red">*</span>表名：</div>
        <a-input
          v-model:value="tableName"
          placeholder="请输入表名"
          :status="!/^(?!^\d+$)[a-z0-9_]+$/.test(tableName) ? 'error' : ''"
          :disabled="isDetail"
        />
      </div>
      <p style="color: #ff0000; font-size: 12px" v-if="!/^(?!^\d+$)[a-z0-9_]+$/.test(tableName)">
        使用小写字母、数字、下划线的组合，且不得以数字开头
      </p>
      <div class="flex mb-3">
        <div class="tab-label">注释：</div>
        <a-input v-model:value="tableNote" placeholder="请输入注释" :disabled="isDetail" />
      </div>
    </div>
    <BasicTable class="w-3/4 xl:w-5/5" @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleAdd" v-if="!isDetail"> 新增 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'shpField' && !isDetail">
          <a-input
            v-model:value="record.shpField"
            placeholder="请输入Shp原始字段"
            @change="record.enName = record.shpField.toLowerCase()"
          />
        </template>
        <template v-if="column.key === 'type' && !isDetail">
          <a-select
            style="width: 100%"
            v-model:value="record.type"
            :options="typeOptions"
            placeholder="请选择数据类型"
            @change="
              ['text', 'bool', 'data', 'geometry(GEOMETRY)'].includes(record.type)
                ? (record.length = 0)
                : 'varchar' == record.type
                  ? (record.length = 255)
                  : (record.length = 10)
            "
          />
        </template>
        <template v-if="column.key === 'length' && !isDetail">
          <a-input-number
            v-model:value="record.length"
            :min="0"
            placeholder="请输入数据长度"
            :disabled="['text', 'bool', 'data', 'geometry(GEOMETRY)'].includes(record.type)"
          />
        </template>
        <template v-if="column.key === 'enName' && !isDetail">
          <span class="content-full">
            <a-input
              v-model:value="record.enName"
              placeholder="请输入英文名称"
              :status="
                !/^[a-z_][a-z0-9_]*$/.test(record.enName) || checkRepeat(record.enName)
                  ? 'error'
                  : ''
              "
              @change="record.enName = record.enName.toLowerCase()"
            />
            <p
              :style="{
                color: '#ff0000',
                fontSize: checkRepeat(record.enName) == '' ? '0px' : '12px',
              }"
            >
              {{ checkRepeat(record.enName) }}
            </p>
          </span>
        </template>
        <template v-if="column.key === 'chName' && !isDetail">
          <a-input v-model:value="record.chName" placeholder="请输入中文名称" />
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="link" style="color: red" @click="handleDelete(record)">删除</a-button>
        </template>
      </template>
    </BasicTable>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, defineEmits, watch } from 'vue';
  import { CloseOutlined } from '@ant-design/icons-vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { columns, columns_isDetail } from './modal.data';
  import { useMessage } from '@/hooks/web/useMessage';
  // api
  import { createPicTable, updateTable, CheckTableExist } from '@/api/database/index';
  import { getLoad } from '@/api/sys/sysDataItemDetail';

  const props = defineProps(['isUpdate', 'isDetail', 'openModal', 'record']);
  const emit = defineEmits(['submit']);
  const { createMessage } = useMessage();

  const tableName: any = ref('');
  const tableNote: any = ref('');
  const getTitle: any = ref('');
  const tableColumns: any = ref([]);
  const typeOptions: any = ref([
    { label: '字符串 varchar', value: 'varchar' },
    { label: '时间 date', value: 'date' },
    { label: '空间类型 geometry(GEOMETRY)', value: 'geometry(GEOMETRY)' },
    { label: '长文本 text', value: 'text' },
    { label: '数字 int8', value: 'int8' },
    { label: '是否 bool', value: 'bool' },
  ]);

  watch(
    () => props.openModal,
    () => {
      if (props.openModal) {
        // 新增
        if (!props.record) {
          getTitle.value = '新增';
          tableName.value = null;
          tableNote.value = null;
          setTimeout(() => {
            setTableData([]);
            handleAdd(1);
            reload();
          }, 100);
        } else {
          // 编辑、详情
          getTitle.value = '详情';
          tableName.value = props.record.tableName;
          tableNote.value = props.record.tableNote;
          const lines = props.record.columnJson.split(':');
          let arr: any = [];
          for (const line of lines) {
            const i = line.split(',');
            arr.push({
              id: new Date().getTime(),
              shpField: i[0],
              type: i[1],
              length: ['text', 'bool', 'data', 'geometry(GEOMETRY)'].includes(i[1]) ? 0 : 255,
              enName: i[0].toLowerCase(),
              chName: i[2],
              isOldColumn: true,
            });
          }
          setTableData(arr);
          reload();
        }
        // 详情隐藏按钮
        if (props.isDetail) {
          tableColumns.value = columns_isDetail;
        } else {
          tableColumns.value = columns;
        }
      }
    },
  );

  // 表格
  const [registerTable, { reload, setTableData, getDataSource }] = useTable({
    rowKey: '',
    columns: tableColumns,
    formConfig: {
      labelWidth: 120,
    },
    useSearchForm: false,
    showTableSetting: false,
    showIndexColumn: true,
    bordered: true,
    canResize: true,
    maxHeight: 500,
    pagination: false,
    handleSearchInfoFn(info) {
      return info;
    },
  });
  // 新增
  function handleAdd(num = 0) {
    let viesObj: any = getDataSource() || [];
    viesObj.push({
      id: new Date().getTime() + num,
      shpField: null,
      type: null,
      length: null,
      enName: null,
      chName: null,
    });
    setTableData(viesObj);
    reload();
  }
  // 删除
  function handleDelete(record: Recordable) {
    let arr = getDataSource();
    let newArr: any = [];
    arr.forEach((item) => {
      if (item.id !== record.id) {
        newArr.push(item);
      }
    });
    setTableData(newArr);
    reload();
  }
  // 使用小写字母、数字、下划线的组合，且不得以数字开头
  // 筛查重复英文名称
  function checkRepeat(enName) {
    let erroeMessage = '';
    if (enName != '' && enName != null) {
      let sortArr: any = getDataSource().map((item) => item.enName);
      if (sortArr.filter((item) => item == enName).length > 1) {
        erroeMessage = '英文名称不能重复';
      }
      if (!/^[a-z_][a-z0-9_]*$/.test(enName)) {
        erroeMessage = '使用小写字母、数字、下划线的组合，且不得以数字开头';
      }
    } else {
      erroeMessage = '';
    }
    return erroeMessage;
  }
  // 提交
  async function handleOk() {
    // 检测：表名
    if (!tableName.value) {
      createMessage.warn('表名是必填项!');
      return;
    }
    // 删除两端空格、制表符和换行符
    tableName.value = tableName.value.trim();
    // 检测：数据库表名的命名规则
    if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName.value)) {
      createMessage.warn('表名不符合数据库表名的命名规则!');
      return;
    }
    // 检测：数据库是否有此表
    let query: any = { tableName: tableName.value };
    let res = await CheckTableExist(query);
    if (res) {
      createMessage.warn('数据库已有此表名!');
      return;
    }
    let arr = getDataSource();
    // 检测：字段行
    if (!arr || arr.length == 0) {
      createMessage.warn('至少输入一行字段!');
      return;
    }
    let flag = true;
    let sortArr: any = [];
    if (arr) {
      arr.forEach((item) => {
        if (flag) {
          // 检测：字段名和字段类型不为空
          if (item.enName == null || item.enName == '' || item.type == null || item.type == '') {
            createMessage.warn('英文名称和数据类型都是必填项!');
            flag = false;
          }
          // 检测：数据库字段名的命名规则
          if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(item.enName)) {
            createMessage.warn('英文名称不符合数据库字段名的命名规则!');
            flag = false;
          }
          // 检测：备注不能含有英文字符的,和:
          if (item.chName && (item.chName.indexOf(':') > -1 || item.chName.indexOf(',') > -1)) {
            createMessage.warn('中文名称内不能含有英文字符的【,】和【:】');
            flag = false;
          }
        }
        // 筛查重复英文名称
        sortArr.push(item.enName);
      });
    }
    // 筛查重复英文名称
    if (flag && sortArr.length != [...new Set(sortArr)].length) {
      createMessage.warn('英文名称有重复项');
      flag = false;
    }
    // 无错误才能继续进行
    if (flag) {
      let newArr: any = [];
      arr.forEach((item) => {
        console.log(item);
        newArr.push({
          shpField: item.shpField,
          type: item.type,
          length: item.length,
          name: item.enName,
          explanation: item.chName,
        });
      });
      const param: any = {
        tableName: tableName.value,
        tableNote: tableNote.value,
        tableInfos: newArr,
      };
      // console.log('param', param);
      if (props.isUpdate) {
        updateTable(param).then((res: Recordable) => {
          console.log('res', res);
          setTableData([]);
          tableName.value = null;
          tableNote.value = null;
          emit('submit');
        });
      } else {
        createPicTable(param).then((res: Recordable) => {
          console.log('res', res);
          setTableData([]);
          tableName.value = null;
          tableNote.value = null;
          emit('submit');
        });
      }
    }
  }
  // 关闭
  function handleCancle() {
    setTableData([]);
    emit('submit');
  }
  // 字典类型
  async function getDataTypeOptions() {
    getLoad({ code: 'clounm_type' }).then((res) => {
      if (res) {
        typeOptions.value = [];
        res?.forEach((item) => {
          typeOptions.value.push({
            label: item.itemName + ' ' + item.itemValue,
            value: item.itemValue,
          });
        });
      }
    });
  }

  onMounted(() => {
    getDataTypeOptions();
  });
</script>
<style>
  .box-container {
    width: 80%;
    margin: 20px auto 0;
  }
  .tab-label {
    width: 100px;
    display: flex;
    align-items: center;
    justify-content: end;
  }
  .red {
    color: red;
  }
  .content-full {
    white-space: pre-wrap;
    word-break: break-all;
    overflow-wrap: break-word;
    max-width: 100%;
    display: block;
  }
</style>
