import React, { useEffect, useState } from "react";
// antd 组件
import { Form, Button, Table, Select, Input, Space, message } from 'antd';
import { SearchOutlined, ReloadOutlined, PlusOutlined } from '@ant-design/icons';
// 类型定义
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
// umi 相关
// 弹窗组件
import CategoryAddModal from './components/CategoryAddModal';
import SupplierAddModal from './components/SupplierAddModal';
import SupplierListModal from './components/SupplierListModal';
// mock服务
import { getCategoryStoreList } from './services';

const { Option } = Select;

// 列表数据接口
interface Data {
  id: number;
  storeName: string;
  category: string;
  region: string;
  unit: string;
  owner: string;
  validTo: string;
  supplierCount: number;
}

const CategoryManage: React.FC = () => {
  // 搜索表单
  const [form] = Form.useForm();
  // 列表数据
  const [data, setData] = useState<Data[]>([]);
  // 列表加载
  const [loading, setLoading] = useState(false);
  // 分页
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 188 });

  // 新增弹窗
  const [addVisible, setAddVisible] = useState(false);
  // 添加供应商弹窗
  const [addSupplierVisible, setAddSupplierVisible] = useState(false);
  const [currentStoreId, setCurrentStoreId] = useState<number | null>(null);
  // 库内供应商数量弹窗
  const [supplierListVisible, setSupplierListVisible] = useState(false);

  // 获取列表
  const getList = async (page: number = 1, pageSize: number = 10) => {
    setLoading(true);
    try {
      // mock 请求
      const { code, data, total } = await getCategoryStoreList({ page, pageSize, ...form.getFieldsValue() });
      if (code === 200) {
        setData(data);
        setPagination({ ...pagination, current: page, pageSize, total });
      }
    } finally {
      setLoading(false);
    }
  };

  // 查询
  const handleSearch = () => {
    setPagination({ ...pagination, current: 1 });
    getList(1, pagination.pageSize || 10);
  };

  // 重置
  const handleReset = () => {
    form.resetFields();
    setPagination({ ...pagination, current: 1 });
    getList(1, pagination.pageSize || 10);
  };

  // 初始化
  useEffect(() => {
    getList();
  }, []);

  // 列表表头
  const columns: ColumnsType<Data> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 60,
      render: (_: any, __: any, idx: number) => ((pagination.current! - 1) * (pagination.pageSize || 10)) + idx + 1,
    },
    {
      title: '品类库名称',
      dataIndex: 'storeName',
      key: 'storeName',
      align: 'center',
    },
    {
      title: '品类',
      dataIndex: 'category',
      key: 'category',
      align: 'center',
    },
    {
      title: '区域',
      dataIndex: 'region',
      key: 'region',
      align: 'center',
    },
    {
      title: '创建单位',
      dataIndex: 'unit',
      key: 'unit',
      align: 'center',
    },
    {
      title: '负责人',
      dataIndex: 'owner',
      key: 'owner',
      align: 'center',
    },
    {
      title: '有效期至',
      dataIndex: 'validTo',
      key: 'validTo',
      align: 'center',
    },
    {
      title: '库内供应商数量',
      dataIndex: 'supplierCount',
      key: 'supplierCount',
      align: 'center',
      render: (val: number, record) => (
        <a
          style={{ color: '#1677ff' }}
          onClick={() => {
            setCurrentStoreId(record.id);
            setSupplierListVisible(true);
          }}
        >
          {val}
        </a>
      ),
    },
    {
      title: '操作',
      key: 'option',
      align: 'center',
      render: (record: any) => (
        <a
          style={{ color: '#1677ff' }}
          onClick={() => {
            setCurrentStoreId(record.id);
            setAddSupplierVisible(true);
          }}
        >
          添加供应商
        </a>
      ),
    },
  ];

  return (
    <>
      {/* 查询区 */}
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 12 }}
      >
        <Form.Item name="storeName" label="品类库名称">
          <Input placeholder="请输入品类库名称" style={{ width: 180 }} />
        </Form.Item>
        <Form.Item name="unit" label="创建单位">
          <Select style={{ width: 150 }} allowClear>
            <Option value="集团">集团</Option>
            <Option value="分公司">分公司</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
            查询
          </Button>
          <Button icon={<ReloadOutlined />} style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
          </Button>
        </Form.Item>
        <Form.Item>
          <Button type="primary" icon={<PlusOutlined />} style={{ marginLeft: 8 }} onClick={() => setAddVisible(true)}>
            新增
          </Button>
        </Form.Item>
      </Form>
      {/* 表格 */}
      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page, pageSize) => getList(page, pageSize),
        }}
        scroll={{ x: 'max-content' }}
      />

      {/* 新增品类库弹窗 */}
      <CategoryAddModal
        visible={addVisible}
        onCancel={() => setAddVisible(false)}
        onSuccess={() => {
          setAddVisible(false);
          getList();
        }}
      />
      {/* 添加供应商弹窗 */}
      <SupplierAddModal
        visible={addSupplierVisible}
        storeId={currentStoreId}
        onCancel={() => setAddSupplierVisible(false)}
        onSuccess={() => {
          setAddSupplierVisible(false);
          getList();
        }}
      />
      {/* 库内供应商数量弹窗 */}
      <SupplierListModal
        visible={supplierListVisible}
        storeId={currentStoreId}
        onCancel={() => setSupplierListVisible(false)}
      />
    </>
  );
};

export default CategoryManage;
