<template>
    <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
      <div class="form">
        <Form
          label-align="left"
          layout="vertical"
          description="线索控件"
          size="small"
          style="padding:0px 15px"
        >
        <a-row :gutter="12">
          <a-col :span="12" >
            <a-card  title="基本设置" class="card-item">
              <FormItem label="是否显示">
                <Switch v-model:checked="mapConfig.isShowMap" />
              </FormItem>
    
              <FormItem label="地图宽度" >
                <a-input-number
                  v-model:value="mapConfig.width"
                  placeholder="请输入地图宽度"
                  :min="1"
                  :max="100"
                >
                  <template #addonAfter><PercentageOutlined /></template>
                </a-input-number>
              </FormItem>
  
              <FormItem label=" &nbsp;"></FormItem>
            </a-card>
          </a-col>
  
          <a-col :span="12" >
            <a-card  title="地图配置" class="card-item" >
              <FormItem label="地图模式">
                <a-radio-group v-model:value="mapConfig.mode">
                  <a-radio :value="'2D'">二维地图</a-radio>
                  <a-radio :value="'3D'">三维地图</a-radio>
                </a-radio-group>
              </FormItem>
              <a-row :gutter="12">
                <a-col :span="12" >
                  <FormItem label="倾斜角度">
                    <a-input-number v-model:value="mapConfig.angle" :min="0"
                    :max="90" />
                  </FormItem>
                </a-col>
                <a-col :span="12" >
                  <FormItem label="中心位置">
                    <a-input v-model:value="mapConfig.center" />
                  </FormItem>
                </a-col>
              </a-row>
    
              <a-row :gutter="12">
                <a-col :span="8" >
                  <FormItem label="初始缩放级别">
                    <a-input-number v-model:value="mapConfig.zoom" :min="1"
                    :max="18" />
                  </FormItem>
                </a-col>
                <a-col :span="8" >
                  <FormItem label="最小缩放级别">
                    <a-input-number v-model:value="mapConfig.minZoom" :min="1"
                    :max="18" />
                  </FormItem>
                </a-col>
                <a-col :span="8" >
                  <FormItem label="最大缩放级别">
                    <a-input-number v-model:value="mapConfig.maxZoom" :min="1"
                    :max="18" />
                  </FormItem>
                </a-col>
              </a-row>
    
            </a-card>
          </a-col>
        </a-row>
  
  
        <a-card  title="底图设置" class="card-item" >
          <template #extra>
            <a-tooltip>
              <template #title>添加地图底图</template>
              <PlusOutlined @click="handlerAddBaseLayer()"/>
            </a-tooltip>
          </template>
          <!-- <a-table :row-selection="rowSelection" :dataSource="baseLayers" :columns="baselayercolumns"  :pagination="false" >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'checked'">
                <a-switch v-model:checked="record.checked" checked-children="显示" un-checked-children="隐藏" />
              </template>
            </template>
          </a-table> -->
  
          <a-table :dataSource="mapConfig.baseLayers" :columns="baselayercolumns" :pagination="false" >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'checked'">
                <a-switch v-model:checked="record.checked" checked-children="显示" un-checked-children="隐藏" />
              </template>
              <template v-if="column.key === 'operation'">
                <span>
                  <a-tooltip>
                    <template #title>删除图层</template>
                    <DeleteOutlined @click="hanelerDeleteBaseLayer(column, record)" />
                  </a-tooltip>
                </span>
              </template>
            </template>
          </a-table>
  
        </a-card>
  
  
        <a-card  title="图层设置" class="card-item" >
          <template #extra>
            <a-tooltip>
              <template #title>添加图层分类</template>
              <PlusOutlined @click="handleAddSource()"/>
            </a-tooltip>
          </template>
          <a-collapse v-model:activeKey="activeKey" v-for="item in mapConfig.layers" :key="item.name" ghost>
            <a-collapse-panel :key="item.name" :header="item.name">
              <!-- <template #header>
                <a-input v-model:value="item.name"/>
              </template> -->
              <template #extra>
                <a-tooltip>
                  <template #title>添加图层</template>
                  <PlusOutlined @click="hanelerAddLayer(item.name)" style="margin-right: 10px"/>
                </a-tooltip>
                <a-tooltip>
                  <template #title>修改图层分类标题</template>
                  <EditOutlined @click="openLayerModal(item.name)" style="margin-right: 10px"/>
                </a-tooltip>
                <a-tooltip>
                  <template #title>删除图层分类</template>
                  <DeleteOutlined @click="hanelerDeleteSource(item.name)"/>
                </a-tooltip>
                
                <a-modal :open="open" title="修改标题名" @ok="submitLayerModal" @cancel="closeLayerModal">
                  <a-input v-model:value="newLayerName" />
                </a-modal>
  
              </template>
              <a-table :dataSource="item.layers" :columns="columns" :pagination="false" >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'checked'">
                    <a-switch v-model:checked="record.checked" checked-children="显示" un-checked-children="隐藏" />
                  </template>
                  <template v-if="column.key === 'operation'">
                    <span>
                      <a-tooltip>
                        <template #title>删除图层</template>
                        <DeleteOutlined @click="hanelerDeleteLayer(item.name, record)" />
                      </a-tooltip>
                    </span>
                  </template>
                </template>
              </a-table>
            </a-collapse-panel>
          </a-collapse>
        </a-card>

        <a-button type="primary" size="middle" style="margin-top:12px;" @click="saveMapConfig">保存</a-button>
        </Form>
      </div>
  
      <a-modal
          class="insert-shp-modal"
          width="1290px"
          title="选择图层"
          :destroyOnClose="true"
          :open="openModal"
          @cancel="changeOpenModal"
        >
        <SelectLayer v-model:openModal="changeOpenModal" @handlerAddToLayerList="handlerAddToLayerList" />
  
      </a-modal>
  
    </PageWrapper>
  </template>
  <script lang="ts" setup>
    import { ref, inject, watch, onMounted,reactive,computed,unref } from 'vue';
    import { Form, FormItem, message, Switch,TableProps } from 'ant-design-vue';
    import { PageWrapper } from '@/components/Page';
    import { ShpLayerSourceLoadPage, GetTableAndViewColumnList } from '@/api/demo/formScheme';
    import{fun_GetForm} from '@/api/demo/formModule'
    import {updateConfig,getConfig} from '@/api/sys/layerManagement'
    import { EditOutlined, DeleteOutlined, PercentageOutlined ,PlusOutlined} from '@ant-design/icons-vue';
    import SelectLayer from '@/components/MapboxMaps/Modal/ServeResource/index.vue'
    import { useMessage } from '@/hooks/web/useMessage';
    const { createMessage } = useMessage();
    const mapConfig = ref({});


    getConfig({code:"mapsetting"}).then(res=>{
        mapConfig.value = JSON.parse(res.codeValue)
    })


    // const mapConfig = reactive({
    //   baseConfig:{
    //     state:true,
    //     width:50
    //   },
    //   viewerConfig:{
    //     mode:"2D",
    //     angle:90,
    //     center:null,
    //     zoom:12,
    //     minZoom:3,
    //     maxZoom:18
    //   },
    
    interface BaseLayerDataType {
      key: string | number;
      name: string;
      checked:boolean;
      layer:Object;
    } 
    //   baseLayers:[
    //     {
    //       name: '天地图底图图层',
    //       show:false,
    //       layer:{
  
    //       }
    //     },{
    //       name: '天地图注记图层',
    //       show:false,
    //       layer:{
            
    //       }
    //     },{
    //       name: '高清影像图层',
    //       show:false,
    //       layer:{
            
    //       }
    //     }
    //   ],
    //   layers:[
    //     {
    //       name: '违法建设线索图层',
    //       show:true,
    //       layer:{
            
    //       }
    //     },
    //     {
    //       name: '乱战耕地线索图层',
    //       show:false,
    //       layer:{
            
    //       }
    //     }
    //   ]
  
    // })
  
    const  baseLayers = reactive([
        
      ])
    
  
  
    const columns = reactive([
      {
        title: '图层名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '默认',
        dataIndex: 'checked',
        key: 'checked',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
      },
    ])
  
  
    const baselayercolumns = reactive([
      {
        title: '图层名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '默认',
        dataIndex: 'checked',
        key: 'checked',
      },{
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
      },
    ])
  
    // config
    // const config: any = inject('formConfig');
    const config = {
    "layoutType": 1,
    "queryType": 1,
    "left": {
        "title": "左侧树形",
        "colField": "",
        "dataType": "1",
        "dataIdKey": "",
        "dataPIdKey": "",
        "dataValueKey": "",
        "dataLabelKey": "",
        "colNames": [],
        "options": [],
        "dataCode": ""
    },
    "table": {
        
    },
    "btns": [
        {
            "label": "新增",
            "id": "Add",
            "prop": "Add",
            "icon": "ant-design:plus-outlined",
            "isRowBtn": false,
            "class": "primary",
            "sort": 0
        },
        {
            "label": "导入",
            "id": "Import",
            "prop": "Import",
            "icon": "ant-design:upload-outlined",
            "isRowBtn": false,
            "class": "success",
            "sort": 1
        },
        {
            "label": "导出",
            "id": "Export",
            "prop": "Export",
            "icon": "ant-design:download-outlined",
            "isRowBtn": false,
            "class": "primary",
            "sort": 2
        },
        {
            "label": "编辑",
            "id": "Edit",
            "prop": "Edit",
            "icon": "ant-design:edit-outlined",
            "isRowBtn": true,
            "class": "success",
            "sort": 3,
            "isWFlow": true,
            "wFlowCode": "0000001"
        },
        {
            "label": "删除",
            "id": "Delete",
            "prop": "Delete",
            "icon": "ant-design:delete-outlined",
            "isRowBtn": true,
            "class": "error",
            "sort": 4
        },
        {
            "label": "详情",
            "id": "Details",
            "prop": "Details",
            "icon": "ant-design:align-center-outlined",
            "isRowBtn": true,
            "class": "default",
            "sort": 5
        }
    ]
};
    // const mapConfig = ref(config.table.maps);
  
  
    watch(
      () => config.table.maps,
      () => {
        mapConfig.value = config.table.maps;
        // 更新选项
        mapConfig.value?.baseLayers?.forEach((item,index)=>{
          selectedRowKeys.value.push(item.key)
        })
      },
    );
  
  
    const selectedBaseLyaers:BaseLayerDataType[] = [];
    const selectedRowKeys = ref<BaseLayerDataType['key'][]>([]);
  
    mapConfig.value?.baseLayers?.forEach((item,index)=>{
      selectedBaseLyaers.push(item);
      selectedRowKeys.value.push(item.key)
    })
  
    const onSelectChange = (changableRowKeys:number[],changeRows:BaseLayerDataType[]) => {
      selectedRowKeys.value = changableRowKeys;
      mapConfig.value.baseLayers = changeRows;
    };
  
    const rowSelection = computed(() => {
      return {
        selectedRowKeys: unref(selectedRowKeys),
        onChange: onSelectChange,
        hideDefaultSelections: false,
      };
    });
  
    const openModal = ref(false);
    const insertShpModal = ref(true);
  
    const changeOpenModal = (value) => {
      openModal.value = !openModal.value
    };
  
    const changeOpenInsertShpModal = (value) => {
        insertShpModal.value = value;
      };
  
    onMounted(() => {
  
    });
  
    const activeKey: any = ref([]);
    let nowCollapseName = null;
    // 添加图层分类
    const handleAddSource = () => {
      if(!mapConfig.value.layers){
        mapConfig.value.layers = [];
      }
      mapConfig.value?.layers.push(
        {
          name: '',
          layers: [],
        }
      );
      activeKey.value.push('');
    };
    // 删除图层分类
    const hanelerDeleteSource = (collapseName) =>{
      mapConfig.value.layers.forEach((item, index)=>{
        if(item.name == collapseName){
          mapConfig.value.layers.splice(index, 1);
          activeKey.value.splice(index, 1);
        }
      });
    }
  
  
    // 图层标题参数
    let oldLayerName = '';
    const newLayerName = ref('');
    const open = ref(false);
    // 打开图层标题弹窗
    const openLayerModal = (name) => {
      open.value = true;
      oldLayerName = name;
      newLayerName.value = name;
      activeKey.value.push(name);
    }
    // 提交图层标题弹窗
    const submitLayerModal = () => {
      if (oldLayerName != newLayerName.value) {
        let number = mapConfig.value?.layers?.filter(la => la.name == newLayerName.value).length;
        if(number > 0) {
          message.warn('图层标题名不能重复！');
          return;
        }
        mapConfig.value?.layers?.forEach((item, index) => {
          if(item.name == oldLayerName) {
            activeKey.value.push(newLayerName.value);
            activeKey.value.splice(oldLayerName, 1);
            mapConfig.value.layers[index].name = newLayerName.value;
          }
        })
      }
      open.value = false;
    }
    // 关闭图层标题弹窗
    const closeLayerModal = (name) => {
      open.value = false;
    }
  
    const addType = ref<String>("");
  
    // 添加图层
    const hanelerAddLayer = (collapseName) =>{
      addType.value = "layer";
      if(collapseName) {
        nowCollapseName = collapseName;
        changeOpenModal(true);
      } else {
        message.warn('请先命名图层分类名');
      }
      activeKey.value.push(collapseName);
    }
  
    // 添加底图图层
    const handlerAddBaseLayer = ()=>{
      addType.value = "baselayer";
      changeOpenModal(true);
    }
    // 删除图层
    const hanelerDeleteLayer = (name, record)=>{
      mapConfig.value?.layers?.forEach((item, item_index)=>{
        if (item.name == name) {
          item.layers.forEach((it, it_index) => {
            if(it.id == record.id){
              mapConfig.value.layers[item_index].layers.splice(it_index, 1);
            }
          });
        }
      })
    }
  
    // 删除底图图层
    const hanelerDeleteBaseLayer = (item,record)=>{
      console.log(mapConfig.value,item,record)
      
      mapConfig.value?.baseLayers?.forEach((item, item_index)=>{
        if (item.name == record.name) {
          mapConfig.value.baseLayers.splice(item_index, 1);
        }
      })
    }
   // 添加图层方法后续
    const handlerAddToLayerList = (item)=>{
      if(addType.value == 'layer'){
        mapConfig.value.layers.forEach((layer, index)=>{
          if(layer.name == nowCollapseName) {
            activeKey.value.push(layer.name);
            mapConfig.value.layers[index].layers.push(item);
          }
        });
      }else if(addType.value == 'baselayer'){
        mapConfig.value.baseLayers?.push(item);
      }
      console.log(mapConfig.value.baseLayers);
    }
  
    const handlerBaseLayerChange = (item) => {
      if(!mapConfig.value?.baseLayers){
        mapConfig.value.baseLayers = [];
      }
      if(item.show == true){
        mapConfig.value.baseLayers.push(item);
      }else{
        mapConfig.value.baseLayers?.forEach((it,idx)=>{
          if(it.name == item.name){
            mapConfig.value.baseLayers?.splice(idx,1);
          }
        })
      }
  
    }

    const saveMapConfig = ()=>{
        let form = {
            code:"mapsetting",
            codeValue:JSON.stringify(mapConfig.value)
        }
        updateConfig(form).then(res=>{
            createMessage.success("保存成功！");
        })
    }
  </script>
  
  <style lang="less" scoped>
    .form {
      overflow-y: auto;
      height: calc(100vh - 120px);
      width: 100%;
    }
  
    .card-item{
      margin-top:30px!important;
    }
  </style>
  