import React, { useEffect, useState } from "react";
// antd 组件
import { Form, Button, Table, Select, Input, Modal, 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 ViewModal from './components/ViewModal';

// mock服务
import { getPage, approval  } from './services';

const { Option } = Select;

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

const CategoryLibraryManage: 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 [viewVisible, setViewVisible] = useState(false);
 const [currentStoreId, setCurrentStoreId] = useState<string>('');
  // 获取列表
  const getList = async (pageNo: number = 1, pageSize: number = 10) => {
    setLoading(true);
    try {
      // mock 请求
      const { code, data } = await getPage({ basePageRequest: { pageNo, pageSize, ...form.getFieldsValue() } });
      if (code === 200) {
        setData(data.records);
        setPagination({ ...pagination, current: pageNo, pageSize, total: data.total });
      }
    } finally {
      setLoading(false);
    }
  };
  const handleApproval = (id: string) => {
    Modal.confirm({
      title: '是否确认提交审核？',
      onOk: async () => {
        const res = await approval({ id });
        if (res.code === 200) {
          message.success('提交成功');
          getList(); // 刷新列表
        }
      },
    });
  };
  // 查询
  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: 'name',
      key: 'name',
      align: 'center',
      ellipsis: true, 
    },
    {
      title: '品类',
      dataIndex: 'categoryNames',
      key: 'categoryNames',
      align: 'center',
      width: 100, 
      ellipsis: true, 
    },
    {
      title: '区域',
      dataIndex: 'area',
      key: 'area',
      align: 'center',
      ellipsis: true, 
    },
    {
      title: '创建单位',
      dataIndex: 'deptName',
      key: 'deptName',
      align: 'center',
      ellipsis: true, 
    },
    {
      title: '有效期至',
      dataIndex: 'termOfValidity',
      key: 'termOfValidity',
      align: 'center',
      ellipsis: true, 
    },
    {
      title: '申请时间',
      dataIndex: 'approveTime',
      key: 'approveTime',
      align: 'center',
      ellipsis: true, 
    },
    {
      title: '流程状态',
      dataIndex: 'approveStatusName',
      key: 'approveStatusName',
      align: 'center',
    },
    {
      title: '审批结果',
      dataIndex: 'approveResult',
      key: 'approveResult',
      align: 'center',
    },
   
    {
      title: '操作',
      key: 'option',
      align: 'center',
      render: (record: any) => {
        const showSubmit = record.approveStatus === 0;
        return showSubmit ? (
          <a style={{ color: '#1677ff' }} onClick={() => handleApproval(record.id)}>
            提交审核
          </a>
        ) : (
          <a
            style={{ color: '#1677ff' }}
            onClick={() => {
              setCurrentStoreId(record.id);
              setViewVisible(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 name="unit" label="流程状态">
          <Select style={{ width: 150 }} allowClear>
            <Option value="集团">集团</Option>
            <Option value="分公司">分公司</Option>
          </Select>
        </Form.Item>
        <Form.Item name="unit" label="申请时间">
          <Select style={{ width: 150 }} allowClear>
            <Option value="集团">集团</Option>
            <Option value="分公司">分公司</Option>
          </Select>
        </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),
        }}
      />

      {/* 新增品类库弹窗 */}
      <CategoryAddModal
        visible={addVisible}
        onCancel={() => setAddVisible(false)}
        onSuccess={() => {
          setAddVisible(false);
          getList();
        }}
      />
      {/* 新增品类库弹窗 */}
      <ViewModal
        visible={viewVisible}
        storeId={currentStoreId}
        onCancel={() => setViewVisible(false)}
      />
    </>
  );
};

export default CategoryLibraryManage;
