<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">
          <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>
        </BasicTable>
        <ShowFormModal
          v-if="openShowFormModal"
          :showFormModalData="showFormModalData"
          :mapgemoList="mapgemoList"
          :formData="formData"
          :MapboxComponent="MapboxComponent"
          :mapSetData="mapSetData"
          :haveMap="haveMap"
          @setSelectedSubTableDataId="setSelectedSubTableDataId"
          @closeShowFormModal="closeShowFormModal"
          @success="submitsuccess"
        />
      </div>
      <div
        v-if="haveMap"
        class="form-call-showMap"
        :style="`width:${mapSetData.width}%;height:calc(100vh - 78px) `"
      >
        <MapboxMap
          :layers="layers"
          :location="location"
          @handlerDrawComplete="handlerDrawComplete"
          @mapOnLoad="mapOnLoad"
          ref="MapboxComponent"
        />
      </div>
    </div>
    <CallModal @success="submitsuccess" @register="registerModal" />
    <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,
  } from '@/api/formrender/index';
  import { getOutKeyList } from '@/api/formdesign/index';
  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 CreateFlow from './CreateFlow.vue';
  // import MapboxMap from '@/components/MapboxMaps/MapComponent.vue'
  import ShowFormModal from './ShowFormModal/index.vue';
  import { v4 as uuidv4 } from 'uuid';

  const MapboxMap = defineAsyncComponent(() => import('@/components/MapboxMaps/MapComponent.vue'));

  const { createConfirm, createMessage } = useMessage();
  const route = useRoute();
  const btnArr: any = [
    { 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 selectedSubTableDataId = ref("")
  const formData = ref([]);
  const mapgemoList = ref([]);
  const MapboxComponent = ref();
  const openShowFormModal = ref(false);
  const haveMap = ref(true);
  const showFormModalData = ref({});
  const treeTitle: any = ref('树形');
  const treeVisible: any = ref(false);
  const paramsId: any = ref();
  const designData: any = ref();
  const searchValue: any = ref();
  const addParamsArr: any = ref([]);
  const paramsCode = route.query.code;
  const callColumns: BasicColumn[] = [];
  const searchFormSchema: FormSchema[] = ref([]);
  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 layers = reactive([
    {
      id: 1,
      name: '沂水县道路中心线1',
      checked: false,
      layer: {
        id: 'roadnetLine1',
        type: 'line',
        source: {
          type: 'vector',
          tiles: [
            'http://192.168.10.102:9020/api/DroneCaseinfo/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=yishuixian&X-Token=1ded3fe7',
          ],
          minzoom: 1,
          maxzoom: 20,
        },
        'source-layer': 'yishuixian',
        layout: {
          'line-join': 'round',
          'line-cap': 'round',
        },
        paint: {
          'line-color': [
            'case',
            ['==', ['get', 'handle_status_id'], 0],
            '#E6A23C',
            ['==', ['get', 'handle_status_id'], 1],
            '#409EFF',
            ['==', ['get', 'handle_status_id'], 2],
            '#67C23A',
            // 默认
            '#67C23A',
          ],
          'line-width': 1,
        },
      },
    },
  ]);

  // 图层定位数据
  const location = reactive([118.556717, 35.80391]);
  if (paramsCode == '数据统计') {
    searchFormSchema.value = [
      {
        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.value = [
      {
        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 [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) => {
      // 接口请求前 参数处理
      var temp = {
        id: paramsId.value,
        paginationInputDto: {
          page: data.page,
          rows: data.limit,
          keyWord: data.key,
        },
        queryJson: searchValue.value,
      };
      return temp;
    },
    afterFetch: () => {
      const rel = designData.value;
      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) => {
              if (res[0]) {
                res[0].db_codecolumnsList.forEach((item) => {
                  if (item.isPrimaryKey == 1) {
                    chlidKey.value = item.dbColumnName;
                  }
                });
              }
            });
          }
          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,
              });
            }
          });
        });
      }
      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',
  });

  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(addParamsArr.value[0].field);
    // 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];
    }
    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,
          };
          if (haveMap.value) {
            showFormModalData.value = toProps;
            openShowFormModal.value = true;
            mapgemoList.value = [];
            // mapSetData.value.isAllowAddPolygon && MapboxComponent.value.handlerDraw();
          } else {
            openModal(true, toProps);
          }
        } else {
          flowFormData.value = {};
          previewOpen.value = true;
          isUpdate.value = false;
        }

        break;
      case 'Edit':
        if (rows.length == 0) {
          return createMessage.warn('请选择一条数据进行编辑');
        }
        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,
          };
          if (haveMap.value) {
            showFormModalData.value = toProps;
            openShowFormModal.value = true;
            // MapboxComponent.value.handlerDraw(
            //   mapgemoList.value,
            //   mapSetData.value.isAllowEditPolygon,
            // );
          } 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,
        };
        if (haveMap.value) {
          showFormModalData.value = toProps;
          openShowFormModal.value = true;
          // MapboxComponent.value.handlerDraw(mapgemoList.value, false);
        } else {
          openModal(true, toProps);
        }
        break;
      case 'Import':
        break;
      case 'Export':
        break;
      default:
        break;
    }
  };
  function handleSelect(selectedKeys: any, selected: any) {
    const rel = selected.node.dataRef;
    const obj: any = {};
    obj[rel.key] = rel.value;
    searchValue.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);

      // 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: {},
        };
      }
      paramsId.value = res.formScheme.id;
      btnList.value = columnObj.table.btns;
      if (columnObj.table.columns) {
        columnObj.table.columns.forEach((item) => {
          callColumns.push({
            title: item.label,
            dataIndex: item.key,
          });
        });
      }
      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;
    });
  }
  //弹窗确定后返回调用
  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 subTableData = res[childTableName].map((item) => {
          return {
            ...item,
            key: uuidv4(),
            MapGeom: item.mapgeom,
          };
        });
        formData.value = [...subTableData];
      })
      .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];
  };
  const mapOnLoad = (map) => {
    const test_url =
      'http://192.168.10.102:9020/api/DroneCaseinfo/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=yishuixian&field="gid","objectid",';
    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
  }
</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;
  }
</style>
