<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTree
      class="w-1/4 m-4 mr-0 overflow-hidden bg-white xl:w-1/5"
      v-if="treeVisible"
      ref="asyncExpandTreeRef"
      :title="treeTitle"
      toolbar
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      loadData
      :actionList="actionList"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'value', title: 'label' }"
      :defaultExpandAll="true"
      @select="handleSelect"
    />
    <div style="display: flex; width: 100%">
      <div
        class="table-container form-call-table"
        :style="`${haveMap ? `width:${100 - mapSetData.width}%;` : 'width:100%'}`"
      >
        <BasicTable @register="registerTable" @row-click="handRowClick" :searchInfo="searchInfo">
          <template #toolbar>
            <div v-for="(item, index) in btnArr" :key="index">
              <a-button :type="item.class" @click="handleClickForm(item.prop)">{{
                item.label
              }}</a-button>
            </div>
          </template>
          <template #bodyCell="{ column, record }">
            <template
              v-if="
                ['TreeSelect', 'Cascader', 'CheckboxGroup', 'Transfer', 'RangePicker'].includes(
                  column.component,
                )
              "
            >
              {{ dataModification(column, record) }}
            </template>
          </template>
        </BasicTable>

        <!-- <ShowFormModal
          v-if="openShowFormModal"
          :showFormModalData="showFormModalData"
          :mapgemoList="mapgemoList"
          :formData="formData"
          :geometryForm="geometryForm"
          :MapboxComponent="MapboxComponent"
          :mapSetData="mapSetData"
          :haveMap="haveMap"
          @setSelectedSubTableDataId="setSelectedSubTableDataId"
          @closeShowFormModal="closeShowFormModal"
          @success="submitsuccess"
        /> -->
        <div class="map-form-container" v-if="mapFormShow">
          <MapFormModal v-if="mapFormShow" @clsoeMapForm="clsoeMapForm" :data="mapFormData">
            <template #detail>
              <infoCallModal :data="mapFormData" />
            </template>
          </MapFormModal>
        </div>
      </div>
      <div
        v-if="haveMap"
        class="form-call-showMap"
        :style="`width:${mapSetData.width}%;height:calc(100vh - 78px) `"
      >
        <MapboxMap
          :mapConfig="mapSetData"
          :layers="layers"
          :location="location"
          @handlerDrawComplete="handlerDrawComplete"
          @mapOnLoad="mapOnLoad"
          ref="MapboxComponent"
        />
      </div>
    </div>

    <CallModal @success="submitsuccess" @register="registerModal" />
    
    <a-modal
      width="80%"
      v-model:open="infoCallModalOpen"
      title="详情"
      :footer="null"
      :maskClosable="true"
      :destroyOnClose="true"
      @cancel="closeModal"
    >
      <div class="content">
        <InfoCallModal :data="infoCallModalData" />
      </div>
    </a-modal>
    <a-modal
      v-model:open="importOpen"
      title="导入"
      :footer="null"
      @cancel="importOpen = false"
      :destroyOnClose="true"
    >
      <ImportModal v-model:open="importOpen" :paramsId="paramsId" :pkey="pkey" />
    </a-modal>

    <a-modal
      width="100%"
      wrap-class-name="full-modal"
      v-model:open="previewOpen"
      title="表单"
      :destroyOnClose="true"
    >
      <template #footer> </template>
      <CreateFlow
        ref="posRef"
        :code="flowCode"
        @closeModel="closeMolder"
        :flowFormData="flowFormData"
        :isUpdate="isUpdate"
      />
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { onMounted, ref, nextTick, unref, h, reactive, defineAsyncComponent } from 'vue';
  import { useRoute } from 'vue-router';
  import { BasicTable, useTable, BasicColumn, FormSchema } from '@/components/Table';
  import { BasicTree, TreeItem, TreeActionItem, TreeActionType } from '@/components/Tree';
  import {
    getFormsDesignData,
    getFormsPageData,
    delFormsData,
    getFormData,
    exportForm,
  } from '@/api/formrender/index';
  import { getOutKeyList } from '@/api/formdesign/index';
  import { getGeom } from '@/api/sys/layerManagement';
  import { PageWrapper } from '@/components/Page';
  import { cloneDeep } from 'lodash-es';
  import { IFormConfig } from '../../form-design/typings/v-form-component';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import CallModal from './CallModal.vue';
  import InfoCallModal from './InfoCallModal/index.vue';
  import MapFormModal from './MapForm.vue';
  import CreateFlow from './CreateFlow.vue';
  // import MapboxMap from '@/components/MapboxMaps/MapComponent.vue'
  import ShowFormModal from './ShowFormModal/index.vue';
  import { v4 as uuidv4 } from 'uuid';
  import { changeCardStructure, cardNestStructure } from '@/views/demo/onlineform/util.ts';
  import { useFormCallStore } from '@/store/modules/formCall.ts';
  import ImportModal from './ImportModal/index.vue';
  const MapboxMap = defineAsyncComponent(() => import('@/components/MapboxMaps/MapComponent.vue'));
  const mapFormShow = ref<boolean>(false);
  const mapFormData = ref<Object>({});
  const { createConfirm, createMessage } = useMessage();
  const route = useRoute();
  const formCallStore = useFormCallStore();
  const btnArr: any = ref([
    { label: '新增', prop: 'Add', class: 'primary' },
    { label: '编辑', prop: 'Edit', class: 'success' },
    { label: '删除', prop: 'Delete', class: 'error' },
    { label: '详情', prop: 'Details', class: 'default' },
  ]);
  const mapSetData = ref({
    width: 100,
  });
  const importOpen = ref(false);
  const pkey = ref('');
  const infoCallModalOpen = ref(false);
  const infoCallModalData = ref({});
  const selectedSubTableDataId = ref('');
  const formData = ref([]);
  const mapgemoList = ref([]);
  const MapboxComponent = ref();
  const openShowFormModal = ref(false);
  const haveMap = ref(false);
  const showFormModalData = ref({});
  const treeTitle: any = ref('树形');
  const treeVisible: any = ref(false);
  const paramsId: any = ref();
  const codeId: any = ref();
  const designData: any = ref();
  const searchInfo: any = ref({});
  const addParamsArr: any = ref([]);
  const paramsCode = route.query.code;
  const callColumns: BasicColumn[] = [];
  const searchFormSchema: FormSchema[] = [];
  const btnList: any = ref([]);
  const treeData = ref<TreeItem[]>([]);
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  const actionList: TreeActionItem[] = [];
  const previewOpen = ref(false); //是否打开流程发起弹窗
  const flowCode = ref(''); //流程code
  const flowFormData = ref({}); //编辑时表单的数据
  const isUpdate = ref(false); //是否是编辑
  const infoUseSubTableData = ref();
  const infoUseMainTableData = ref({});
  const exportParams: any = ref();
  // 展示的图层列表
  const layers = reactive();
  const geometryForm = ref({});

  // 图层定位数据
  const location = reactive([118.556717, 35.80391]);
  if (paramsCode == '数据统计') {
    // searchFormSchema = [
    //   {
    //     field: 'typeid',
    //     component: 'ApiSelect',
    //     label: '企业类型',
    //     colProps: { span: 6 },
    //     componentProps: () => {
    //       return {
    //         // api: getLoadCaseType, // 接口
    //         // 接口参数
    //         resultField: 'result',
    //         labelField: 'itemName',
    //         valueField: 'itemDetailId',
    //       };
    //     },
    //   },
    //   {
    //     field: 'deal_username',
    //     component: 'Input',
    //     label: '面积（m²）',
    //     colProps: { span: 6 },
    //   },
    //   {
    //     field: '[report_start_time, report_end_time]',
    //     component: 'RangePicker',
    //     label: '成立时间',
    //     componentProps: {
    //       format: 'YYYY-MM-DD',
    //       placeholder: ['开始时间', '结束时间'],
    //     },
    //     colProps: { span: 8 },
    //   },
    //   {
    //     field: 'is_intact',
    //     component: 'Select',
    //     label: '是否纳税',
    //     colProps: { span: 6 },
    //     defaultValue: 1,
    //     componentProps: {
    //       options: [
    //         { label: '未判读', value: 0, key: '0' },
    //         { label: '已提交', value: 1, key: '1' },
    //         { label: '已关闭', value: 99, key: '99' },
    //         { label: '全部', value: null, key: '' },
    //       ],
    //     },
    //   },
    // ];
  } else if (paramsCode == '数据审核') {
    // searchFormSchema = [
    //   {
    //     field: 'typeid',
    //     component: 'ApiSelect',
    //     label: '企业类型',
    //     colProps: { span: 6 },
    //     componentProps: () => {
    //       return {
    //         // api: getLoadCaseType, // 接口
    //         // 接口参数
    //         resultField: 'result',
    //         labelField: 'itemName',
    //         valueField: 'itemDetailId',
    //       };
    //     },
    //   },
    //   {
    //     field: 'deal_username',
    //     component: 'Input',
    //     label: '面积（m²）',
    //     colProps: { span: 6 },
    //   },
    //   {
    //     field: '[report_start_time, report_end_time]',
    //     component: 'RangePicker',
    //     label: '成立时间',
    //     componentProps: {
    //       format: 'YYYY-MM-DD',
    //       placeholder: ['开始时间', '结束时间'],
    //     },
    //     colProps: { span: 8 },
    //   },
    //   {
    //     field: 'is_intact',
    //     component: 'Select',
    //     label: '是否已审核',
    //     colProps: { span: 6 },
    //     defaultValue: 1,
    //     componentProps: {
    //       options: [
    //         { label: '未判读', value: 0, key: '0' },
    //         { label: '已提交', value: 1, key: '1' },
    //         { label: '已关闭', value: 99, key: '99' },
    //         { label: '全部', value: null, key: '' },
    //       ],
    //     },
    //   },
    // ];
  }
  const [registerModal, { openModal }] = useModal();

  const [registerMapFormModal, { openModal: openMapFormModal }] = useModal();

  const [registerTable, { reload, setColumns, getSelectRows, clearSelectedRowKeys }] = useTable({
    title: '表单列表',
    api: getFormsPageData,
    // rowKey: 'f_Id',
    columns: callColumns,
    formConfig: {
      labelWidth: 120,
      showAdvancedButton: false,
      schemas: searchFormSchema,
    },
    rowSelection: {
      type: 'radio',
    },
    showIndexColumn: false,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    beforeFetch: (data) => {
      // 接口请求前 参数处理
      const querys = JSON.parse(JSON.stringify(data));
      delete querys.page;
      delete querys.limit;
      var temp = {
        id: paramsId.value,
        mid: codeId.value,
        paginationInputDto: {
          page: data.page,
          rows: data.limit,
        },
        queryJson: JSON.stringify(querys),
      };
      exportParams.value = temp;
      return temp;
    },
    afterFetch: () => {
      const rel = designData.value;
      console.log('rel', rel);
      let arr: any = [];
      if (rel.primaryKey) {
        rel.db.forEach((val) => {
          let params = {
            dbCode: rel.dbCode,
            tableNames: val.name,
          };
          let chlidKey: any = ref();
          if (val.type === 'chlid') {
            getOutKeyList(params).then((res: Recordable) => {
              console.log('ressss', res);
              if (res[0]) {
                res[0].db_codecolumnsList.forEach((item) => {
                  if (item.isPrimaryKey == 1) {
                    chlidKey.value = item.dbColumnName;
                  }
                });
              }
            });
          }
          setTimeout(() => {
            console.log('chlidKey', chlidKey.value);
          }, 500);

          if (rel.formInfo.schemas.length > 1) {
            rel.formInfo.schemas.forEach((item) => {
              if (
                item.componentProps.dataTable == val.name &&
                rel.primaryKey == item.componentProps.fieldName
              ) {
                arr.push({
                  type: val.type,
                  field: item.field,
                });
              }
              if (
                val.type == 'chlid' &&
                val.name == item.componentProps.dataTable &&
                chlidKey.value == item.componentProps.fieldName
              ) {
                arr.push({
                  type: val.type,
                  field: item.field,
                });
              }
            });
          } else {
            rel.formInfo.schemas[0].componentProps.options.forEach((opt) => {
              opt.children.forEach((item) => {
                if (
                  item.componentProps.dataTable == val.name &&
                  rel.primaryKey == item.componentProps.fieldName
                ) {
                  item.type = val.type;
                  arr.push({
                    type: val.type,
                    field: item.field,
                  });
                }
                if (
                  val.type == 'chlid' &&
                  val.name == item.componentProps.dataTable &&
                  chlidKey.value == item.componentProps.fieldName
                ) {
                  item.type = val.type;
                  arr.push({
                    type: val.type,
                    field: item.field,
                  });
                }
              });
            });
          }
        });
      }
      console.log('after', arr);
      addParamsArr.value = [...new Set(arr)];
    },
    handleSearchInfoFn(info) {
      return info;
    },
  });

  const formConfig = ref<IFormConfig>({
    // 表单配置
    schemas: [],
    layout: 'horizontal',
    labelLayout: 'flex',
    labelWidth: 100,
    labelCol: {},
    wrapperCol: {},
    currentItem: {
      component: '',
      componentProps: {},
    },
    activeKey: 1,
    status: 'Add',
    beforeSetData: '',
    afterValidateForm: '',
    afterSaveEvent: '',
    changeDataEvent: '',
  });

  interface GeomParams {
    TableName: string;
    FieldName: string;
    FiledValue: Array<any>;
  }

  const handleClickForm = (status) => {
    const config = cloneDeep(formConfig.value);
    const rows = getSelectRows();
    const query: any = ref({
      id: paramsId.value,
      key: designData.value.primaryKey,
      // key: 'f_id',
      keyValue: null,
    });
    const str: any = ref();
    // const str: any = ref('_input_guid_43');
    addParamsArr.value.forEach((item) => {
      if (item.type == 'main') {
        str.value = item.field;
      }
    });

    if (rows.length > 0) {
      query.value.keyValue = rows[0][str.value];
    }
    console.log('config', config);
    switch (status) {
      case 'Add':
        btnList.value.forEach((element) => {
          if (element.prop === 'Add' && element.isWFlow) {
            flowCode.value = element.wFlowCode;
          }
        });
        if (flowCode.value == '') {
          formData.value = [];
          let toProps = {
            isDetail: false,
            isUpdate: false,
            tab: config.schemas,
            query: query.value,
            addParams: addParamsArr.value,
            btnList: btnList.value,
            beforeSetData: config.beforeSetData,
            afterValidateForm: config.afterValidateForm,
            afterSaveEvent: config.afterSaveEvent,
            changeDataEvent: config.changeDataEvent,
          };
          if (haveMap.value) {
            // showFormModalData.value = toProps;
            // openShowFormModal.value = true;
            openModal(true, toProps);
            mapgemoList.value = [];
            mapSetData.value.isAllowAddPolygon && MapboxComponent.value.handlerDraw(status);
          } else {
            openModal(true, toProps);
          }
        } else {
          flowFormData.value = {};
          previewOpen.value = true;
          isUpdate.value = false;
        }

        break;
      case 'Edit':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据进行编辑');
        }
        // console.log('rowsrows',formConfig,rows);

        btnList.value.forEach((element) => {
          if (element.prop === 'Edit' && element.isWFlow) {
            flowCode.value = element.wFlowCode;
          }
        });
        if (flowCode.value == '') {
          let toProps = {
            isDetail: false,
            isUpdate: true,
            tab: config.schemas,
            record: rows[0],
            recordChildren: formData.value,
            query: query.value,
            btnList: btnList.value,
            beforeSetData: config.beforeSetData,
            afterValidateForm: config.afterValidateForm,
            afterSaveEvent: config.afterSaveEvent,
            changeDataEvent: config.changeDataEvent,
            infoUseMainTableData: infoUseMainTableData.value,
            infoUseSubTableData: infoUseSubTableData.value,
          };
          if (haveMap.value) {
            // showFormModalData.value = toProps;
            // openShowFormModal.value = true;
            // openMapFormModal(true,toProps);
            // mapFormShow.value = true;
            // mapFormData.value = toProps;
            // MapboxComponent.value.handlerDraw(
            //   status,
            //   mapgemoList.value,
            //   mapSetData.value?.isAllowEditPolygon,
            // );
            // openModal(true, toProps);
            // previewOpen.value = true;
            // flowFormData.value = rows[0];
            // isUpdate.value = true;
            openModal(true, toProps);
          } else {
            openModal(true, toProps);
          }
        } else {
          previewOpen.value = true;
          flowFormData.value = rows[0];
          isUpdate.value = true;
        }
        break;
      case 'Delete':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据进行删除');
        }
        createConfirm({
          iconType: 'info',
          title: '删除',
          content: '确定要删除该条数据？',
          onOk: async () => {
            delFormsData(query.value).then((res) => {
              if (res) {
                createMessage.success('删除成功', 2);
                setTimeout(() => {
                  clearSelectedRowKeys();
                  reload();
                }, 100);
              } else {
                createMessage.error('删除失败', 2);
              }
            });
          },
        });
        break;
      case 'Details':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据查看详情');
        }
        let toProps = {
          isDetail: true,
          isUpdate: false,
          tab: config.schemas,
          record: rows[0],
          recordChildren: formData.value,
          query: query.value,
          btnList: btnList.value,
          infoUseMainTableData: infoUseMainTableData.value,
          infoUseSubTableData: infoUseSubTableData.value,
        };
        if (haveMap.value) {
          mapFormShow.value = true;
          mapFormData.value = toProps;
          // openMapFormModal(true,toProps);
          // showFormModalData.value = toProps;
          // openShowFormModal.value = true;
          // 根据ids获取图斑
          console.log(rows);
          console.log("formConfig");
          try {
            console.log('formConfig', formConfig);
            handlerShowGeomtrys(formConfig, rows[0]);
          } catch (e) {
            createMessage.error('当前数据没有图斑！');
          }
        } else {
          // openModal(true, toProps);
          infoCallModalOpen.value = true;
          infoCallModalData.value = toProps;
        }
        break;
      case 'Import':
        importOpen.value = true;
        break;
      case 'Export':
        let params = exportParams.value;
        params.code = paramsCode;
        console.log('params', params);
        exportForm(params).then((res) => {
          console.log('aaaa', res);
          const content = res;
          const blob = new Blob([content]);
          const fileName = '数据导出' + getToday() + '.xlsx';
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
          }
        });
        break;
      default:
        break;
    }
  };
  const chooseLayer = ref<string>('');
  const geomfield = ref<string>('');

  function getToday() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var dates = date.getDate();
    var time = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();

    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (dates >= 0 && dates <= 9) {
      dates = '0' + dates;
    }
    let datatime = year + '0' + month + '0' + dates + time + '0' + minutes + '0' + seconds;
    return datatime;
  }

  function findValue(obj, targetKey) {
    for (var key in obj) {
      if (typeof obj[key] === 'object') {
        // 如果当前值是对象，则递归调用findValue
        var result = findValue(obj[key], targetKey);
        if (result !== undefined && result == 'MapGeom') {
          return result;
        }
      } else if (key === targetKey && obj[key] == 'MapGeom') {
        // 如果当前键等于目标键，则返回对应的值
        chooseLayer.value = obj['mapSetData'].chooseLayer;
        geomfield.value = obj['field'];
        return obj[key];
      }
    }
  }

  async function handlerShowGeomtrys(currentNode, rows) {
    console.log('currentNode222', currentNode.value);
    findValue(currentNode.value.schemas, 'component');

    let info = currentNode.value.schemas?.find((item, index) => {
      return item.component.match(/mapgeom/i);
    });
    let layer: string = chooseLayer.value;
    // // let layer:string="drone_shp_data";
    // if(info){
    //   layer = info?.mapSetData?.chooseLayer
    // }
    if (!layer) {
      createMessage.error('图斑未绑定图层服务！');
      return;
    }
    let geomfiledValue = geomfield.value;
    let gids = '';
    try {
      // geomfiledValue = geomfiledValue.charAt(0).toLowerCase();
      geomfiledValue = geomfiledValue.charAt(0).toLowerCase() + geomfiledValue.slice(1);
      gids = rows[geomfiledValue];
      if (gids) {
        try {
          let getGeomPrams = {
            TableName: layer,
            FieldName: 'gid',
            FieldValue: gids?.split(","),
            page: 1,
            limit: 999,
            key: null,
          };
          await getGeom(getGeomPrams).then((res) => {
            let geoms = [];
            if (res) {
              if (res.items?.length > 0) {
                res.items.forEach((item, index) => {
                  let geom = {
                    key: item.gid,
                    mapgeom: item.geometry,
                  };
                  geoms.push(geom);
                });
              }
              MapboxComponent.value.handlerDraw('Details', geoms, false);
            } else {
              createMessage.error('当前数据没有图斑！');
            }
          });
        } catch (e) {
          createMessage.error('当前数据没有图斑！');
        }
      } else {
        createMessage.error('当前数据没有图斑！');
      }
    } catch {
      createMessage.error('获取图斑数据失败！');
    }
  }

  function handleSelect(selectedKeys: any, selected: any) {
    const rel = selected.node.dataRef;
    const obj: any = {};
    obj[rel.key] = rel.value;
    searchInfo.value = JSON.stringify(obj);
    reload();
  }

  function getPublicForm() {
    let params = {
      code: paramsCode,
    };

    getFormsDesignData(params).then((res: Recordable) => {
      let columnObj = JSON.parse(res.entity.scheme);
      let formObj = JSON.parse(res.formScheme.scheme);
      pkey.value = formObj.primaryKey;
      console.log('formObj', formObj);
      console.log('columnObj', columnObj);
      if (formObj.formInfo.tabList && formObj.formInfo.tabList.length > 0) {
        // 为使用字典字段的下拉组件的options赋值
        formObj.formInfo.tabList.forEach((childTab) => {
          childTab.schemas.forEach(async (item) => {
            if (item.component === 'Select' && item.dataType === '2') {
              item.componentProps.options = await formCallStore.getDictionaryOptions(item.dataCode);
            }
          });
        });
        // 将card嵌套起来
        formObj.formInfo.tabList = cardNestStructure(formObj.formInfo.tabList);
        const arr: any = [];
        formObj.formInfo.tabList.forEach((item, index) => {
          arr.push({
            label: item.text,
            value: index + 1,
            children: item.schemas,
          });
        });
        formObj.formInfo.schemas = [
          {
            component: 'Tabs',
            label: '选项卡',
            colProps: {
              span: 24,
            },
            field: 'Tabs',
            componentProps: {
              options: arr,
            },
            itemProps: {
              labelCol: {},
              wrapperCol: {},
            },
          },
        ];
      }
      if (formObj.formInfo.tabList && formObj.formInfo.tabList.length == 1) {
        formObj.formInfo.schemas = formObj.formInfo.tabList[0].schemas;
      }
      delete formObj.formInfo.tabList;
      // TODO 判断是否有地图
      let mapgeomData = columnObj.table?.maps;
      haveMap.value = mapgeomData?.isShowMap || false;
      if (haveMap.value) {
        mapSetData.value = mapgeomData || {
          isAllowAddPolygon: false,
          isAllowEditPolygon: false,
          isEnablePostionJump: false,
          width: 50,
          layerFields: {},
        };
      }
      codeId.value = res.entity.id;
      paramsId.value = res.formScheme.id;
      btnList.value = columnObj.table.btns;
      btnArr.value = columnObj.table.btns;
      if (columnObj.table.columns) {
        columnObj.table.columns.forEach((item) => {
          callColumns.push({
            title: item.label,
            dataIndex: item.key,
            // 用于表单列表数据修饰
            component: item.component,
          });
        });
      }
      if (columnObj.table.querys) {
        columnObj.table.querys.forEach((item) => {
          if (['Transfer'].includes(item.type)) {
            searchFormSchema.push({
              field: item.key,
              component: item.type,
              label: item.label,
              colProps: { span: 12 },
              componentProps: {
                render: (item) => `${item.title} ${item.description}`,
                ...item.componentProps,
              } || { options: item.options },
            });
          } else {
            searchFormSchema.push({
              field: item.key,
              component: item.type,
              label: item.label,
              colProps: { span: 6 },
              componentProps: item.componentProps || { options: item.options },
            });
          }
        });
      }
      callColumns.forEach((item) => {
        formObj.formInfo.schemas.forEach((val) => {
          if (item.dataIndex == val.field && val.componentProps.options) {
            item.customRender = ({ record }) => {
              const text: any = val.componentProps.options.filter(
                (price) => price.value == record[val.field],
              );
              if (text[0]) {
                return h(() => text[0].label);
              }
            };
          }
        });
      });
      setColumns(callColumns);
      reload();
      if (columnObj.left.options.length > 0) {
        treeData.value = columnObj.left.options;
        treeTitle.value = columnObj.left.title;
        treeVisible.value = true;
      } else {
        treeVisible.value = false;
      }
      designData.value = formObj;
      // 展开全部
      nextTick(() => {
        unref(asyncExpandTreeRef)?.expandAll(true);
      });
      formConfig.value.schemas = formObj.formInfo.schemas;
      // 表单脚本
      formConfig.value.beforeSetData = formObj.formInfo.beforeSetData;
      formConfig.value.afterValidateForm = formObj.formInfo.afterValidateForm;
      formConfig.value.afterSaveEvent = formObj.formInfo.afterSaveEvent;
      formConfig.value.changeDataEvent = formObj.formInfo.changeDataEvent;
    });
  }
  //弹窗确定后返回调用
  function submitsuccess() {
    reload();
    mapgemoList.value = [];
  }
  function closeMolder() {
    previewOpen.value = false;
    submitsuccess();
  }

  onMounted(() => {
    getPublicForm();
  });
  const closeShowFormModal = () => {
    openShowFormModal.value = false;
    // MapboxComponent.value.handlerCancleDraw();
    clearSelectedRowKeys();
    formData.value = [];
  };
  const handRowClick = (record) => {
    // todo 设置需要请求时请求
    // if(!haveMap.value) return
    let keyValue = null;
    Object.keys(record).forEach((key) => {
      if (key.indexOf('guid') !== -1) {
        keyValue = record[key];
      }
    });
    let params = {
      id: paramsId.value,
      key: designData.value.primaryKey,
      keyValue,
    };
    getFormData(params)
      .then((res) => {
        let childTableName = designData.value.db.find((item) => item.type === 'chlid')?.name;
        let mainTableName = designData.value.db.find((item) => item.type === 'main').name;
        let subTableData = res[childTableName]
          ? res[childTableName].map((item) => {
              return {
                ...item,
                key: uuidv4(),
                MapGeom: item.mapgeom,
              };
            })
          : [];
        formData.value = [...subTableData];
        infoUseSubTableData.value = res[childTableName]
          ? res[childTableName].map((item) => {
              return {
                ...item,
                key: uuidv4(),
              };
            })
          : [];
        res[mainTableName].forEach((item) => {
          infoUseMainTableData.value = { ...infoUseMainTableData.value, ...item };
        });
        mapgemoList.value = formData.value;
      })
      .catch((err) => {
        console.log('err', err);
      });
  };
  // 绘图完成返回geom
  const handlerDrawComplete = (geom) => {
    console.log('绘制完成返回的图斑', geom);
    formData.value.forEach((item) => {
      if (item.key === selectedSubTableDataId.value) {
        console.log(geom[0].value, 'geom[0].value');
        item.MapGeom = geom[0].value;
      }
    });
    mapgemoList.value = [...geom];

    // 处理geom保存表单
    mapgemoList.value?.forEach((item, index) => {
      geometryForm.value?.data.push(item.value);
    });
  };
  const mapOnLoad = (map) => {
    // const test_url =
    // map.addSource('street-border-source', {
    //   type: 'vector',
    //   tiles: [test_url],
    // });
    // map.addLayer({
    //   id: 'street-border',
    //   type: 'line',
    //   source: 'street-border-source',
    //   'source-layer': 'yishuixian',
    //   layout: {
    //     visibility: 'visible',
    //   },
    // });
  };
  const setSelectedSubTableDataId = (value) => {
    selectedSubTableDataId.value = value;
  };

  // 处理图斑数据新增、编辑、删除
  const handlerDealGeomtry = (status: string, features = null) => {
    // Add
    if (status == 'Add') {
      let geoms: string[] = [];

      mapgemoList.value?.forEach((item, index) => {
        console.log('mapgeoms', item);
      });
    }
    // Edit
    if (status == 'Edit') {
    }

    // Delete
    if (status == 'Delete') {
    }
  };

  const clsoeMapForm = () => {
    mapFormShow.value = false;
  };
  const closeModal = () => {
    infoCallModalOpen.value = false;
  };

  // 表单列表数据修饰
  const dataModification = (column, record) => {
    let res: any = '';
    if (column.component == 'TreeSelect') {
      searchFormSchema?.forEach((item: any) => {
        if (item.component && item.component == 'TreeSelect') {
          res = getTreeSelectLabel(res, item.componentProps.treeData, record[column.dataIndex]);
        }
      });
    } else if (column.component == 'Cascader') {
      searchFormSchema?.forEach((item: any) => {
        if (item.component && item.component == 'Cascader') {
          // 转成数组
          let CascaderData = JSON.parse(record[column.dataIndex]?.replace(/\r\n/g, '') || '[]');
          // 返回的结果
          let CascaderRes = {
            label: '',
            children: item.componentProps.options,
          };
          CascaderData?.forEach((value, value_index) => {
            if (value_index == 0) {
              CascaderRes = getCascaderLabel(value, CascaderRes);
              res = CascaderRes.label;
            } else {
              CascaderRes = getCascaderLabel(value, CascaderRes);
              res = res + ' / ' + CascaderRes.label;
            }
          });
        }
      });
    } else if (column.component == 'CheckboxGroup') {
      searchFormSchema?.forEach((item: any) => {
        if (item.component && item.component == 'CheckboxGroup') {
          item.componentProps.options?.forEach((op) => {
            // 转成数组
            let CheckboxGroupData = JSON.parse(
              record[column.dataIndex]?.replace(/\r\n/g, '') || '[]',
            );
            CheckboxGroupData?.forEach((CheckboxGroupData_item, index) => {
              if (op.value == CheckboxGroupData_item) {
                if (index == 0) {
                  res = op.label;
                } else {
                  res = res + ' | ' + op.label;
                }
              }
            });
          });
        }
      });
    } else if (column.component == 'Transfer') {
      searchFormSchema?.forEach((item: any) => {
        if (item.component && item.component == 'Transfer') {
          item.componentProps.dataSource?.forEach((ds) => {
            // 转成数组
            let TransferData = JSON.parse(record[column.dataIndex]?.replace(/\r\n/g, '') || '[]');
            TransferData?.forEach((TransferData_item, index) => {
              if (ds.key == TransferData_item) {
                if (index == 0) {
                  res = ds.title;
                } else {
                  res = res + '、' + ds.title;
                }
              }
            });
          });
        }
      });
    } else if (column.component == 'RangePicker') {
      // 转成数组
      let RangePickerData;
      if (typeof record[column.dataIndex] == 'string') {
        RangePickerData = JSON.parse(record[column.dataIndex]?.replace(/\r\n/g, '') || '[]');
      } else {
        RangePickerData = record[column.dataIndex];
      }
      RangePickerData?.forEach((RangePickerData_item, index) => {
        if (index == 0) {
          res = RangePickerData_item;
        } else {
          res = res + ' 至 ' + RangePickerData_item;
        }
      });
    } else {
      // console.log(1080);
      // console.log(column);
      // console.log(record);
      // console.log(searchFormSchema);
      res = record[column.dataIndex];
    }
    return res;
  };

  // 树形选择-表单列表数据修饰
  function getTreeSelectLabel(res, treeData, value) {
    treeData?.forEach((element) => {
      if (element.value == value) {
        res = element.label;
      }
      if (element.children) {
        res = getTreeSelectLabel(res, element.children, value);
      }
    });
    return res;
  }

  // 级联选择-表单列表数据修饰
  function getCascaderLabel(value, CascaderRes) {
    let res: any = {};
    CascaderRes.children.forEach((ch) => {
      if (ch.value == value) {
        res.label = ch.label;
        res.children = ch.children;
      }
    });
    return res;
  }
</script>
<style lang="less">
  .full-modal {
    .ant-modal {
      max-width: 100%;
      top: 0;
    }

    .ant-modal-content {
      height: calc(100vh);
    }

    .ant-modal-body {
      height: 85%;
    }
  }
  .table-container {
    position: relative;
  }
  .form-call-table {
    .ant-form {
      .ant-form-item-control-input-content {
        display: flex;
      }
    }
  }
  .form-call-showMap {
    width: 100%;
    background-color: #fff;
    z-index: 1;
  }

  .map-form-container {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    background: #fff;
    z-index: 999;
  }
  .content {
    padding: 30px;
    height: 750px;
    overflow: auto;
  }
</style>
