<template>
  <div class="page-div categories-page">
    <div class="tree-div w-1/7 xl:w-1/7 m-4 mr-0">
      <div class="header">
        <div class="buttons-div">
          <a-button
            type="primary"
            color="info"
            style="margin-right: 10px"
            @click="buttonClick('treeAdd')"
          >
            添加分类
          </a-button>
          <a-button type="primary" color="error" @click="buttonClick('treeDel')">
            删除分类
          </a-button>
        </div>
      </div>
      <div class="content">
        <div class="showTree">
          <BasicTree
            ref="treeRef"
            :treeData="showTree"
            :loading="lLoading"
            :fieldNames="{ key: 'itemValue', title: 'itemName' }"
            @select="
              (selectedKeys, { node }) => {
                getSelectId(node.itemDetailId);
                changeTypeId(node.itemValue);
              }
            "
          />
        </div>
      </div>
    </div>
    <div class="right-div w-6/7 xl:w-6/7">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <PermissionBtn @btnEvent="buttonClick"></PermissionBtn>
          <a-button @click="buttonClick('btnAdd')" type="primary">新增</a-button>
          <a-button @click="buttonClick('btnEdit')" type="success">编辑</a-button>
          <a-button @click="buttonClick('btnDelete')" type="error">删除</a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key == 'code'">
            {{ getCode(record) }}
          </template>
          <template v-if="column.key == 'layer'">
            {{ getLayer(record) }}
          </template>
          <template v-if="column.key == 'isClass'">
            <a-tag v-if="record.isClass == 1" color="yellow">分类</a-tag>
            <a-tag v-if="record.isClass == 0" color="gray">不分类</a-tag>
          </template>
          <template v-if="column.key == 'overlayList'">
            <span class="content-full">
              <a-tag color="green" v-for="tag in getOverlayList(record)" :key="tag">
                {{ tag }}
              </a-tag>
            </span>
          </template>
          <template v-if="column.key == 'isSum'">
            <a-tag v-if="record.isSum == 1" color="blue">合计</a-tag>
            <a-tag v-if="record.isSum == 0" color="red">不合计</a-tag>
          </template>
        </template>
      </BasicTable>
    </div>
    <a-modal
      class="categories-modal"
      v-model:open="openModal"
      :title="modalData.title"
      :maskClosable="false"
      :afterClose="clearModal"
      :footer="null"
    >
      <UseModal
        ref="modalFormRef"
        :modalData="modalData"
        :showTree="showTree"
        :layerOptioins="layerOptioins"
        :orverlayListOptioins="orverlayListOptioins"
        @closeModal="closeModal"
        @submit="submit"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import UseModal from './Modal/modal.vue';
  import { BasicTree } from '@/components/Tree';
  import { BasicTable, useTable } from '@/components/Table';
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { ref, onMounted, reactive, watch, createVNode, unref } from 'vue';
  import {
    getLeftTree,
    addLeftItem,
    delLeftItem,
    LoadPage,
    Add,
    Update,
    Delete,
  } from '@/api/sys/cloud';
  import { ShpGeoLayerLoadPage } from '@/api/demo/system';
  import {
    columns,
    emptyTableItem,
    emptyTreeItem,
    searchFormSchema_1,
    searchFormSchema_2,
  } from './util';
  import { Modal, message } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { cloneDeep, forEach } from 'lodash-es';

  // 左侧树
  const treeRef = ref();
  let showTree = ref([]);
  let typeId = ref('');
  let selectTreeId = ref('');
  let lLoading = ref(false);
  // 右侧表
  const modalFormRef = ref();
  const modalData = reactive({
    title: '',
    data: {},
    type: '',
  });
  const firstRequestCode = ref('');
  const searchFormSchema = ref(searchFormSchema_1);

  let openModal = ref(false);

  // watch(
  //   () => typeId.value,
  //   (newVal) => {
  //     if (newVal == 'imgage_data') {
  //       searchFormSchema.value = searchFormSchema_2;
  //     } else {
  //       searchFormSchema.value = searchFormSchema_1;
  //     }
  //   },
  //   {
  //     immediate: true,
  //   },
  // );

  // 云查询管理
  const [registerTable, { reload, getSelectRows }] = useTable({
    beforeFetch: (params) => {
      if (params.StartTime) {
        params.StartTime = dayjs(params.StartTime).startOf('day').format('YYYY-MM-DD');
      }
      if (params.EndTime) {
        params.EndTime = dayjs(params.EndTime).endOf('day').format('YYYY-MM-DD HH:mm:ss');
      }
      if (firstRequestCode.value !== '') {
        params = { ...params, Code: firstRequestCode.value };
      } else if (typeId.value !== '') {
        params = { ...params, Code: typeId.value };
      } else {
        params = { ...params };
      }
      return params;
    },
    api: LoadPage,
    columns,
    title: '云查询管理',
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    showIndexColumn: false,
    rowSelection: {
      type: 'radio',
    },
    useSearchForm: true,
    bordered: true,
    showTableSetting: true,
    handleSearchInfoFn(info) {
      return info;
    },
    immediate: false,
    afterFetch(res) {
      firstRequestCode.value = '';
      return res;
    },
  });

  // 左侧树
  const getTreeData = (isMounted) => {
    lLoading.value = true;
    getLeftTree({ code: 'cloudQueryManagement' })
      .then((res) => {
        showTree.value = res;
        lLoading.value = false;
        if (isMounted && res.length > 0) {
          firstRequestCode.value = res[0].itemValue;
          selectTreeId.value = res[0].itemDetailId;
          typeId.value = res[0].itemValue;
          unref(treeRef).setSelectedKeys([res[0].itemValue]);
        }
        reload();
      })
      .catch((err) => {
        lLoading.value = false;
      });
  };

  // 左侧树选中
  const changeTypeId = (itemValue) => {
    if (typeId.value != itemValue) {
      typeId.value = itemValue;
      reload();
    } else {
      typeId.value = '';
      reload();
    }
  };
  const getSelectId = (itemDetailId) => {
    if (selectTreeId.value != itemDetailId) {
      selectTreeId.value = itemDetailId;
    } else {
      selectTreeId.value = '';
    }
  };

  // 按钮分类
  const buttonClick = (diffType) => {
    let check = false;
    switch (diffType) {
      case 'treeAdd':
        openModal.value = true;
        modalData.title = '添加分组';
        modalData.data = cloneDeep(emptyTreeItem);
        modalData.type = diffType;
        break;
      case 'treeDel':
        check = selectTreeId.value === '' ? true : false;
        if (check) {
          message.warning('请选择一条分组数据');
          return;
        }
        Modal.confirm({
          title: '是否确认删除?',
          icon: createVNode(ExclamationCircleOutlined),
          onCancel() {},
          onOk() {
            return delLeftItem({ id: selectTreeId.value })
              .then((res) => {
                getTreeData(false);
                typeId.value = '';
                reload();
              })
              .catch((err) => {
                console.log(err);
              });
          },
        });
        break;
      case 'btnAdd':
        openModal.value = true;
        modalData.title = '添加';
        modalData.data = cloneDeep(emptyTableItem);
        modalData.type = diffType;
        break;
      case 'btnEdit':
        if (getSelectRows().length !== 1) {
          message.warning('请选择一条数据');
          return;
        }
        let editData = getSelectRows()[0];
        editData.isClass = editData.isClass == 1 ? true : false;
        editData.isSum = editData.isSum == 1 ? true : false;
        modalData.title = '编辑';
        modalData.data = { ...editData };
        modalData.type = diffType;
        openModal.value = true;
        break;
      case 'btnDelete':
        check = getSelectRows().length !== 1 ? true : false;
        if (check) {
          message.warning('请选择一条数据');
          return;
        }
        Modal.confirm({
          title: '是否确认删除?',
          icon: createVNode(ExclamationCircleOutlined),
          onCancel() {},
          onOk() {
            console.log(getSelectRows()[0]);

            let id = getSelectRows()[0].id;
            return Delete({ id: id })
              .then((res) => {
                reload();
              })
              .catch((err) => {
                console.log(err);
              });
          },
        });
        break;
    }
  };
  // 表单提交
  const submit = () => {
    let userName = localStorage.getItem('fireUserLoginName');
    switch (modalData.type) {
      case 'treeAdd':
        addLeftItem({
          ...modalData.data,
          itemCode: 'cloudQueryManagement',
          createUserName: userName,
          modifyUserName: userName,
          createDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          modifyDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          enabledMark: 1,
          sortCode: showTree.value.length,
        })
          .then((res) => {
            getTreeData(false);
            openModal.value = false;
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      case 'btnAdd':
        modalData.data.isClass = modalData.data.isClass ? 1 : 0;
        modalData.data.isSum = modalData.data.isSum ? 1 : 0;
        modalData.data.countynameList = getCountyNameListByOverlayList(modalData.data.tableName);
        Add({
          ...modalData.data,
          createUserName: userName,
          modifyUserName: userName,
          createDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          modifyDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        })
          .then((res) => {
            reload();
            openModal.value = false;
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      case 'btnEdit':
        modalData.data.isClass = modalData.data.isClass ? 1 : 0;
        modalData.data.isSum = modalData.data.isSum ? 1 : 0;    
        modalData.data.countynameList = getCountyNameListByOverlayList(modalData.data.tableName);
        Update({
          ...modalData.data,
          modifyUserName: userName,
          modifyDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        })
          .then((res) => {
            reload();
            openModal.value = false;
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      default:
        break;
    }
  };

  // 关闭弹窗
  const closeModal = () => {
    openModal.value = false;
    clearModal();
  };
  // 清理验证
  const clearModal = () => {
    modalFormRef.value.clearModal();
  };

  // 云查询图层的options
  const layerOptioins: any = ref([]);
  // 叠加图层的options
  const orverlayListOptioins: any = ref([{ serverName: '天地图', dataTable: '天地图', countyname: '天地图' }]);
  function getLayerOptions() {
    ShpGeoLayerLoadPage({ page: 1, limit: 10000 }).then((res) => {
      layerOptioins.value = res.items;
      orverlayListOptioins.value = orverlayListOptioins.value.concat(layerOptioins.value);
    });
  }

  // 表格-云查询分类的值
  const getCode = (record) => {
    let result = '';
    showTree.value.forEach((item: any) => {
      if (item.itemValue === record.code) {
        result = item.itemName;
      }
    });
    return result;
  };

  // 表格-图层的值
  const getLayer = (record) => {
    let result = '';
    layerOptioins.value.forEach((item: any) => {
      if (item.id === record.layer) {
        result = item.serverName;
      }
    });
    return result;
  };

  // 表格-叠加图层的值
  const getOverlayList = (record) => {
    let result: any = [];
    orverlayListOptioins.value.forEach((item: any) => {
      record.overlayList.forEach((over) => {
        if (item.dataTable == over) {
          result.push(item.serverName);
        }
      });
    });
    // result = record.overlayList;
    return result;
  };
  // 区别图层的区县
  function getCountyNameListByOverlayList(tableName) {
    let result: any = [];
    orverlayListOptioins.value.forEach((optioins: any) => {
      if(tableName == optioins.dataTable) {
        result.push(optioins.countyname);
      }
    });
    return result;
  }

  onMounted(() => {
    getTreeData(true);
    getLayerOptions();
  });
</script>
<style lang="scss" scoped>
  .page-div {
    position: relative;
    display: flex;
    height: calc(100% - 20px);
    display: flex;

    .tree-div {
      background-color: #fff;
      display: flex;
      flex-direction: column;
      .header {
        display: flex;
        flex-direction: column;
        padding: 10px;
        border-bottom: 1px solid #eee;
        .buttons-div {
          display: flex;
          justify-content: left;
        }
        .search-div {
          margin-top: 10px;
          display: flex;
        }
      }
      .content {
        border-radius: 5px;
        height: 100%;
        overflow: auto;
        .showTree {
          height: 100%;
          overflow: auto;
        }
      }
    }
    .right-div {
      flex: 1;
      display: flex;
      flex-direction: column;
    }
  }

  .categories-page {
    .tree-div {
      .h-full {
        height: auto;
      }
      .search-div {
        .ant-btn-primary {
          background-color: #2a7dc9;
        }
        .ant-input-search-button {
          width: 42px;
        }
      }
    }
  }
  .categories-modal {
    .ant-modal-footer > button {
      display: none;
    }
    .ant-modal-footer {
      margin-top: 0px;
      border-top: 0px;
    }
  }
  // ant-table-header

  .content-full {
    white-space: pre-wrap;
    word-break: break-all;
    overflow-wrap: break-word;
    max-width: 100%;
    display: block;
  }
</style>
