import React, { useEffect, useState } from "react";
//第三方UI库/组件
import { Form, Button, Table, Select, Input, Tree, Row, Col, Space, message } from 'antd';
import { SearchOutlined, DownloadOutlined, ReloadOutlined } from '@ant-design/icons';
//类型定义
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
//umi 相关
//本地组件、弹窗、业务逻辑
import SupplierViewModal from './components/SupplierViewModal';
import SupplierDetailModal from './components/SupplierDetailModal';
//本地服务/接口
import { list, treeData, systemDict } from './services';

const { Option } = Select;
//下拉数据接口
type OptionType = { label: string; value: string };
// 列表数据接口
interface Data {
  id: number;
  name: string;
  region: string;
  supplierType: string;
  regTime: string;
  status: string;
}

const groupQualifiedSupplierQuery: React.FC = () => {
  //搜搜表单
  const [form] = Form.useForm();
  // 树数据
  const [dataTree, setDataTree] = useState<any[]>([]);
  //默认选中树
  const [treeSelected, setTreeSelected] = useState<string[]>([]);
  //当前树key
  const [selectedKeys, setSelectedKeys] = useState<string>('');
  //列表数据
  const [data, setData] = useState<Data[]>([]);
  //列表加载
  const [loading, setLoading] = useState(false);
  //分页
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 188 });
  //查看是否显示状态
  const [viewVisible, setViewVisible] = useState(false);
  //准入明细是否显示状态
  const [detailVisible, setDetailVisible] = useState(false);
  //查看、准入明细 参数传递
  const [currentRecord, setCurrentRecord] = useState<any>(null);
  // 境内/境外下拉数据
  const [regionOptions, setRegionOptions] = useState<OptionType[]>([]);
  //集采类别
  const [categoryOptions, setCategoryOptions] = useState<OptionType[]>([]);
  //集采库
  const [storeOptions, setStoreOptions] = useState<OptionType[]>([]);
  // 导出
  const handleExport = () => {
    message.success('导出成功（此处为前端示例，实际应调接口）');
  };
  // 查询
  const handleSearch = () => {
    setPagination({ ...pagination, current: 1 });
    getList(selectedKeys);
  };
  // 重置
  const handleReset = () => {
    form.resetFields();
    setPagination({ ...pagination, current: 1 });
    getList(selectedKeys);
  };
  // 点击树节点请求右表
  const handleTreeSelect = (keys: React.Key[]) => {
    const key = keys[0] as string;
    setSelectedKeys(key);
    getList(key)
  };
  //列表方法
  const getList = async (treeId: string, page: number = 1, pageSize: number = 10) => {
    setLoading(true);
    try {
      const { code, data, msg, total } = await list({ page, pageSize, treeId });
      if (code === 200) {
        setData(data);
        setPagination({ current: page, pageSize, total });
      } else {
        message.error(msg)
      }
    } finally {
      setLoading(false);
    }
  };
  // 辅助递归找第一个叶子 key（一般最下层为叶子）
  const findFirstLeafKey = (nodes: any[]): string | undefined => {
    for (const node of nodes) {
      if (!node.children || node.children.length === 0) return node.key;
      const found = findFirstLeafKey(node.children);
      if (found) return found;
    }
    return undefined;
  };
  // 初始化时选中树第一个叶子节点，并请求右表
  useEffect(() => {
    // 境内/境外 下拉
    systemDict('regionOptions').then((res) => {
      const { code, data } = res;
      if (code == 200) {
        setRegionOptions(data)
      }
    });
    // 集采类别 下拉
    systemDict('categoryOptions').then((res) => {
      const { code, data } = res;
      if (code == 200) {
        setCategoryOptions(data)
      }
    });
    // 集采库 下拉
    systemDict('storeOptions').then((res) => {
      const { code, data } = res;
      if (code == 200) {
        setStoreOptions(data)
      }
    });
    //tree数据
    treeData().then((res) => {
      const { code, data } = res;
      if (code == 200) {
        setDataTree(data)
        const key = findFirstLeafKey(data);
        if (key) {
          setSelectedKeys(key);
          setTreeSelected([key])
          getList(key)
        }
      }
    })
  }, []);


  const columns: ColumnsType<Data> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 60,
      render: (_: any, __: any, idx: number) => idx + 1,
    },
    {
      title: '供应商名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: '统一社会信用代码/税号',
      dataIndex: 'code',
      key: 'code',
      align: 'center',
    },
    {
      title: '境内/境外',
      dataIndex: 'region',
      key: 'region',
      align: 'center',
    },
    {
      title: '企业类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
    },
    {
      title: '注册时间',
      dataIndex: 'regTime',
      key: 'regTime',
      align: 'center',
    },
    {
      title: '操作',
      key: 'option',
      align: 'center',
      render: (record: any) => (
        <Space>
          <a
            style={{ color: '#1677ff' }}
            onClick={() => { setCurrentRecord(record); setViewVisible(true); }}
          >查看</a>
          <a
            style={{ color: '#1677ff' }}
            onClick={() => { setCurrentRecord(record); setDetailVisible(true); }}
          >准入明细</a>
        </Space>
      ),
    },
  ];

  return (
    <>
      <div style={{ width: '100%', height: '100%' }}>
        <Row gutter={16} style={{ height: 'calc(100% - 30px)' }} >
          {/* 左侧树 */}
          <Col flex="250px" >
            <div style={{
              background: '#fff', height: '100%', padding: '20px 10px',
              overflowX: 'auto',
              overflowY: 'auto',
              width: '250px',
              boxSizing: 'border-box',
              whiteSpace: 'nowrap',
            }}>
             {dataTree.length > 0 && (
                <Tree
                  treeData={dataTree}
                  defaultExpandAll
                  selectedKeys={treeSelected}
                  onSelect={handleTreeSelect}
                />
              )}
             
            </div>
          </Col>
          {/* 右侧主体 */}
          <Col flex="auto" style={{ background: '#fff', width: 'calc(100% - 270px)', height: '100%', padding: '20px' }}>
            {/* 查询表单 */}
            <Form
              form={form}
              layout="inline"
              style={{ marginBottom: 12, }}
            >
              <Form.Item name="name" label="供应商名称">
                <Input placeholder="请输入供应商名称关键字" style={{ width: 180 }} />
              </Form.Item>
              <Form.Item name="category" label="集采类别">
                <Select style={{ width: 150 }} allowClear>
                  {categoryOptions.map(opt => (
                    <Option key={opt.value} value={opt.value}>{opt.label}</Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="store" label="集采库">
                <Select style={{ width: 150 }} allowClear>
                  {storeOptions.map(opt => (
                    <Option key={opt.value} value={opt.value}>{opt.label}</Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="region" label="境内/境外">
                <Select style={{ width: 130 }} allowClear>
                  {regionOptions.map(opt => (
                    <Option key={opt.value} value={opt.value}>{opt.label}</Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item>
                <Button type="primary" icon={<DownloadOutlined />} style={{ marginRight: 8 }} onClick={handleExport}>
                  数据导出
                </Button>
                <Button type="primary" icon={<SearchOutlined />} htmlType="submit" onClick={handleSearch}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} icon={<ReloadOutlined />} onClick={handleReset}>
                  重置
                </Button>
              </Form.Item>
            </Form>
            {/* 表格 */}
            <Table
              rowKey="id"
              columns={columns}
              dataSource={data}
              loading={loading}
              pagination={pagination}
              onChange={(pagination) => getList(selectedKeys, pagination.current!, pagination.pageSize!)}
            />
          </Col>
        </Row>
      </div>
      {/* 查看组件 */}
      <SupplierViewModal
        visible={viewVisible}
        record={currentRecord}
        onCancel={() => setViewVisible(false)}
      />
      {/* 准入明细组件 */}
      <SupplierDetailModal
        visible={detailVisible}
        record={currentRecord}
        onCancel={() => setDetailVisible(false)}
      />
    </>
  );
};

export default groupQualifiedSupplierQuery;
