<template>
  <ResizePageWrapper dense contentFullHeight fixed-height contentClass="flex">
    <template #resizeLeft>
      <div class="overflow-hidden">
        <div>
          <div
            class="flex justify-between text-base font-bold items-center h-50px"
            style="padding: 18px 10px 18px 16px; border-bottom: 1px solid #eee"
            >{{ t('数据字典分类')
            }}<Icon icon="gridicons:add" size="20" :color="primaryColor" @click="handleCateAdd"
          /></div>
          <div>
            <div
              class="flex justify-between pl-4 pr-10px h-10 items-center"
              :style="
                it.id == dicCateId
                  ? `background:#F7FBFF;border-left:4px solid ${primaryColor}`
                  : 'border-left:4px solid transparent'
              "
              v-for="it in categoryList"
              :key="it.id"
            >
              <div
                @click="handleCate(it.id)"
                class="cursor-pointer overflow-hidden text-ellipsis whitespace-nowrap"
                style="width: calc(100% - 40px)"
                ><a-tooltip
                  placement="left"
                  :title="t(it.typeName)"
                  :get-popup-container="getPopupContainer"
                >
                  {{ t(it.typeName) }}
                </a-tooltip></div
              >
              <div>
                <Icon
                  icon="mdi:edit-circle"
                  size="18"
                  :color="it.id == dicCateId ? primaryColor : 'rgba(28,141,255,0.3)'"
                  class="cursor-pointer mr-5px"
                  @click="handleCateEdit(it)" />
                <Icon
                  icon="zondicons:minus-solid"
                  :color="it.id == dicCateId ? '#FF5461' : 'rgba(255,84,97,0.3)'"
                  class="cursor-pointer"
                  @click="handleCateDelete(it)"
              /></div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template #resizeRight>
      <PageWrapper
        dense
        contentFullHeight
        fixedHeight
        contentClass="flex"
        :contentStyle="{ marginTop: 0 }"
      >
        <div class="flex w-1/2 pb-10px">
          <div style="width: 100%; padding: 0 10px 0 0">
            <BasicTable @register="registerTableItem" @row-click="handleRowClick">
              <template #toolbar>
                <a-button type="primary" v-auth="'dic:addItems'" @click="handleItemCreate">{{
                  t('新增项')
                }}</a-button>
              </template>
              <template #action="{ record }">
                <TableAction
                  stopButtonPropagation
                  :actions="[
                    {
                      label: '编辑',
                      auth: 'dic:edit',
                      onClick: handleItemEdit.bind(null, record),
                    },
                    {
                      label: '删除',
                      auth: 'dic:delete',
                      color: 'error',
                      popConfirm: {
                        title: t('是否确认删除'),
                        confirm: handleItemDelete.bind(null, record),
                      },
                    },
                  ]"
                />
              </template>
            </BasicTable>
          </div>
        </div>
        <div class="w-1/2 pb-10px">
          <BasicTable @register="registerTableDetail">
            <template #toolbar>
              <a-button type="primary" v-auth="'dic:addDictionary'" @click="handleDetailCreate">{{
                t('新增字典')
              }}</a-button>
            </template>
            <template #action="{ record }">
              <TableAction
                stopButtonPropagation
                :actions="[
                  {
                    label: '编辑',
                    auth: 'dic:edit',
                    onClick: handleDetailEdit.bind(null, record),
                  },
                  {
                    label: '删除',
                    auth: 'dic:delete',
                    color: 'error',
                    popConfirm: {
                      title: t('是否确认删除'),
                      confirm: handleDetailDelete.bind(null, record),
                    },
                  },
                ]"
              />
            </template>
          </BasicTable>
        </div>
        <DicCateDrawer @register="registerModal" @success="handleCateSuccess" />
        <DicItemDrawer @register="registerItemModal" @success="handleItemSuccess" />

        <DicDetailDrawer @register="registerDetailModal" @success="handleDetailSuccess" />
      </PageWrapper>
    </template>
  </ResizePageWrapper>
</template>
<script lang="ts">
  import { createVNode, defineComponent, ref } from 'vue';
  import { ResizePageWrapper } from '/@/components/Page';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import {
    getDicItemPageList,
    getDicDetailPageList,
    deleteDicItem,
    deleteDicDetail,
    getDicCateList,
    deleteDicCate,
  } from '/@/api/system/dic';
  import { PageWrapper } from '/@/components/Page';
  import Icon from '/@/components/Icon/index';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import DicItemDrawer from './components/DicItemDrawer.vue';
  import DicCateDrawer from './components/DicCateDrawer.vue';
  import DicDetailDrawer from './components/DicDetailDrawer.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { Modal } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { primaryColor } from '../../../../build/config/themeConfig';
  import { useModal } from '/@/components/Modal';
  const getPopupContainer = (trigger: HTMLElement) => {
    return trigger.parentElement;
  };
  const { t } = useI18n();
  export const searchFormSchemaItem: FormSchema[] = [
    {
      field: 'name',
      label: t('项目名'),
      component: 'Input',
    },
    {
      field: 'code',
      label: t('编码'),
      component: 'Input',
    },
  ];

  export const itemColumns: BasicColumn[] = [
    {
      title: t('项目名'),
      dataIndex: 'name',
      width: 150,
      align: 'center',
      resizable: true,
    },
    {
      title: t('编号'),
      dataIndex: 'code',
      width: 120,
      align: 'center',
      resizable: true,
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      align: 'center',
      resizable: true,
    },
  ];

  export const searchFormSchemaDetail: FormSchema[] = [
    {
      field: 'name',
      label: t('字典名'),
      component: 'Input',
    },
    {
      field: 'code',
      label: t('编码'),
      component: 'Input',
    },
  ];

  export const detailColumns: BasicColumn[] = [
    {
      title: t('字典名'),
      dataIndex: 'name',
      width: 150,
      align: 'center',
      resizable: true,
    },
    {
      title: t('编号'),
      dataIndex: 'code',
      width: 120,
      align: 'center',
      resizable: true,
    },
    {
      title: t('值'),
      dataIndex: 'value',
      width: 120,
      align: 'center',
      resizable: true,
    },
    {
      title: t('备注'),
      align: 'center',
      dataIndex: 'remark',
      resizable: true,
    },
  ];

  export default defineComponent({
    name: 'DicManagement',
    components: {
      BasicTable,
      PageWrapper,
      TableAction,
      DicItemDrawer,
      DicDetailDrawer,
      Icon,
      DicCateDrawer,
      ResizePageWrapper,
    },
    setup() {
      const { notification } = useMessage();

      const selectItemId = ref('');
      const categoryList = ref();
      const dicCateId = ref('1');
      fetchCate();
      const { hasPermission } = usePermission();
      const [registerModal, { openModal: openCateModal }] = useModal();
      const [registerItemModal, { openModal: openItemModal }] = useModal();
      const [registerDetailModal, { openModal: openDetailModal }] = useModal();

      const [registerTableItem, { reload: itemReload }] = useTable({
        title: t('数据字典项'),
        api: getDicItemPageList,
        beforeFetch: (params) => {
          //发送请求默认新增  左边树结构所选机构id
          return { ...params, typeId: dicCateId.value };
        },
        rowKey: 'id',
        columns: itemColumns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchemaItem,
          showResetButton: false,
        },
        rowSelection: {
          type: 'radio',
          onChange: onSelectChange,
        },
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        actionColumn: {
          width: 88,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        tableSetting: {
          size: false,
        },
        customRow: (record) => {
          return {
            ondblclick: () => {
              if (hasPermission('dic:edit')) {
                handleItemEdit(record);
              }
            },
          };
        },
      });
      const [registerTableDetail, { reload: detailReload }] = useTable({
        title: t('数据字典详情'),
        api: getDicDetailPageList,
        rowKey: 'id',
        columns: detailColumns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchemaDetail,
          showResetButton: false,
        },
        beforeFetch: (params) => {
          //发送请求默认新增  左边树结构所选机构id
          return { ...params, itemId: selectItemId.value };
        },
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        actionColumn: {
          width: 88,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        tableSetting: {
          size: false,
        },
        customRow: (record) => {
          return {
            ondblclick: () => {
              if (hasPermission('dic:edit')) {
                handleDetailEdit(record);
              }
            },
          };
        },
      });

      function handleRowClick(record: any) {
        selectItemId.value = record.id;
        detailReload();
      }
      function onSelectChange(rowKey: string[]) {
        selectItemId.value = rowKey[0];
        detailReload();
      }
      function handleItemCreate() {
        openItemModal(true, {
          isUpdate: false,
          parentId: dicCateId.value,
        });
      }
      function handleCateAdd() {
        openCateModal(true, {
          isUpdate: false,
        });
      }
      function handleDetailCreate() {
        if (!selectItemId.value) {
          notification.warning({
            message: t('提示'),
            description: t('没有选择任意一行字典项！'),
          });
          return;
        }

        openDetailModal(true, {
          itemId: selectItemId.value,
          isUpdate: false,
        });
      }

      function handleItemEdit(record: Recordable) {
        openItemModal(true, {
          record,
          isUpdate: true,
          parentId: dicCateId.value,
        });
      }
      function handleDetailEdit(record: Recordable) {
        console.log(record);
        openDetailModal(true, {
          record,
          isUpdate: true,
        });
      }

      function handleItemDelete(record: Recordable) {
        deleteDicItem([record.id]).then((_) => {
          itemReload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          }); //提示消息
        });
      }

      function handleDetailDelete(record: Recordable) {
        deleteDicDetail([record.id]).then((_) => {
          detailReload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          }); //提示消息
        });
      }
      function handleCateSuccess() {
        fetchCate();
      }
      function handleItemSuccess() {
        itemReload();
      }

      function handleDetailSuccess() {
        detailReload();
      }
      function fetchCate() {
        getDicCateList().then((res) => {
          categoryList.value = res;
        });
      }
      function handleCateEdit(record) {
        openCateModal(true, {
          record,
          isUpdate: true,
        });
      }
      function handleCateDelete(record) {
        Modal.confirm({
          title: '删除分类会把分类下的字典项一起删除，确定要删掉吗？',
          icon: createVNode(ExclamationCircleOutlined),
          content: '',
          okText: t('确定'),
          okType: 'danger',
          cancelText: t('取消'),
          onOk() {
            deleteDicCate([record.id]).then((_) => {
              fetchCate();
              notification.success({
                message: t('提示'),
                description: t('删除成功'),
              }); //提示消息
            });
          },
          onCancel() {},
        });
      }
      function handleCate(id) {
        dicCateId.value = id;
        itemReload();
      }
      return {
        registerTableItem,
        registerTableDetail,
        registerItemModal,
        registerDetailModal,
        handleItemCreate,
        handleItemEdit,
        handleItemDelete,
        handleDetailCreate,
        handleDetailEdit,
        handleDetailDelete,
        handleItemSuccess,
        handleDetailSuccess,
        handleRowClick,
        t,
        handleCateAdd,
        registerModal,
        handleCateSuccess,
        handleCateEdit,
        handleCateDelete,
        handleCate,
        categoryList,
        getPopupContainer,
        dicCateId,
        primaryColor,
      };
    },
  });
</script>
<style scoped>
  :deep(.vben-basic-table-header__toolbar) {
    min-width: auto;
  }
</style>
