import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import {
  Button,
  Table,
  Space,
  message,
  Input,
  Select,
  Form,
  Tooltip,
  Tag,
  TreeSelect,
} from 'antd';
import type { TablePaginationConfig } from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import {
  TemplateStatusText,
  TemplateStatusColor,
  TemplateStatus,
} from '@/dicts/supplierTemplateDict';
import {
  getTemplateList,
  getCategoryTree,
} from '@/servers/api/supplierEvaluate';

const { Option } = Select;

// 处理品类树数据
const processCategoryTree = (data: any[]): any[] => {
  return data.map(item => ({
    title: item.categoryName,
    value: item.id,
    key: item.id,
    selectable: item.type === '1', // 只有类型为品类的节点可选
    children: item.children ? processCategoryTree(item.children) : undefined
  }));
};

const SupplierTemplateManage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();

  const [templateData, setTemplateData] = useState<SupplierEvaluate.TemplateRecord[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<SupplierEvaluate.TemplateSearchParams>({});

  // 品类和部门下拉选项
  const [categoryTreeData, setCategoryTreeData] = useState<any[]>([]);
  const [companyOptions, setCompanyOptions] = useState<{ label: string, value: string }[]>([
    { label: '中山市合创展包装材料有限公司', value: '中山市合创展包装材料有限公司' },
    { label: '广州市科技发展有限公司', value: '广州市科技发展有限公司' },
    { label: '深圳市创新科技有限公司', value: '深圳市创新科技有限公司' },
    { label: '东莞市制造业有限公司', value: '东莞市制造业有限公司' },
  ]);

  // 获取品类树
  const fetchCategoryTree = async () => {
    try {
      const res = await getCategoryTree();
      if (res.success && res.data) {
        // 使用组件外的函数处理数据
        const treeData = processCategoryTree(res.data);
        setCategoryTreeData(treeData);
      }
    } catch (error) {
      console.error('获取品类树失败:', error);
      message.error('获取品类树失败');
    }
  };

  // 获取模板列表
  const fetchTemplateList = async (
    current = 1,
    pageSize = 10,
    params: SupplierEvaluate.TemplateSearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      const requestParams: SupplierEvaluate.TemplateRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
        ...params,
      };

      const res = await getTemplateList(requestParams);

      if (res.success && res.data) {
        // 处理返回的数据
        const records = res.data.records

        setTemplateData(records);
        setPagination({
          ...pagination,
          current: res.data.current,
          pageSize: res.data.size,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取模板列表失败');
      }
    } catch (error) {
      console.error('获取模板列表失败:', error);
      message.error('获取模板列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    fetchTemplateList(pagination.current, pagination.pageSize, {});
    fetchCategoryTree();
  }, []);

  // 处理查看
  const handleView = (record: SupplierEvaluate.TemplateRecord) => {
    // 跳转到详情页面
    history.push({
      pathname: '/supplierTemplateManage/supplierTemplateManageDetail',
      state: {
        id: record.id,
      }
    });
  };

  // 处理编辑
  const handleEdit = (record: SupplierEvaluate.TemplateRecord) => {
    // 跳转到新增页面并传递编辑数据
    history.push({
      pathname: '/supplierTemplateManage/supplierTemplateManageAdd',
      state: {
        isEdit: true,
        editData: record
      }
    });
  };

  // 获取状态标签
  const getStatusTag = (status: string | undefined) => {
    if (!status) return <Tag>未知状态</Tag>;
    const color = TemplateStatusColor[status as keyof typeof TemplateStatusColor] || 'default';
    const text = TemplateStatusText[status as keyof typeof TemplateStatusText] || '未知状态';
    return <Tag color={color}>{text}</Tag>;
  };

  // 处理表格分页变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchTemplateList(newPagination.current, newPagination.pageSize, searchParams);
  };

  const columns = [
    {
      title: '序号',
      render: (_: any, __: SupplierEvaluate.TemplateRecord, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: '模板名称',
      dataIndex: 'templateName',
      key: 'templateName',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (templateName: string) => (
        <Tooltip placement="topLeft" title={templateName}>
          {templateName}
        </Tooltip>
      ),
    },
    {
      title: '品类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 120,
    },
    {
      title: '创建单位',
      dataIndex: 'tenantName',
      key: 'tenantName',
      width: 180,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '创建部门',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      align: 'center' as const,
      render: (_: unknown, record: SupplierEvaluate.TemplateRecord) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => handleView(record)}>
            查看
          </Button>
        </Space>
      ),
    },
  ];

  // 处理添加
  const handleAdd = () => {
    // 跳转到新增页面
    history.push('/supplierTemplateManage/supplierTemplateManageAdd');
  };

  // 处理搜索
  const handleSearch = (values: any) => {
    const { dateRange, ...rest } = values;
    const params: SupplierEvaluate.TemplateSearchParams = { ...rest };

    if (dateRange && dateRange.length === 2) {
      params.dateRange = [dateRange[0].format('YYYY-MM-DD'), dateRange[1].format('YYYY-MM-DD')];
    }

    fetchTemplateList(1, pagination.pageSize, params);
  };

  return (
    <div className={`common-container`}>
      <div className="filter-action-row">
        <Form
          form={form}
          name="search"
          onFinish={handleSearch}
          layout="inline"
          className="filter-form"
        >
          <Form.Item name="templateName" label="模板名称">
            <Input placeholder="请输入模板名称" allowClear />
          </Form.Item>
          <Form.Item name="tenantName" label="创建单位">
            <Select placeholder="请选择创建单位" allowClear style={{ width: 200 }}>
              {companyOptions.map(option => (
                <Option key={option.value} value={option.value}>{option.label}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="categoryId" label="品类">
            <TreeSelect
              placeholder="请选择品类"
              allowClear
              showSearch
              treeNodeFilterProp="title"
              style={{ width: 200 }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={categoryTreeData}
              treeDefaultExpandAll
            />
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                form.resetFields();
                fetchTemplateList(1, pagination.pageSize, {});
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
        <div className="right-buttons">
          <Button type="primary" ghost icon={<PlusOutlined />} onClick={handleAdd}>
            新增
          </Button>
        </div>
      </div>

      <div className="content-area">
        <Table
          columns={columns}
          dataSource={templateData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
        />
      </div>
    </div>
  );
};

export default SupplierTemplateManage;
