<template>
  <div class="page-div categories-page">
    <div class="tree-div w-1/5 xl:w-1/6 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="showLTree"
            :loading="lLoading"
            :fieldNames="{ key: 'itemValue', title: 'itemName' }"
            @select="
              (selectedKeys, { node }) => {
                getLeftSelectId(node.itemDetailId);
                changeTypeId(node.key);
              }
            "
          />
        </div>
      </div>
    </div>
    <div class="right-div w-4/5 xl:w-5/6">
      <BasicTable @register="registerTable">
        <template #toolbar>
          <PermissionBtn @btnEvent="buttonClick"></PermissionBtn>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key == 'overlay'">
            {{ getOverlay(record) }}
          </template>
          <template v-if="column.key == 'overlayList'">
            <div v-for="tag in record.overlayList" :key="tag">
              <a-tag>{{ tag }}</a-tag>
            </div>
          </template>
        </template>
      </BasicTable>
    </div>
    <a-modal
      class="categories-modal"
      v-model:open="openModal"
      :title="modalData.title"
      :afterClose="clearModal"
      :footer="null"
    >
      <UseModal
        ref="modalForm"
        :modalData="modalData"
        :showLTree="showLTree"
        @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 { columns, emptyRightItem, emptyLeftItem, searchFormSchema } from './util';
  import { Modal, message } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { cloneDeep, forEach } from 'lodash-es';

  const modalForm = ref();
  let lLoading = ref(false);
  let typeId = ref('');
  let selectTreeId = ref('');
  let showLTree = ref([]);
  let openModal = ref(false);
  const modalData = reactive({
    title: '',
    data: {},
    type: '',
  });
  const treeRef = ref();
  const firstRequestCode = ref('');

  const [registerTable, { reload, getSelectRows }] = useTable({
    beforeFetch: (params) => {
      console.log(firstRequestCode.value, 'before');
      if (firstRequestCode.value !== '') {
        params = { ...params, code: firstRequestCode.value };
      } else {
        params = { ...params, code: typeId.value };
      }
      return params;
    },
    api: LoadPage,
    columns,
    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 getLeftTreeData = (isMounted) => {
    lLoading.value = true;
    getLeftTree({ code: 'cloudQueryManagement' })
      .then((res) => {
        showLTree.value = res;
        lLoading.value = false;
        if (isMounted && res.length > 0) {
          firstRequestCode.value = res[0].key;
          typeId.value = res[0].key;
          unref(treeRef).setSelectedKeys([res[0].key]);
        }
        reload();
      })
      .catch((err) => {
        lLoading.value = false;
      });
  };
  onMounted(() => {
    getLeftTreeData(true);
  });
  const changeTypeId = (value) => {
    typeId.value = value;
    reload();
  };
  const getLeftSelectId = (value) => {
    selectTreeId.value = value;
  };

  const buttonClick = (diffType) => {
    let check = false;
    switch (diffType) {
      case 'treeAdd':
        openModal.value = true;
        modalData.title = '添加分组';
        modalData.data = cloneDeep(emptyLeftItem);
        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) => {
                getLeftTreeData(false);
                typeId.value = '';
                reload();
              })
              .catch((err) => {
                console.log(err);
              });
          },
        });
        break;
      case 'btnAdd':
        openModal.value = true;
        modalData.title = '添加';
        modalData.data = cloneDeep(emptyRightItem);
        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: showLTree.value.length,
        })
          .then((res) => {
            getLeftTreeData(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;
        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;
        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;
  };
  const clearModal = () => {
    modalForm.value = cloneDeep(emptyLeftItem);
  };

  const getOverlay = (record) => {
    let result = '';
    showLTree.value.forEach((item: any) => {
      if (item.itemValue === record.overlay) {
        result = item.itemName;
      }
    });
    return result;
  };
</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
</style>
