import React, { useEffect, useRef, useState } from 'react';
import './index.scss';
import { Button, message, Modal, Table } from 'antd';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { ColumnsType } from 'antd/es/table';
import { CategoryManageAPI, MakeManageAPI, ProduceManageAPI } from '~/api';
import AddOrEditProduce from './components/addOrEditProduceModal';
import { InterDataType, InterReqType, PaginationProps } from '~/api/interface';
import { addProductType, productListType } from '~/api/interface/produceManageType';
import { directoryListType } from '~/api/interface/categoryManage';
import { MakeListType } from '~/api/interface/makeManage';
import { PlusOutlined } from '@ant-design/icons';
import qs from 'query-string';
import SearchBox, { searchColumns } from '~/components/search-box';

//产品列表返回类型
type produceListType = InterDataType<productListType>['list'];
//产品列表参数类型
type produceParametersType = Omit<InterReqType<productListType>, 'pageSize' | 'pageNo'>;
//目录返回类型
type directoryType = InterDataType<directoryListType>;
//品牌返回类型
type makeListType = InterDataType<MakeListType>['list'];
//新增编辑表单类型
type addMakeParameterType = InterReqType<addProductType>;

const { confirm } = Modal;

function ProduceManage() {
  const searchRef = useRef<any>();
  // 路由操作
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  // 表格数据
  const [tableData, setTableData] = useState<produceListType>([]);
  //筛选表单
  const [query, setQuery] = useState<produceParametersType>();
  // 加载中
  const [loading, setLoading] = useState<boolean>(false);
  // 新增弹窗是否显示
  const [visibleAddEdit, setVisibleAddEdit] = useState(false);
  // 新增弹窗内容
  const [addEditData, setAddEditData] = useState<
    addMakeParameterType & { id: number; categoriesId: number }
  >();
  // 品牌列表
  const [makeList, setMakeList] = useState<makeListType>([]);
  // 目录列表
  const [decList, setDecList] = useState<directoryType>([]);
  // 表格结构
  const columns: ColumnsType<produceListType[0]> = [
    {
      title: '产品名称',
      dataIndex: 'productName',
      align: 'center',
      fixed: 'left',
    },
    {
      title: '产品目录',
      dataIndex: 'directoryName',
      align: 'center',
    },
    { title: '产品类型', dataIndex: 'categoryName', align: 'center' },
    { title: '型号', dataIndex: 'model', align: 'center' },
    { title: '产品品牌', dataIndex: 'productBrand', align: 'center' },
    {
      title: '操作',
      align: 'center',
      width: '15%',
      fixed: 'right',
      render: (_text: string, 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 }>({
    pageSize: 10,
    pageNo: 1,
    totalCount: 0,
  });
  //筛选参数
  const [searchColumnsData, setSearchColumnsData] = useState<searchColumns[]>([
    {
      label: '产品名称',
      placeholder: '请输入产品名称',
      type: 'input',
      name: 'productName',
    },
    {
      label: '产品目录',
      placeholder: '请输入产品名称',
      type: 'select',
      name: 'directoryId',
      options: [],
      onSelect: (value) => decSelectChange(value),
    },
    {
      label: '产品类型',
      placeholder: '请输入产品名称',
      type: 'select',
      name: 'categoryId',
      options: [],
    },
  ]);

  // 跳转详情
  const handleDetail = (record: produceListType[0]) => {
    navigate({
      pathname: '/mallManage/produceDetail',
      search: `id=${record.id}`,
    });
  };
  // 新增弹窗
  const handleAdd = () => {
    getMakeList();
    setVisibleAddEdit(true);
    setAddEditData(undefined);
  };
  // 编辑弹窗
  const handleEdit = (record: produceListType[0]) => {
    getMakeList();
    setVisibleAddEdit(true);
    setAddEditData({
      id: record.id,
      categoryId: record.categoriesId,
      directoryId: record.directoryId,
      model: record.model,
      productBrandId: record.productBrandId,
      productName: record.productName,
      categoriesId: record.categoriesId,
    });
  };
  // 关闭弹窗
  const handleAddEditClosed = () => {
    setVisibleAddEdit(false);
    setAddEditData(undefined);
  };
  const addOrEditProduceOk = () => {
    setVisibleAddEdit(false);
    setAddEditData(undefined);
    getProduceList(query);
  };
  // 删除产品
  const handleDelete = (record: produceListType[0]) => {
    confirm({
      title: '提示',
      content: '删除后此数据将会丢失，确定删除吗？',
      onOk() {
        ProduceManageAPI.removeProductSku({ id: record.id }).then(({ code }) => {
          if (code === '200') {
            if (pagination.pageNo != 1 && tableData.length === 1) {
              pagination.pageNo -= 1;
            }
            message.success('删除成功');
            getProduceList(query);
          }
        });
      },
    });
  };
  //产品列表
  const getProduceList = (query?: produceParametersType) => {
    setLoading(true);
    ProduceManageAPI.listPageProductSku({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setLoading(false);
      setTableData(result.list || []);
      pagination.totalCount = result.totalCount;
      setPagination(pagination);
    });
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    setSearchParams(qs.stringify({ ...query, pageNo, pageSize }));
    getProduceList(query);
  };
  // 表单提交
  const onFinish = (val: any) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    // 在这里对提交的数据做处理，如range转为开始和结束时间
    const data = Object.fromEntries(
      // 过滤为空项
      Object.entries({
        ...val,
      }).filter(
        (i) => (typeof i[1] === 'string' && i[1] !== '') || (i[1] !== undefined && i[1] !== null),
      ),
    );
    setQuery(data);
    setSearchParams(
      qs.stringify({ ...data, pageNo: pagination.pageNo, pageSize: pagination.pageSize }),
    );
    getProduceList(data);
  };
  //品牌列表
  const getMakeList = () => {
    MakeManageAPI.getListBrandInfo({ pageNo: 1, pageSize: 9999 }).then(({ result }) => {
      setMakeList(result.list || []);
    });
  };
  // 目录列表
  const getDirectoryList = () => {
    ProduceManageAPI.getProductDirectoryList().then(({ result }) => {
      setDecList(result || []);
      searchColumnsData[1].options = (result || []).map((v) => ({
        name: v.directoryName,
        id: v.id,
      }));
      searchColumnsData.splice(1, 1, searchColumnsData[1]);
      setSearchColumnsData([...searchColumnsData]);
    });
  };
  //根据目录获取分类
  const getCategoryListByDirectory = (directoryId: number) => {
    CategoryManageAPI.getCategoryList({ pageNo: 1, pageSize: 99999, directoryId, type: 4 }).then(
      ({ result }) => {
        searchColumnsData[2].options = (result.list || []).map((v) => ({
          name: v.classifyName,
          id: v.id,
        }));
        searchColumnsData.splice(2, 1, searchColumnsData[2]);
        setSearchColumnsData([...searchColumnsData]);
      },
    );
  };
  // 目录修改
  const decSelectChange = (value: number) => {
    if (value) {
      (searchRef.current as any).getForm().setFieldValue('categoryId', undefined);
      getCategoryListByDirectory(value);
    }
  };
  // componentDidMount
  useEffect(() => {
    pagination.pageNo = Number(searchParams.get('pageNo') || 1);
    pagination.pageSize = Number(searchParams.get('pageSize') || 10);
    (searchRef.current as any).getForm().setFieldsValue({
      productName: searchParams.get('productName') || undefined,
      directoryId: searchParams.get('directoryId')
        ? Number(searchParams.get('directoryId'))
        : undefined,
      categoryId: searchParams.get('categoryId')
        ? Number(searchParams.get('categoryId'))
        : undefined,
    });
    setQuery({
      productName: searchParams.get('productName') || undefined,
      directoryId: searchParams.get('directoryId')
        ? Number(searchParams.get('directoryId'))
        : undefined,
      categoryId: searchParams.get('categoryId')
        ? Number(searchParams.get('categoryId'))
        : undefined,
    });
    getProduceList({
      productName: searchParams.get('productName') || undefined,
      directoryId: searchParams.get('directoryId')
        ? Number(searchParams.get('directoryId'))
        : undefined,
      categoryId: searchParams.get('categoryId')
        ? Number(searchParams.get('categoryId'))
        : undefined,
    });
    getDirectoryList();
    if (searchParams.get('directoryId')) {
      getCategoryListByDirectory(Number(searchParams.get('directoryId')));
    }
  }, []);

  return (
    <div className='from-table-wrap'>
      <div className='header-view'>
        <SearchBox
          search={searchColumnsData}
          searchData={onFinish}
          child={
            <Button type='primary' onClick={handleAdd} icon={<PlusOutlined />}>
              新增产品
            </Button>
          }
          baseRef={searchRef}
        />
      </div>
      <Table
        size='small'
        dataSource={tableData}
        loading={loading}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1500 }}
        bordered
        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} 条数据`,
        }}
      />
      <AddOrEditProduce
        open={visibleAddEdit}
        closed={handleAddEditClosed}
        data={addEditData}
        makeList={makeList}
        decList={decList}
        onOk={addOrEditProduceOk}
      />
    </div>
  );
}
export default ProduceManage;
