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, ProduceManageAPI } from '~/api';
import AddOrEditProduce from './components/addOrEditProduceModal';
import { MakeItemEntity } from './propsType';
import { InterDataType, PaginationProps } from '~/api/interface';
import { productListType } from '~/api/interface/produceManageType';
import { categoryListType, directoryListType } from '~/api/interface/categoryManage';

//产品列表返回类型
type produceListType = InterDataType<productListType>['list'];
//分类返回类型
type categoryType = InterDataType<categoryListType>['list'];
//目录返回类型
type directoryType = InterDataType<directoryListType>;

const { Option } = Select;
const { confirm } = Modal;
// 搜索表单的数据
let query: any = {};

// 表单提交
interface FormType {
  productName?: string;
  goodsTypeId?: number;
}

function ProduceManage() {
  // 路由操作
  const navigate = useNavigate();
  // 表格数据
  const [tableData, setTableData] = useState<produceListType>([]);
  // 加载中
  const [loading, setLoading] = useState<boolean>(false);
  // 产品类型下拉列表
  const [productTypeSelectList, setProductTypeSelectList] = useState<categoryType>([]);
  // 新增弹窗是否显示
  const [visibleAddEdit, setVisibleAddEdit] = useState(false);
  // 新增弹窗内容
  const [addEditData, setAddEditData] = useState<produceListType[0]>();
  // 品牌列表
  const [makeList, setMakeList] = useState<MakeItemEntity[]>([]);
  // 目录列表
  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 = () => {
    setVisibleAddEdit(true);
    setAddEditData(undefined);
  };
  // 编辑弹窗
  const handleEdit = (record: produceListType[0]) => {
    setVisibleAddEdit(true);
    setAddEditData(record);
  };
  // 关闭弹窗
  const handleAddEditClosed = () => {
    setVisibleAddEdit(false);
    setAddEditData(undefined);
    paginationChange(pagination.pageNo, pagination.pageSize);
  };
  // 删除产品
  const handleDelete = (record: produceListType[0]) => {
    confirm({
      title: '提示',
      content: '删除后此数据将会丢失，确定删除吗？',
      async onOk() {
        const res: any = await ProduceManageAPI.removeProductSku({ id: record.id });
        if (res && res.code === '200') {
          await message.success('操作成功');
          await paginationChange(pagination.pageNo, pagination.pageSize);
        } else {
          message.error(res.message);
        }
      },
    });
  };
  //产品列表
  const getProduceList = () => {
    ProduceManageAPI.listPageProductSku({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
    }).then(({ result }) => {
      setTableData(result.list || []);
      setPagination(pagination);
    });
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getProduceList();
  };
  // 表单提交
  const onFinish = (val: FormType) => {
    // 在这里对提交的数据做处理，如range转为开始和结束时间
    const data = Object.fromEntries(
      // 过滤为空项
      Object.entries({
        ...val,
      }).filter((i) => i[1] !== '' && i[1] !== undefined && i[1] !== null),
    );
    query = data;
    // getTableList(data).then();
  };
  // 获取品牌列表
  const getMakeList = () => {
    ProduceManageAPI.getListBrandInfo({ pageNo: 1, pageSize: 999999 }).then(({ code, result }) => {
      setMakeList(result.list || []);
    });
  };
  // 目录列表
  const getDirectoryList = () => {
    CategoryManageAPI.getDirectoryList({ 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();
    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
        visible={visibleAddEdit}
        closed={handleAddEditClosed}
        data={addEditData}
        makeList={makeList}
        decList={decList}
      />
    </div>
  );
}
export default ProduceManage;
