import React, { useEffect, useState } from 'react';
import './index.scss';
import { Button, message, Modal, Table } from 'antd';
import { useNavigate } from 'react-router-dom';
import { ColumnsType } from 'antd/es/table';
import { CategoryManageAPI, IndustryManageAPI } from '~/api';
import AddOrEditIndustryModal from './components/addOrEditIndustryModal';
import { InterDataType, InterReqType, PaginationProps } from '~/api/interface';
import { categoryListType } from '~/api/interface/categoryManage';
import SearchBox, { searchColumns } from '~/components/search-box';
import { PlusOutlined } from '@ant-design/icons';
import { listIndustryType } from '~/api/interface/industryManageType';

//行业列表返回类型
type industryListType = InterDataType<listIndustryType>['list'];
//行业列表筛选类型
type industrySearchParameter = InterReqType<listIndustryType>;
//分类通用类型
type categoryResponseType = InterDataType<categoryListType>['list'];

function IndustryList() {
  // 路由操作
  const navigate = useNavigate();
  const [searchColumns, setSearchColumns] = useState<searchColumns[]>([
    {
      label: '方案名称',
      type: 'input',
      placeholder: '请输入方案名称',
      name: 'solutionName',
    },
    {
      label: '所属行业',
      type: 'select',
      placeholder: '请选择所属行业',
      name: 'categoryId',
      options: [],
    },
  ]);
  // 表格数据
  const [tableData, setTableData] = useState<industryListType>([]);
  // 加载中
  const [loading, setLoading] = useState<boolean>(false);
  //行业-筛选
  const [query, setQuery] = useState<Omit<industrySearchParameter, 'pageSize' | 'pageNo'>>({
    categoryId: undefined,
    solutionName: undefined,
  });
  //行业分类列表
  const [industryCategoryList, setIndustryCategoryList] = useState<categoryResponseType>([]);
  // 表格结构
  const columns: ColumnsType<industryListType[0]> = [
    { title: '方案名称', dataIndex: 'solutionName', align: 'center' },
    {
      title: '所属行业',
      align: 'center',
      dataIndex: 'categoryName',
    },
    { title: '描述', dataIndex: 'description', align: 'center' },
    {
      title: '操作',
      align: 'center',
      width: '15%',
      fixed: 'right',
      render: (record) => {
        return (
          <div>
            <Button type='link' onClick={() => handleDetail(record)}>
              详情
            </Button>
            <Button type='link' onClick={() => handleEdit(record)}>
              编辑
            </Button>
            <Button type='link' onClick={() => handleDelete(record)}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  // 表格分页配置
  const [pagination, setPagination] = useState<
    PaginationProps & { totalCount: number; totalPage: number }
  >({
    totalCount: 0,
    pageSize: 10,
    pageNo: 1,
    totalPage: 0,
  });
  // 新增弹窗是否显示
  const [visibleAddEdit, setVisibleAddEdit] = useState(false);
  // 新增弹窗内容
  const [currentIndustryItem, setCurrentIndustryItem] = useState<Partial<industryListType[0]>>();

  //行业列表
  const getIndustryList = (search: Omit<industrySearchParameter, 'pageSize' | 'pageNo'>) => {
    setLoading(true);
    IndustryManageAPI.getIndustryList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...search,
    }).then(({ result }) => {
      setLoading(false);
      setTableData(result.list || []);
      pagination.totalCount = result.totalCount;
      pagination.totalPage = result.totalPage;
      setPagination(pagination);
    });
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getIndustryList(query);
  };
  // 行业-筛选
  const searchIndustryEvent = (val: any) => {
    setQuery(val);
    getIndustryList(val);
  };
  //获取行业目录下的分类
  const getIndustryCategory = () => {
    CategoryManageAPI.getCategoryList({ pageNo: 1, pageSize: 99999, type: 0, directoryId: 2 }).then(
      ({ result }) => {
        if (result.list) {
          setIndustryCategoryList(result.list);
          const industryOptions = result.list.map((v) => ({ id: v.id, name: v.classifyName }));
          searchColumns[1].options = industryOptions;
          setSearchColumns(searchColumns);
        }
      },
    );
  };
  // 新增弹窗
  const handleAdd = () => {
    setVisibleAddEdit(true);
    setCurrentIndustryItem(undefined);
  };
  // 编辑弹窗
  const handleEdit = (record: industryListType[0]) => {
    setVisibleAddEdit(true);
    setCurrentIndustryItem(record);
  };
  // 关闭弹窗
  const addOrEditIndustryModalClose = () => {
    setVisibleAddEdit(false);
    setCurrentIndustryItem(undefined);
  };
  //新增或编辑成功
  const addOrEditSuccess = () => {
    getIndustryList(query);
  };
  //行业删除
  const handleDelete = (record: industryListType[0]) => {
    Modal.confirm({
      content: '确认删除该行业?',
      onOk: () => {
        IndustryManageAPI.removeIndustryRequest({ id: record.id }).then(({ code }) => {
          if (code === '200') {
            message.success('删除成功');
            if (tableData.length === 1 && pagination.pageNo !== 1) {
              pagination.pageNo -= 1;
            }
            getIndustryList(query);
          }
        });
      },
    });
  };
  // 跳转详情
  const handleDetail = (record: industryListType[0]) => {
    navigate({
      pathname: '/mallManage/industryDetail',
      search: `id=${record.id}`,
    });
  };

  useEffect(() => {
    getIndustryCategory();
    getIndustryList(query);
  }, []);

  return (
    <div className='industry-list'>
      <SearchBox
        search={searchColumns}
        child={
          <Button type='primary' icon={<PlusOutlined />} onClick={handleAdd}>
            新增
          </Button>
        }
        searchData={searchIndustryEvent}
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1500 }}
        bordered
        loading={loading}
        pagination={{
          total: pagination.totalCount,
          pageSize: pagination.pageSize,
          current: pagination.pageNo,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />

      <AddOrEditIndustryModal
        open={visibleAddEdit}
        industryItem={currentIndustryItem}
        categoryIndustryList={industryCategoryList}
        close={addOrEditIndustryModalClose}
        addOrEditSuccess={addOrEditSuccess}
      />
    </div>
  );
}
export default IndustryList;
