<template>
  <div>
    <a-row ::gutter="0">
      <a-col :span="12">
        <BasicTable  @register="registerTable" :searchInfo="searchInfo">
          <template #toolbar>
            <PermissionBtn @btn-event="onBtnClicked" />
          </template>
        </BasicTable>
      </a-col>
      <a-col :span="12">
        <div class="map-outer">
          <MapboxMap
          :geomsList="geomsList"
          :mapConfig="mapConfig"
          @handlerDrawComplete="handlerDrawComplete"
          @mapOnLoad="onMapboxLoad"
          ref="MapboxComponent"
        />
        </div>
      </a-col>
    </a-row>

    <div class="data-preview-container" v-if="showRecordList">
      <a-tabs v-model:activeKey="activeKey"  hide-add type="editable-card" @edit="onEdit" @change="handleTabChange">
        <a-tab-pane v-for="(pane,index) in tablist" :key="index.toString()" :tab="pane.streetname+'-'+pane.label" :closable="pane.closable">
        </a-tab-pane>
      </a-tabs>
      <RecordList :tablist="tablist" :currentListQuery="currentListQuery.listQuery"></RecordList>

      <div class="data-preview-container-option">
        
        <div @click="exportList()">
          <CloudDownloadOutlined />
        </div>
        <div @click="handleCloseRecordList()">
          <MinusOutlined />
        </div>
        <div @click="handleCloseAllRecordList()">
          <CloseOutlined />
        </div>
      </div>
    </div>

    <a-modal
      v-model:open="addModalShow"
      title="添加GeoServer服务"
      width="800px"
      size="small"
    >
    <div class="content">
      <div class="select-file-div">
        <div class="upload-div">
          <a-upload-dragger
            style="height: 174px; width: 174px"
            class="upload-dragger"
            v-model:fileList="fileList"
            name="file"
            :multiple="false"
            :maxCount="1"
            :before-upload="beforeUpload"
            accept=".zip,.xlsx"
          >
            <p class="ant-upload-drag-icon">
              <inbox-outlined></inbox-outlined>
            </p>
            <div style="opacity: 0.7">
              <a-button :icon="h(PlusOutlined)">文件上传</a-button>
            </div>
          </a-upload-dragger>
        </div>
        <div class="upload-span">
          <div class="upload-span-content">
            <div style="opacity: 0.7">将文件拖拽到这里或点击上传按钮</div>
            <div style="color: #1e5eff">支持扩展名：zip,xlsx</div>
            <div style="opacity: 0.7">zip中需要包含 .shp .shx .dbf 文件 且.shp文件大小小于10MB</div>
          </div>
        </div>
        <div class="upload-form">

          <a-form
            ref="formRef"
            :model="uploadFrom"
            :label-col="{ style: { width: '75px' } }"
            labelAlign="right"
            :rules="uploadFormRules"
          >
            <a-form-item label="服务名称" name="serverName">
              <a-input v-model:value="uploadFrom.serverName" placeholder="请输入服务名称" />
            </a-form-item>

            <!-- 显示条件：文件类型为Excel时 -->
            <a-form-item label="图斑数据" name="hasFeature" v-if="!isShp">
              <a-select v-model:value="uploadFrom.hasFeature" placeholder="请选择是否具有图斑数据">
                <a-select-option value="1">是</a-select-option>
                <a-select-option value="0">否</a-select-option>
              </a-select>
            </a-form-item>

            <!-- 显示条件：文件类型为shp 或者 类型为Excel时有图斑数据 -->
            <a-form-item label="空间参考" name="spaceType" v-if="isShp || (!isShp && uploadFrom.hasFeature == '1')">
              <a-select v-model:value="uploadFrom.spaceType" placeholder="请选择空间参考">
                <a-select-option value="EPSG:4326">EPSG:4326</a-select-option>
                <a-select-option value="3857">EPSG:3857</a-select-option>
                <a-select-option value="900913">EPSG:900913</a-select-option>
              </a-select>
            </a-form-item>

            <!-- 显示条件：文件类型为Excel有图斑时 -->
            <a-form-item label="数据类型" name="spaceType" v-if="!isShp && uploadFrom.hasFeature == '1'">
              <a-select v-model:value="uploadFrom.layerType" placeholder="请选择数据类型">
                <a-select-option value="point">点</a-select-option>
                <a-select-option value="linestring">线</a-select-option>
                <a-select-option value="polygon">面</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="数据表名" name="tableName">
              <a-row :gutter="12">
                <a-col :span="20">
                  <a-input v-model:value="uploadFrom.tableName" placeholder="请输入表名" />
                </a-col>
                <a-col :span="4">
                  <a-button type=""  :icon="h(PlusOutlined)" @click="handlerGetExistsTableList()"  />
                </a-col>
              </a-row>
            </a-form-item>
          </a-form>

          <!-- <div class="upload-span-button">
            <a-button type="primary" :icon="h(CloudUploadOutlined)" @click="submitShp">上传</a-button>
          </div> -->

          
        </div>
      </div>
    </div>

      <template #footer>
        <a-button type="default" >取消</a-button>
        <a-button type="primary" >添加</a-button>
      </template>
    </a-modal>

  </div>
</template>
<script lang="ts" setup>
  import { ref,reactive,h } from 'vue';

  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getStatisticalList, deleteRole } from '@/api/demo/system';

	// import {DataPreivew} from './RecordList.vue'

  import { useMessage } from '@/hooks/web/useMessage';
  import { useModal } from '@/components/Modal';
  import { RecordList } from './page';

  import { PermissionBtn } from '@/components/PermissionBtn/index';

  import { columns, columnsDataPreview,searchFormSchema } from './statistical.data';
  import {MinusOutlined,CloseOutlined,CloudDownloadOutlined,PlusOutlined} from '@ant-design/icons-vue'
  import axios from 'axios';
  import print from "vue3-print-nb";

  import { getAppEnvConfig } from '@/utils/env';
  import MapboxMap from '@/components/MapboxMaps/MapComponent.vue';
  import type { UploadProps } from 'ant-design-vue';

  const { VITE_GLOB_API_URL } = getAppEnvConfig();

  const addModalShow = ref<Boolean>(false);

  const vPrint = print;

  const printOpen = ref<boolean>(false);

  const uploadFrom = ref({})
  const uploadFormRules = reactive({
    serverName: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
    imageServerAddress: [{ required: true, message: '请输入服务地址', trigger: 'blur' }],
    hasFeature: [{ required: true, message: '请选择是否有图斑数据', trigger: 'blur' }],
    spaceType: [{ required: true, message: '请选择参考系', trigger: 'blur' }],
    layerType: [{ required: true, message: '请选数据类型', trigger: 'blur' }],
    tableName: [{ required: true, message: '请输入表名', trigger: 'blur' }],
  });

  const printObj = reactive({
    id:"printMe",
    popTitle: "",
    beforeOpenCallback() {
      
    },
    openCallback() {
      
    },
    closeCallback() {
      
    }
  })

  const beforeUpload:UploadProps['beforeUpload'] = (file) => {
    // file.type === FILETYPE.ZIP ? isShp.value = true: isShp.value = false
    fileList.value = [file];
    return false;
  };

  const fileList = ref<UploadProps['fileList']>([]);

  
  defineOptions({ name: 'RoleManagement' });
  
  let activeKey = ref('0')

  const { createConfirm, createMessage } = useMessage();
  const [registerModal, { openModal: openRoleModal }] = useModal();
  const [registerModulesModal, { openModal: openModulesModal }] = useModal();
  const [registerAccountModal, { openModal: openAccountModal }] = useModal();
  const searchInfo = reactive<Recordable>({
    countyid:null
  });

  const currentOrgLevel = ref<string>("country")

  const showRecordList = ref<boolean>(false);

  const panes = reactive<{ title: string; content: string; key: string; closable?: boolean}[]>([])
  const searchParams = ref();
  const [registerTable, { reload, getSelectRows, clearSelectedRowKeys, updateTableData}] = useTable({
    // 表格名称
    title: 'GeoServer服务管理',
    // 获取数据的接口
    api: getStatisticalList,
    // 表单列信息 BasicColumn[]
    columns,
    rowKey: 'streetid',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    // 使用搜索表单
    useSearchForm: true,
    // 显示表格设置工具
    showTableSetting: true,
    // 是否显示分页
    pagination:true,
    // 是否显示表格边框
    bordered: true,
    // 序号列
    showIndexColumn: true,
    // 勾选列
    rowSelection: {
      type: 'radio',
    },
    // 搜索
    handleSearchInfoFn(info) {
      searchParams.value = info;
      return info;
    },
  });

  const [registerPrintTable] = useTable({
    // 表格名称
    title: '',
    // 获取数据的接口
    api: getStatisticalList,
    // 表单列信息 BasicColumn[]
    columns,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    // 使用搜索表单
    useSearchForm: false,
    // 显示表格设置工具
    showTableSetting: false,
    // 是否显示分页
    pagination:false,
    // 是否显示表格边框
    bordered: true,
    // 序号列
    showIndexColumn: false,
    // 勾选列
    rowSelection: false,
    // 搜索
    handleSearchInfoFn(info) {
      searchParams.value = info;
      return info;
    },
  });

  



  const [registerTableDataPreview,{ reloadDataPreview, getSelectRowsDataPreview, clearSelectedRowKeysDataPreview }] = useTable({
    // 表格名称
    title: '',
    // 获取数据的接口
    api: getStatisticalList,
    // 表单列信息 BasicColumn[]
    columnsDataPreview,
    rowKey: 'id',
    formConfig: {
      labelWidth: 120,
    //   schemas: searchFormSchema,
    },
    // 使用搜索表单
    useSearchForm: false,
    // 显示表格设置工具
    showTableSetting: false,
    // 是否显示表格边框
    bordered: true,
    // 序号列
    showIndexColumn: false,
    // 勾选列
    rowSelection: false,
    // 搜索
    handleSearchInfoFn(info) {
      return info;
    },
  });
  function handleCloseRecordList(){
	  showRecordList.value = false;
  }
  function exportList(){
    createMessage.success("接口待对接！")
  }

  function handleCreate() {
    addModalShow.value = true;
  }
  function viewAccount(record: Recordable) {
    openAccountModal(true, {
      record,
    });
  }
  function onEdit(targetKey: string){
    tablist.splice(parseInt(targetKey),1);
    if(tablist.length==0){
      showRecordList.value = false;
    }
    if(parseInt(targetKey)>1){
      activeKey.value = (parseInt(targetKey)-1).toString();

    }else{
      activeKey.value = '0';
    }
    currentListQuery.listQuery = tablist[activeKey.value].listQuery
  }

  let currentListQuery = reactive({listQuery:{}});
  
  function handleTabChange(e){
    currentListQuery.listQuery = tablist[e].listQuery

    console.log(currentListQuery)
  }


  // function remvoeTab(){

  // }

  const tablist = reactive<{streetname:string;label:string;listQuery:searchListSchema}[]>([])
  // 查询条件
  interface searchListSchema{
    is_intact?:number;
    streetid?:number;
    countyid?:number;
    identification_start_time?:string;
    identification_end_time?:string;
    page?:number;
    limit?:number;
    is_deal?:number;
    is_not_deal_hour24?:number;
    is_drawback?:number;
    typeid?:number;
    is_illegal?:number;
    is_complete?:number;
    handle_status_id?:number;
    out_time_flag?:number;
  }



  // const searchForm = reactive<searchListSchema>({

  // })
  
  function handlePreViewData(column,record:Recordable){

    const searchForm = reactive<searchListSchema>({
      identification_start_time:searchParams.value?.identification_start_time,
      identification_end_time:searchParams.value?.identification_end_time,
      is_intact:1,
      page:1,
      limit:10,
    })

    if(currentOrgLevel.value == 'country'){
      searchForm.countyid = record.streetid;
    }else if(currentOrgLevel.value == 'street'){
      searchForm.streetid = record.streetid;
    }

    console.log("searchForm",searchForm);

    switch(column.dataIndex){
      case 'allCount':
        break;
      case 'handleStatus':
        searchForm.is_deal = 1;
        break;
      case 'notDealHour24':
        searchForm.is_not_deal_hour24 = 1;
        searchForm.is_drawback = 0;
        break;
      case 'notDealHour24':
        searchForm.is_not_deal_hour24 = 1;
        searchForm.is_drawback = 0;
        break;
      case 'typeFanxinCount':
        searchForm.typeid = record.typeid
      case 'typeJiagaiCount':
        searchForm.typeid = record.typeid
      case 'typeFanjianCount':
        searchForm.typeid = record.typeid
      case 'typeCunliangCount':
        searchForm.typeid = record.typeid
      case 'typeTuituCount':
        searchForm.typeid = record.typeid
      case 'illegal0Count':
        searchForm.is_illegal = 0;
        searchForm.is_deal = 1;
        break;
      case 'illegal1Count':
        searchForm.is_illegal = 1;
        searchForm.is_deal = 1;
        break;
      case 'illegal2Count':
        searchForm.is_illegal = 2;
        searchForm.is_deal = 1;
        break;
      case 'illegal1Count1':
        searchForm.is_illegal = 1;
        searchForm.is_deal = 1;
        break;
      case 'illegalHandle2Status':
        searchForm.handle_status_id = 1;
        searchForm.is_deal = 1;
        break;
      case 'illegalHandle01Status':
        searchForm.is_illegal = 1;
        searchForm.is_deal = 1;
        searchForm.is_complete = 0;
        break;
      case 'notComplete3':
        searchForm.is_illegal = 1;
        searchForm.is_complete = 0;
        searchForm.out_time_flag = 1;
        break;
      case 'notComplete7':
        searchForm.is_illegal = 1;
        searchForm.is_complete = 0;
        searchForm.out_time_flag = 2;
        break;
      case 'notComplete30':
        searchForm.is_illegal = 1;
        searchForm.is_complete = 0;
        searchForm.out_time_flag = 4;
        break;
      case 'notComplete30More':
        searchForm.is_illegal = 1;
        searchForm.is_complete = 0;
        searchForm.out_time_flag = 5;
        break;
    }
    
    let tabItem = {
      streetname:record.streetname,
      label:column.title,
      listQuery:searchForm,
    }

    tablist.push(tabItem)
    activeKey.value = tablist.length > 1 ? (tablist.length-1).toString() : '0'; 

    showRecordList.value = true;
    currentListQuery.listQuery = searchForm

  }

  // 获取下级行政结构案件统计
  function getOrgCaseList(column,record:Recordable){

    if(currentOrgLevel.value == 'country'){
      currentOrgLevel.value = 'street'
    }else if(currentOrgLevel.value == 'street'){
      currentOrgLevel.value = 'country'
    }
    searchInfo.countyid = record.streetid;
    console.log("searchInfo",searchInfo);
    reload();
    console.log("searchInfo",searchInfo);
  }
  function handleCloseAllRecordList(){
    for(let i=0;i<tablist.length;i++){
      tablist.pop();
    }
    showRecordList.value = false;

  }
  function handleEdit() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请勾选一个角色进行编辑');
    }
    const record = rows[0];
    openRoleModal(true, {
      record,
      isUpdate: true,
    });
  }

  async function handleDelete() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请勾选一个角色进行删除');
    }
    const query = [rows[0].id];
    createConfirm({
      iconType: 'info',
      title: '删除',
      content: '确定要删除当前角色吗',
      onOk: async () => {
        const data = await deleteRole(query);
        if (data) {
          handleSuccess();
          createMessage.success('删除成功');
        } else {
          createMessage.error('删除失败');
        }
      },
    });
  }

  function handlePrint(){
    printOpen.value = true;
  }

  // 直接下载接口返回的二进制流 

  function handleExport(){
    let params = {...searchParams.value}
    params.countyid = searchInfo?.countyid;
    axios({
      method:"post",
      url:VITE_GLOB_API_URL+"/api/DroneCaseinfo/ExportCaseSynthesisCensusStreet",
      params:params,
      headers:{
        "X-Token":localStorage.getItem("X-Token")
      },
      responseType:"blob"
    }).then(res=>{
        console.log("excel",res);
        let fileName = "统计报表" + new Date().getTime() + ".xls";
        const elink = document.createElement('a')
        elink.download = fileName;
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(res.data)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)

    })
  }

  function handleExcelDownload(data) {
      // 将二进制数据转换为Excel文件
      const workbook = XLSX.read(data, { type: 'array' });

      // 可以进一步处理workbook对象，例如提取工作表数据等
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const excelData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

      console.log('Excel Data:', excelData);

      // 下载Excel文件
      XLSX.writeFile(workbook, 'example.xlsx');
    }


  function handleSuccess() {
    clearSelectedRowKeys();
    reload();
	reloadDataPreview();
  }
  
  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnBack':
        currentOrgLevel.value = 'street'
        getOrgCaseList({},{streetid:null});
        break;
      case 'btnAdd':
        handleCreate();
        break;
      case 'btnEdit':
        handleEdit();
        break;
      case 'btnDelete':
        handleDelete();
        break;
      case 'btnModules':
        let rows = getSelectRows();
        if (rows.length == 0) {
          return createMessage.warn('请勾选一个角色进行编辑');
        }
        const record = rows[0];
        openModulesModal(true, {
          record,
        });
        break;
	  case 'btnPrint':
		  handlePrint();
		break;
      case 'btnExport':
	  	handleExport();
		break;
      default:
        break;
    }
  }
</script>
<style>
.map-outer{
  width:100%;
  height: calc( 100vh - 80px);
}
.data-preview-container{
	width:100%;
	height: calc( 100% - 0px);
	position:absolute;
	padding:30px 10px;
	top:0px;
	left:0px;
  background:#fff;
}
.data-preview-container-option{
	width:120px;
	height: 40px;
	position:absolute;
	top:30px;
	right:0px;
}
.data-preview-container-option div{
	width:40px;
	height:40px;
	line-height:40px;
	float:left;
	text-align: center;
	cursor:pointer;
}

.content{
  padding:20px;
}

.upload-div{
}

.upload-span{
  margin:30px auto;
}
</style>
