import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import { Tag, Space, Button, Table, Pagination, message, Modal } from 'antd';
import { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import { FC, useEffect, useState } from 'react';
import { CategoryManageAPI } from '~/api';
import { categoryEntity, categoryDec } from '~/api/interface/categoryManage';
import AddOrEditDec from './components/addOrEditDec';

interface DataType {
  title: string;
  dataIndex: string;
  key: string;
  align: string;
}

const typeOptions = [
  {
    value: 0,
    label: '通用分类',
  },
  {
    value: 1,
    label: '作业服务分类',
  },
  {
    value: 2,
    label: '设备租赁分类',
  },
  {
    value: 3,
    label: '飞手服务分类',
  },
  {
    value: 4,
    label: '产品商城分类',
  },
];

const DirectoryManage: FC = (props: any) => {
  const [data, setData] = useState<categoryDec[]>(); //table数据
  const [loading, setLoading] = useState(false); //table获取数据的loading
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
  });
  //目录modal
  const [isAddOrEditDecModal, setIsAddOrEditDecModal] = useState<boolean>(false);
  const [editData, setEditData] = useState<categoryDec | null>(null);

  const columns: ColumnsType<DataType> = [
    {
      title: '目录名称',
      dataIndex: 'directoryName',
      key: 'directoryName',
      align: 'center',
    },
    {
      title: '分类模块',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      render: (value) => {
        const find = typeOptions.find((item) => {
          return item.value == value;
        });
        return <div>{find?.label}</div>;
      },
    } /* 
    {
      title: '目录类型',
      dataIndex: 'directoryType',
      key: 'directoryType',
      align: 'center',
    },
    {
      title: '上级目录',
      dataIndex: 'relevanceName',
      key: 'relevanceName',
      align: 'center',
    }, */,
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size='middle'>
          <Button
            type='link'
            icon={<EditOutlined />}
            onClick={() => {
              console.log('record', record);
              setEditData(record);
              setIsAddOrEditDecModal(true);
            }}
          >
            编辑
          </Button>
          <Button type='link' danger icon={<DeleteOutlined />} onClick={() => onDel(record.id)}>
            删除
          </Button>
        </Space>
      ),
      align: 'center',
    },
  ];

  useEffect(() => {
    getDirectoryList();
  }, [pagination.current]);

  // 目录弹窗
  const showDecModal = () => {
    setEditData(null);
    setIsAddOrEditDecModal(true);
  };
  const addOrEditDecHandleOk = () => {
    getDirectoryList();
    setIsAddOrEditDecModal(false);
  };
  const addOrEditDecHandleCancel = () => {
    setIsAddOrEditDecModal(false);
  };

  //获取所有目录列表
  const getDirectoryList = () => {
    setLoading(true);
    CategoryManageAPI.directoryList({
      pageNo: pagination!.current!,
      pageSize: pagination!.pageSize!,
    })
      .then((res) => {
        setData(
          res.result?.list.map((item: categoryDec) => {
            if (item.pid) {
              item.directoryType = '有关联用户';
            } else {
              item.directoryType = '无关联用户';
            }
            return item;
          }) || [],
        );
        setLoading(false);
        setPagination({
          ...pagination,
          current: res.result.pageNo,
          pageSize: res.result.pageSize,
          total: res.result.totalCount,
        });
      })
      .catch((err) => {
        setData([]);
        setLoading(false);
      });
  };

  // 删除
  const onDel = (id: number) => {
    Modal.confirm({
      title: '目录删除',
      content: '确认删除该目录?',
      onOk() {
        CategoryManageAPI.removeDirectory(id).then((res) => {
          if (res.code == 200) {
            message.success('删除成功');
            getDirectoryList();
          } else {
            message.error(res.message);
          }
        });
      },
    });
  };

  const handleTableChange = (
    pagination: TablePaginationConfig,
    filters: Record<string, FilterValue>,
    sorter: SorterResult<DataType>,
  ) => {
    setPagination(pagination);

    // `dataSource` is useless since `pageSize` changed
    if (pagination.pageSize !== pagination?.pageSize) {
      setData([]);
    }
  };

  return (
    <>
      <div>
        <Button
          type='primary'
          onClick={() => showDecModal()}
          icon={<PlusOutlined />}
          style={{
            margin: '10px 0 15px 10px',
          }}
        >
          新增目录
        </Button>
        <Table
          rowKey='id'
          columns={columns}
          dataSource={data}
          bordered
          onChange={handleTableChange}
          pagination={pagination}
          loading={loading}
        />
        ;
      </div>
      {/* 目录管理 */}
      <AddOrEditDec
        isModalVisible={isAddOrEditDecModal}
        handleOk={addOrEditDecHandleOk}
        handleCancel={addOrEditDecHandleCancel}
        editData={editData}
      />
    </>
  );
};

export default DirectoryManage;
