<template>
  <div class="page-div categories-page">
    <div class="left-div w-1/4 xl:w-1/5 m-4 mr-0">
      <div class="header">
        <div class="buttons-div">
          <a-button type="primary" color="error" @click="buttonClick('left-del')"
            >删除分类</a-button
          >
          <a-button type="primary" color="info" @click="buttonClick('left-add')">添加分类</a-button>
        </div>
        <div class="search-div">
          <a-input-search
            size="small"
            v-model:value="LValue"
            placeholder="搜索"
            enter-button
            @search="searchData('left')"
          />
        </div>
      </div>
      <div class="content">
        <div class="showTree">
          <BasicTree
            ref="treeRef"
            :treeData="showLTree"
            :loading="lLoading"
            @select="
              (selectedKeys, { node }) => {
                getLeftSelectId(node.id);
                changeTypeId(node.key);
              }
            "
          />
        </div>
      </div>
    </div>
    <div class="right-div w-3/4 xl:w-4/5">
      <BasicTable @register="registerTable">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'enabledMark'">
            <a-tag v-if="record.enabledMark" color="success">正常</a-tag>
            <a-tag v-else color="error">停用</a-tag>
          </template>
        </template>
        <template #toolbar>
          <PermissionBtn @btnEvent="buttonClick"></PermissionBtn>
        </template>
      </BasicTable>
    </div>
    <a-modal
      class="categories-modal"
      v-model:open="openModal"
      :title="modalData.title"
      :afterClose="clearModal"
    >
      <UseModal
        ref="modalForm"
        :modalData="modalData"
        @closeModal="closeModal"
        @submit="submit"
        :lTree="lTree"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import UseModal from './Modal/index.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,
    getRightTable,
    addLeftItem,
    addRightItem,
    delLeftItem,
    editRightItem,
    delRightItem,
  } from '@/api/sys/categories';
  import { columns, emptyRightItem, emptyLeftItem, dataProcess, searchFormSchema } from './util';
  import { Modal, message } from 'ant-design-vue';
  import dayjs from 'dayjs';

  const modalForm = ref();
  let LValue = ref('');
  let lLoading = ref(false);
  let typeId = ref('');
  let selectLeftId = ref('');
  let lTree = 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: getRightTable,
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    showIndexColumn: false,
    rowSelection: {
      type: 'checkbox',
    },
    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()
      .then((res) => {
        let data = dataProcess(res);
        lTree.value = data;
        showLTree.value = data;
        lLoading.value = false;
        if (isMounted && data.length > 0) {
          firstRequestCode.value = data[0].key;
          typeId.value = data[0].key;
          unref(treeRef).setSelectedKeys([data[0].key]);
        }
        reload();
      })
      .catch((err) => {
        console.log(err);
        lLoading.value = false;
      });
  };
  onMounted(() => {
    getLeftTreeData(true);
  });
  const changeTypeId = (value) => {
    typeId.value = value;
    reload();
  };
  const getLeftSelectId = (value) => {
    selectLeftId.value = value;
  };
  const searchData = (type) => {
    if (type === 'left') {
      let data = lTree.value.filter((item) => item.title.indexOf(LValue.value) !== -1);
      showLTree.value = data;
    } else {
      reload();
    }
  };
  const submit = () => {
    let userName = localStorage.getItem('fireUserLoginName');
    switch (modalData.type) {
      case 'leftadd':
        addLeftItem(modalData.data)
          .then((res) => {
            getLeftTreeData(false);
            openModal.value = false;
          })
          .catch((err) => {
            console.log(err);
          });
        break;
      case 'rightadd':
        addRightItem({
          ...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 'rightedit':
        editRightItem({
          ...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 buttonClick = (diffType) => {
    const [diff, type] = diffType.split('-');
    let isLeft = diff === 'left';
    switch (type) {
      case 'add':
        openModal.value = true;
        modalData.title = isLeft ? '添加分组' : '添加';
        modalData.data = isLeft ? emptyLeftItem : emptyRightItem;
        modalData.type = `${diff}${type}`;
        break;
      case 'del':
        let check = isLeft
          ? selectLeftId.value === ''
            ? true
            : false
          : getSelectRows().length !== 1
            ? true
            : false;
        if (check) {
          message.warning(isLeft ? '请选择一条分组数据' : '请选择一条数据');
          return;
        }
        Modal.confirm({
          title: '是否确认删除?',
          icon: createVNode(ExclamationCircleOutlined),
          onCancel() {},
          onOk() {
            if (isLeft) {
              return delLeftItem({ id: selectLeftId.value })
                .then((res) => {
                  getLeftTreeData(false);
                  typeId.value = '';
                  reload();
                })
                .catch((err) => {
                  console.log(err);
                });
            } else {
              let selectRightId = getSelectRows()[0].itemDetailId;
              console.log(selectRightId);
              return delRightItem({ id: selectRightId })
                .then((res) => {
                  reload();
                })
                .catch((err) => {
                  console.log(err);
                });
            }
          },
        });
        break;
      case 'edit':
        if (getSelectRows().length !== 1) {
          message.warning('请选择一条数据');
          return;
        }
        let editData = getSelectRows()[0];
        console.log(editData);
        modalData.title = '编辑';
        modalData.data = { ...editData };
        modalData.type = `${diff}${type}`;
        openModal.value = true;
        break;
    }
  };
  const closeModal = () => {
    openModal.value = false;
  };
  const clearModal = () => {
    modalForm.value.clearModalData();
  };
</script>

<style lang="scss" scoped>
  .page-div {
    position: relative;
    top: 10px;
    left: 10px;
    width: calc(100% - 20px);
    height: calc(100% - 20px);
    display: flex;
    .left-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: space-between;
        }
        .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;
    }
  }
</style>
<style lang="scss">
  .categories-page {
    .left-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>
