import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Card, Button, Table, Space, Modal, Tag, Tooltip, Input, Form, InputNumber } from 'antd';
import { UserOutlined, SettingOutlined } from '@ant-design/icons';
import styles from '../supplierTaskManageAdd.less';
import EvaluateTaskPersonnelSelector, { PersonnelItem } from '@/components/EvaluateTaskPersonnelSelector/EvaluateTaskPersonnelSelector';

interface EvaluatorSelectStepProps {
  formData: any;
  onFormDataChange: (data: any) => void;
}

interface SupplierItem {
  key: string;
  supplierName: string;
  socialCreditCode: string;
  category: string;
  department: string;
  evaluatorCount: number;
  evaluators?: PersonnelItem[];
}

interface WeightUnit {
  id: string;
  name: string;
  weight: number;
}

const EvaluatorSelectStep = forwardRef<any, EvaluatorSelectStepProps>(({ formData, onFormDataChange }, ref) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [suppliers, setSuppliers] = useState<SupplierItem[]>([]);
  const [batchSelectModalVisible, setBatchSelectModalVisible] = useState(false);
  const [weightSettingModalVisible, setWeightSettingModalVisible] = useState(false);
  const [evaluatorModalVisible, setEvaluatorModalVisible] = useState(false);
  const [currentSupplier, setCurrentSupplier] = useState<SupplierItem | null>(null);
  const [weightUnits, setWeightUnits] = useState<WeightUnit[]>([
    { id: '1', name: '集运', weight: 0 },
    { id: '2', name: '散运', weight: 0 },
    { id: '3', name: '能源', weight: 0 },
    { id: '4', name: '特运', weight: 0 },
    { id: '5', name: '化运', weight: 0 },
  ]);
  const [form] = Form.useForm();

  // 暴露表单方法给父组件
  useImperativeHandle(ref, () => ({
    validateFields: () => {
      // 自定义验证逻辑
      if (suppliers.length === 0) {
        return Promise.reject('请至少添加一个供应商');
      }

      // 检查是否每个供应商都有评价人员
      const hasNoEvaluator = suppliers.some(supplier =>
        !supplier.evaluators || supplier.evaluators.length === 0
      );

      if (hasNoEvaluator) {
        return Promise.reject('存在未分配评价人员的供应商');
      }

      return Promise.resolve();
    },
    getFieldsValue: () => {
      // 构建评价人员列表
      const indicatorList = suppliers.flatMap(supplier =>
        supplier.evaluators?.map(evaluator => ({
          userId: evaluator.id,
          type: 0, // 假设按评价单评价
          indicatorIds: []
        })) || []
      );

      // 构建供应商ID列表
      const supplierIds = suppliers.map(supplier => ({
        id: supplier.key,
        userIds: supplier.evaluators?.map(e => e.id) || []
      }));

      return {
        indicatorList,
        supplierIds,
        suppliersWithEvaluators: suppliers
      };
    },
    setFieldsValue: (values: any) => {
      if (values.suppliersWithEvaluators) {
        setSuppliers(values.suppliersWithEvaluators);
      }
      if (values.weightUnits) {
        setWeightUnits(values.weightUnits);
      }
    },
  }));

  // 从上一步获取供应商数据
  useEffect(() => {
    if (formData.selectedSuppliers) {
      // 转换上一步的供应商数据，添加评价人员数量字段
      const suppliersWithEvaluators = formData.selectedSuppliers.map((supplier: any) => ({
        ...supplier,
        department: supplier.department || '采购部', // 假设部门数据，实际应该从上一步获取
        evaluatorCount: supplier.evaluators?.length || 0,
      }));
      setSuppliers(suppliersWithEvaluators);
    } else {
      // 如果没有从上一步获取到数据，使用模拟数据
      const mockSuppliers: SupplierItem[] = [
        { key: '1', supplierName: '供应商A', socialCreditCode: '123456789012345678', category: '润滑油', department: '采购部', evaluatorCount: 2, evaluators: [
          { id: '1', name: '张三', department: '采购部' },
          { id: '2', name: '李四', department: '技术部' }
        ] },
        { key: '2', supplierName: '供应商B', socialCreditCode: '123456789012345679', category: '燃油', department: '技术部', evaluatorCount: 0 },
        { key: '3', supplierName: '供应商C', socialCreditCode: '123456789012345680', category: '备件', department: '质量部', evaluatorCount: 1, evaluators: [
          { id: '3', name: '王五', department: '质量部' }
        ] },
        { key: '4', supplierName: '供应商D', socialCreditCode: '123456789012345681', category: '计算机', department: '生产部', evaluatorCount: 0 },
      ];
      setSuppliers(mockSuppliers);
    }

    // 初始化权重数据（如果有）
    if (formData.weightUnits) {
      setWeightUnits(formData.weightUnits);
    }
  }, [formData]);

  // 更新表单数据
  const updateFormData = (updatedData: any) => {
    // 构建评价人员列表
    const indicatorList = suppliers.flatMap(supplier =>
      supplier.evaluators?.map(evaluator => ({
        userId: evaluator.id,
        type: 0, // 假设按评价单评价
        indicatorIds: []
      })) || []
    );

    // 构建供应商ID列表
    const supplierIds = suppliers.map(supplier => ({
      id: supplier.key,
      userIds: supplier.evaluators?.map(e => e.id) || []
    }));

    onFormDataChange({
      ...updatedData,
      indicatorList,
      supplierIds
    });
  };

  // 处理批量选择
  const handleBatchSelect = () => {
    if (selectedRowKeys.length === 0) return;
    setBatchSelectModalVisible(true);
  };

  // 处理设置评分单位权重
  const handleWeightSetting = () => {
    // 设置初始表单值
    form.setFieldsValue({
      weightUnits: weightUnits.reduce((acc, unit) => {
        acc[unit.id] = unit.weight;
        return acc;
      }, {} as Record<string, number>)
    });

    setWeightSettingModalVisible(true);
  };

  // 保存权重设置
  const handleSaveWeights = () => {
    form.validateFields().then(values => {
      const updatedWeightUnits = weightUnits.map(unit => ({
        ...unit,
        weight: values.weightUnits[unit.id]
      }));

      setWeightUnits(updatedWeightUnits);
      updateFormData({ weightUnits: updatedWeightUnits });
      setWeightSettingModalVisible(false);
    });
  };

  // 处理选择评价人员
  const handleSelectEvaluators = (supplier: SupplierItem) => {
    setCurrentSupplier(supplier);
    setEvaluatorModalVisible(true);
  };

  // 处理评价人员选择确认
  const handleEvaluatorSelect = (selectedEvaluators: PersonnelItem[]) => {
    if (!currentSupplier) return;

    const updatedSuppliers = suppliers.map(supplier => {
      if (supplier.key === currentSupplier.key) {
        return {
          ...supplier,
          evaluators: selectedEvaluators,
          evaluatorCount: selectedEvaluators.length
        };
      }
      return supplier;
    });

    setSuppliers(updatedSuppliers);
    updateFormData({ suppliersWithEvaluators: updatedSuppliers });
    setEvaluatorModalVisible(false);
  };

  // 处理批量选择评价人员确认
  const handleBatchEvaluatorSelect = (selectedEvaluators: PersonnelItem[]) => {
    if (selectedRowKeys.length === 0) return;

    const updatedSuppliers = suppliers.map(supplier => {
      if (selectedRowKeys.includes(supplier.key)) {
        return {
          ...supplier,
          evaluators: selectedEvaluators,
          evaluatorCount: selectedEvaluators.length
        };
      }
      return supplier;
    });

    setSuppliers(updatedSuppliers);
    updateFormData({ suppliersWithEvaluators: updatedSuppliers });
    setBatchSelectModalVisible(false);
  };

  // 处理删除供应商
  const handleDeleteSupplier = (key: string) => {
    const updatedSuppliers = suppliers.filter(item => item.key !== key);
    setSuppliers(updatedSuppliers);
    updateFormData({ suppliersWithEvaluators: updatedSuppliers });
  };

  // 删除确认对话框
  const showDeleteConfirm = (record: SupplierItem) => {
    Modal.confirm({
      title: '确定要删除此供应商吗？',
      content: `供应商: ${record.supplierName}`,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => handleDeleteSupplier(record.key),
    });
  };

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '供应商名称',
      dataIndex: 'supplierName',
      key: 'supplierName',
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'socialCreditCode',
      key: 'socialCreditCode',
    },
    {
      title: '品类',
      dataIndex: 'category',
      key: 'category',
      render: (text: string) => <Tag color="blue">{text}</Tag>,
    },
    {
      title: '准入部门',
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: '评价人员数',
      dataIndex: 'evaluatorCount',
      key: 'evaluatorCount',
      render: (count: number) => (
        <span style={{ color: count === 0 ? 'red' : 'inherit' }}>
          {count}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: SupplierItem) => (
        <>
          <Button
            type="link"
            onClick={() => handleSelectEvaluators(record)}
          >
            选择评价人员
          </Button>

          {record.evaluatorCount > 0 && (
            <Button
              type="link"
              onClick={() => handleSelectEvaluators(record)}
            >
              查看
            </Button>
          )}

          <Button
            type="link"
            onClick={() => showDeleteConfirm(record)}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  return (
    <div className={styles.evaluatorSelectStep}>
      <Card title="选择评价人员" bordered={false} className="inner-card">
        <div className={styles.toolbar}>
          <Space>
            <Button
              type="primary"
              icon={<UserOutlined />}
              onClick={handleBatchSelect}
              disabled={selectedRowKeys.length === 0}
            >
              批量选择评价人员
            </Button>
            <Button
              icon={<SettingOutlined />}
              onClick={handleWeightSetting}
            >
              设置评分单位权重
            </Button>
          </Space>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={suppliers}
          pagination={false}
          rowKey="key"
        />

        {/* 批量选择评价人员弹窗 */}
        <Modal
          title="批量选择评价人员"
          visible={batchSelectModalVisible}
          onCancel={() => setBatchSelectModalVisible(false)}
          footer={null}
          width={700}
        >
          <EvaluateTaskPersonnelSelector
            onSelect={handleBatchEvaluatorSelect}
            selectedPersonnel={[]}
          />
        </Modal>

        {/* 单个供应商选择评价人员弹窗 */}
        <Modal
          title={`选择评价人员 - ${currentSupplier?.supplierName || ''}`}
          visible={evaluatorModalVisible}
          onCancel={() => setEvaluatorModalVisible(false)}
          footer={null}
          width={700}
        >
          <EvaluateTaskPersonnelSelector
            onSelect={handleEvaluatorSelect}
            selectedPersonnel={currentSupplier?.evaluators || []}
          />
        </Modal>

        {/* 权重设置弹窗 */}
        <Modal
          title="设置评分单位权重"
          visible={weightSettingModalVisible}
          onOk={handleSaveWeights}
          onCancel={() => setWeightSettingModalVisible(false)}
        >
          <Form
            form={form}
            layout="vertical"
          >
            <Form.Item label="权重设置" required>
              <p>请设置各评分单位的权重比例，总和需为100%</p>
              {weightUnits.map(unit => (
                <Form.Item
                  key={unit.id}
                  label={unit.name}
                  name={['weightUnits', unit.id]}
                  rules={[{ required: true, message: '请输入权重值' }]}
                >
                  <InputNumber
                    min={0}
                    max={100}
                    formatter={value => `${value}%`}
                    parser={(value: string | undefined) => {
                      if (!value) return 0;
                      const num = Number(value.replace('%', ''));
                      return num;
                    }}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              ))}
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
});

export default EvaluatorSelectStep;
