import React, { useEffect, useState } from 'react';
import './index.scss';
import { Button, Form, Input, message, Modal, Select, Table } from 'antd';
import { useNavigate } 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 { categoryListType, directoryListType } from '~/api/interface/categoryManage';
import { MakeListType } from '~/api/interface/makeManage';

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

const { Option } = Select;
const { confirm } = Modal;

function ProduceManage() {
  // 路由操作
  const navigate = useNavigate();
  // 表格数据
  const [tableData, setTableData] = useState<produceListType>([]);
  //筛选表单
  const [query, setQuery] = useState<produceParametersType>();
  // 加载中
  const [loading, setLoading] = useState<boolean>(false);
  // 产品类型下拉列表
  const [productTypeSelectList, setProductTypeSelectList] = useState<categoryType>([]);
  // 新增弹窗是否显示
  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 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;
    getProduceList(query);
  };
  // 表单提交
  const onFinish = (val: produceListType) => {
    // 在这里对提交的数据做处理，如range转为开始和结束时间
    const data = Object.fromEntries(
      // 过滤为空项
      Object.entries({
        ...val,
      }).filter(
        (i) => (typeof i[1] === 'string' && i[1] !== '') || (i[1] !== undefined && i[1] !== null),
      ),
    );
    setQuery(data);
    getProduceList(data);
  };
  //品牌列表
  const getMakeList = () => {
    MakeManageAPI.getListBrandInfo({ pageNo: 1, pageSize: 9999 }).then(({ result }) => {
      setMakeList(result.list || []);
    });
  };
  // 目录列表
  const getDirectoryList = () => {
    CategoryManageAPI.getDirectoryListClone({ type: 4 }).then(({ result }) => {
      setDecList(result || []);
    });
  };
  //根据目录获取分类
  const getCategoryListByDirectory = (directoryId: number) => {
    CategoryManageAPI.getCategoryList({ pageNo: 1, pageSize: 99999, directoryId, type: 4 }).then(
      ({ result }) => {
        setProductTypeSelectList(result.list || []);
      },
    );
  };
  // 目录修改
  const decSelectChange = (value: number) => {
    if (value) {
      getCategoryListByDirectory(value);
    }
  };
  // componentDidMount
  useEffect(() => {
    getProduceList(query);
    getDirectoryList();
  }, []);

  return (
    <div className='from-table-wrap'>
      <div className='header-view'>
        <Form name='basic' layout='inline' onFinish={onFinish}>
          <Form.Item>
            <Button type='primary' onClick={handleAdd}>
              新增
            </Button>
          </Form.Item>
          <Form.Item name='productName' label='产品名称'>
            <Input placeholder='请输入产品名称' allowClear />
          </Form.Item>
          <Form.Item name='directoryId' label='产品目录'>
            <Select placeholder='请选择产品目录' onChange={decSelectChange} allowClear>
              {decList.map((v, index: number) => (
                <Select.Option value={v.id} key={index}>
                  {v.directoryName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name='goodsTypeId' label='产品类型'>
            <Select placeholder='请选择产品类型' allowClear>
              {productTypeSelectList.map((i, j) => (
                <Option value={i.id} key={j}>
                  {i.classifyName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>
              搜索
            </Button>
          </Form.Item>
        </Form>
      </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;
