import React, { useState, useEffect } from 'react';
import { Button, Table, Space, message, Tooltip, Modal, Tag, Form, Input, InputNumber } from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { TablePaginationConfig } from 'antd';
import { useIntl, FormattedMessage } from 'umi';
import {
  getAllEvaluateRules,
  getEvaluateRuleDetail,
  addEvaluateRule,
  updateEvaluateRule,
  deleteEvaluateRule
} from '@/servers/api/supplierEvaluate';

// 定义规则表单数据类型
interface RuleFormData {
  id?: string;
  beginValue: string;
  endValue: string;
  levelName: string;
  ratingName?: string;
  remark?: string;
}

const SupplierEvaluateRuleManage: React.FC = () => {
  const intl = useIntl();
  const [loading, setLoading] = useState<boolean>(false);
  const [ruleData, setRuleData] = useState<API.EvaluateRuleItem[]>([]);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>(intl.formatMessage({ id: 'supplierEvaluateRuleManage.modal.add' }));
  const [editingRule, setEditingRule] = useState<API.EvaluateRuleItem | null>(null);
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);

  // 获取规则列表
  const fetchRuleList = async () => {
    setLoading(true);
    try {
      const response = await getAllEvaluateRules();
      if (response.success && response.data) {
        setRuleData(response.data);
      } else {
        message.error(response.message || intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.getList.error' }));
      }
    } catch (error) {
      console.error('获取评价规则列表失败:', error);
      message.error(intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.getList.error' }));
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    fetchRuleList();
  }, []);

  // 处理添加规则
  const handleAdd = () => {
    setModalTitle(intl.formatMessage({ id: 'supplierEvaluateRuleManage.modal.add' }));
    setEditingRule(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 处理编辑规则
  const handleEdit = async (record: API.EvaluateRuleItem) => {
    setModalTitle(intl.formatMessage({ id: 'supplierEvaluateRuleManage.modal.edit' }));
    setEditingRule(record);

    try {
      // 获取规则详情
      const response = await getEvaluateRuleDetail(record.id);
      if (response.success && response.data) {
        const ruleDetail = response.data;
        form.setFieldsValue({
          id: ruleDetail.id,
          beginValue: ruleDetail.beginValue,
          endValue: ruleDetail.endValue,
          levelName: ruleDetail.levelName,
          ratingName: ruleDetail.ratingName || '',
          remark: ruleDetail.remark || '',
        });
        setModalVisible(true);
      } else {
        message.error(response.message || intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.getDetail.error' }));
      }
    } catch (error) {
      console.error('获取评价规则详情失败:', error);
      message.error(intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.getDetail.error' }));
    }
  };

  // 处理删除规则
  const handleDelete = (record: API.EvaluateRuleItem) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'supplierEvaluateRuleManage.modal.delete' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage(
        { id: 'supplierEvaluateRuleManage.modal.delete.content' },
        { levelName: record.levelName }
      ),
      okText: intl.formatMessage({ id: 'supplierEvaluateRuleManage.confirm' }),
      cancelText: intl.formatMessage({ id: 'supplierEvaluateRuleManage.cancel' }),
      onOk: async () => {
        try {
          const response = await deleteEvaluateRule(record.id);
          if (response.success) {
            message.success(
              intl.formatMessage(
                { id: 'supplierEvaluateRuleManage.message.delete.success' },
                { levelName: record.levelName }
              )
            );
            fetchRuleList(); // 刷新列表
          } else {
            message.error(response.message || intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.delete.error' }));
          }
        } catch (error) {
          console.error('删除评价规则失败:', error);
          message.error(intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.delete.error' }));
        }
      },
    });
  };

  // 处理表单提交
  const handleFormSubmit = async () => {
    try {
      const values = await form.validateFields();
      setConfirmLoading(true);

      if (editingRule) {
        // 更新规则
        const updateParams: API.EvaluateRuleUpdateRequest = {
          id: editingRule.id,
          beginValue: String(values.beginValue),
          endValue: String(values.endValue),
          levelName: values.levelName,
          remark: values.remark,
        };

        const response = await updateEvaluateRule(updateParams);
        if (response.success) {
          message.success(intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.update.success' }));
          setModalVisible(false);
          fetchRuleList(); // 刷新列表
        } else {
          message.error(response.message || intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.update.error' }));
        }
      } else {
        // 新增规则
        const addParams: API.EvaluateRuleAddRequest = {
          beginValue: String(values.beginValue),
          endValue: String(values.endValue),
          levelName: values.levelName,
          ratingName: values.ratingName || '',
          remark: values.remark,
        };

        const response = await addEvaluateRule(addParams);
        if (response.success) {
          message.success(intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.add.success' }));
          setModalVisible(false);
          fetchRuleList(); // 刷新列表
        } else {
          message.error(response.message || intl.formatMessage({ id: 'supplierEvaluateRuleManage.message.add.error' }));
        }
      }
    } catch (error) {
      console.error('表单验证或提交失败:', error);
    } finally {
      setConfirmLoading(false);
    }
  };

  // 取消表单
  const handleCancel = () => {
    setModalVisible(false);
  };

  const columns = [
    {
      title: <FormattedMessage id="supplierEvaluateRuleManage.column.index" />,
      render: (_: any, __: any, index: number) => index + 1,
      width: 80,
    },
    {
      title: <FormattedMessage id="supplierEvaluateRuleManage.column.levelName" />,
      dataIndex: 'levelName',
      key: 'levelName',
      width: 120,
    },
    {
      title: <FormattedMessage id="supplierEvaluateRuleManage.column.ratingName" />,
      dataIndex: 'ratingName',
      key: 'ratingName',
      width: 150,
      render: (ratingName: string) => ratingName || '-',
    },
    {
      title: <FormattedMessage id="supplierEvaluateRuleManage.column.scoreRange" />,
      key: 'scoreRange',
      width: 150,
      render: (_: any, record: API.EvaluateRuleItem) => `${record.beginValue} - ${record.endValue}`,
    },
    {
      title: <FormattedMessage id="supplierEvaluateRuleManage.column.remark" />,
      dataIndex: 'remark',
      key: 'remark',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (remark: string) => (
        <Tooltip placement="topLeft" title={remark}>
          {remark || '-'}
        </Tooltip>
      ),
    },
    {
      title: <FormattedMessage id="supplierEvaluateRuleManage.column.action" />,
      key: 'action',
      width: 150,
      align: 'center' as const,
      render: (_: unknown, record: API.EvaluateRuleItem) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>
            <FormattedMessage id="supplierEvaluateRuleManage.edit" />
          </Button>
          <Button type="link" onClick={() => handleDelete(record)}>
            <FormattedMessage id="supplierEvaluateRuleManage.delete" />
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="common-container">
      <div className="action-row" style={{ marginBottom: '16px', display: 'flex', justifyContent: 'flex-end' }}>
        <Button type="primary" ghost icon={<PlusOutlined />} onClick={handleAdd}>
          <FormattedMessage id="supplierEvaluateRuleManage.add" />
        </Button>
      </div>

      <div className="content-area">
        <Table
          columns={columns}
          dataSource={ruleData}
          loading={loading}
          rowKey="id"
          scroll={{ x: 1500 }}
        />
      </div>

      {/* 新增/编辑规则模态框 */}
      <Modal
        title={modalTitle}
        visible={modalVisible}
        onCancel={handleCancel}
        maskClosable={false}
        width={600}
        confirmLoading={confirmLoading}
        onOk={handleFormSubmit}
        okText={intl.formatMessage({ id: 'supplierEvaluateRuleManage.submit' })}
        cancelText={intl.formatMessage({ id: 'supplierEvaluateRuleManage.cancel' })}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            beginValue: '',
            endValue: '',
            levelName: '',
            ratingName: '',
            remark: '',
          }}
        >
          {editingRule && (
            <Form.Item name="id" hidden>
              <Input />
            </Form.Item>
          )}
          <Form.Item
            name="levelName"
            label={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.levelName' })}
            rules={[{ required: true, message: intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.levelName.required' }) }]}
          >
            <Input placeholder={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.levelName.placeholder' })} />
          </Form.Item>
          <Form.Item
            name="ratingName"
            label={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.ratingName' })}
            rules={[{ required: !editingRule, message: intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.ratingName.required' }) }]}
          >
            <Input placeholder={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.ratingName.placeholder' })} />
          </Form.Item>
          <Form.Item
            name="beginValue"
            label={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.beginValue' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.beginValue.required' }) },
              {
                pattern: /^[1-9]\d*$/,
                message: intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.beginValue.integer' })
              }
            ]}
          >
            <InputNumber min={0} precision={0} style={{ width: '100%' }} placeholder={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.beginValue.placeholder' })} />
          </Form.Item>
          <Form.Item
            name="endValue"
            label={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.endValue' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.endValue.required' }) },
              {
                pattern: /^[1-9]\d*$/,
                message: intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.endValue.integer' })
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || !getFieldValue('beginValue')) {
                    return Promise.resolve();
                  }
                  if (parseInt(value) <= parseInt(getFieldValue('beginValue'))) {
                    return Promise.reject(new Error(intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.endValue.greater' })));
                  }
                  return Promise.resolve();
                },
              }),
            ]}
          >
            <InputNumber min={0} precision={0} style={{ width: '100%' }} placeholder={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.endValue.placeholder' })} />
          </Form.Item>
          <Form.Item
            name="remark"
            label={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.remark' })}
          >
            <Input.TextArea rows={4} placeholder={intl.formatMessage({ id: 'supplierEvaluateRuleManage.form.remark.placeholder' })} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SupplierEvaluateRuleManage;
