import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Radio,
  Button,
  message,
  Row,
  Col,
  Divider,
  Space,
  Switch,
  Typography,
  Spin,
} from 'antd';
import { history, useLocation } from 'umi';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import EvaluateTemplateTable from '@/components/EvaluateTemplateTable';
import CategorySelector from '@/components/CategorySelector';
import {
  CategoryLimitationType,
  CategoryLimitationTypeText,
  TemplateStatus,
  TemplateStatusText,
  StarLevel,
  IndicatorAddOption
} from '@/dicts/supplierTemplateDict';
import {
  getTemplateDetail,
  getAllTemplates,
  updateTemplate,
  addTemplate
} from '@/servers/api/supplierEvaluate';
import './supplierTemplateManage.less';

const { Option } = Select;

interface LocationState {
  isEdit?: boolean;
  editData?: SupplierEvaluate.TemplateRecord;
}

const { Title } = Typography;

const SupplierTemplateManageAdd: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [templateData, setTemplateData] = useState<any[]>([]);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [templateDetail, setTemplateDetail] = useState<SupplierEvaluate.TemplateDetail | null>(null);
  const [templateList, setTemplateList] = useState<SupplierEvaluate.TemplateItem[]>([]);

  // 添加控制开关的状态
  const [indicatorStMore, setIndicatorStMore] = useState<string>(IndicatorAddOption.CAN_ADD);
  const [indicatorNdMore, setIndicatorNdMore] = useState<string>(IndicatorAddOption.CAN_ADD);

  // 获取路由传递的数据
  const location = useLocation<LocationState>();

  // 获取所有模板列表
  const fetchTemplateList = async () => {
    try {
      const res = await getAllTemplates();
      if (res.success && res.data) {
        setTemplateList(res.data);
      } else {
        message.error(res.message || '获取模板列表失败');
      }
    } catch (error) {
      console.error('获取模板列表失败:', error);
      message.error('获取模板列表失败');
    }
  };

  // 获取模板详情
  const fetchTemplateDetail = async (templateId: string) => {
    try {
      setLoading(true);
      const res = await getTemplateDetail(templateId);
      if (res.success && res.data) {
        setTemplateDetail(res.data);

        // 设置表单数据
        form.setFieldsValue({
          templateName: res.data.templateName,
          categoryLimitation: res.data.categoryLimitation,
          categoryId: res.data.categoryId,
          status: res.data.status,
          copyTemplateId: res.data.templateType,
          indicatorStMore: res.data.indicatorStMore || IndicatorAddOption.CAN_ADD,
          indicatorNdMore: res.data.indicatorNdMore || IndicatorAddOption.CAN_ADD,
        });

        // 直接设置指标数据，无需转换
        if (res.data.indicatorStList && res.data.indicatorStList.length > 0) {
          setTemplateData(res.data.indicatorStList);
        }
      } else {
        message.error(res.message || '获取模板详情失败');
      }
    } catch (error) {
      console.error('获取模板详情失败:', error);
      message.error('获取模板详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化编辑数据
  useEffect(() => {
    // 获取所有模板列表
    fetchTemplateList();

    // 如果是编辑模式，加载编辑数据
    if (location.state?.isEdit && location.state?.editData) {
      setIsEdit(true);

      // 获取模板详情
      if (location.state.editData.id) {
        fetchTemplateDetail(location.state.editData.id);
      }
    }
  }, []);

  // 处理返回
  const handleBack = () => {
    history.goBack();
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    // 验证指标数据
    if (!templateData || templateData.length === 0) {
      message.error('请添加评价指标数据');
      return;
    }

    // 查找选择的模板，获取其templateType
    const selectedTemplate = templateList.find(template => template.id === values.copyTemplateId);

    // 准备提交数据
    const submitData: any = {
      ...values,
      templateType: selectedTemplate?.templateType || '', // 添加templateType
      indicatorStList: templateData, // 直接使用模板数据，无需转换
      indicatorTypeMore: IndicatorAddOption.CAN_ADD, // 默认可以增加对应指标类型
      status: parseInt(values.status, 10) // 确保status是数字类型
    };

    // 如果是编辑模式，添加ID
    if (isEdit && templateDetail) {
      submitData.id = templateDetail.id;
    }

    setLoading(true);
    try {
      // 调用API接口
      let res;
      if (isEdit) {
        res = await updateTemplate(submitData);
      } else {
        // 使用addTemplate函数，这是原始的API接口
        res = await addTemplate(submitData);
      }

      if (res.success) {
        message.success(isEdit ? '模板更新成功' : '模板保存成功');
        history.goBack();
      } else {
        message.error(res.message || (isEdit ? '模板更新失败' : '模板保存失败'));
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理指标数据变更
  const handleTemplateDataChange = (data: any[]) => {
    setTemplateData(data);
  };

  // 处理开关变化
  const handleSwitchChange = (field: string, value: boolean) => {
    const newValue = value ? IndicatorAddOption.CAN_ADD : IndicatorAddOption.CANNOT_ADD;
    switch (field) {
      case 'indicatorStMore':
        setIndicatorStMore(newValue);
        form.setFieldsValue({ indicatorStMore: newValue });
        break;
      case 'indicatorNdMore':
        setIndicatorNdMore(newValue);
        form.setFieldsValue({ indicatorNdMore: newValue });
        break;
      default:
        break;
    }
  };

  // 处理模板选择
  const handleTemplateSelect = async (templateId: string) => {
    // 如果是新建模式，并且选择了模板，获取模板详情作为基础数据
    if (!isEdit && templateId) {
      try {
        setLoading(true);
        const res = await getTemplateDetail(templateId);
        if (res.success && res.data) {
          // 只复制指标数据，不复制基础信息
          if (res.data.indicatorStList && res.data.indicatorStList.length > 0) {
            // 复制模板数据，但清除ID以创建新记录
            const copiedIndicatorStList = JSON.parse(JSON.stringify(res.data.indicatorStList)).map((stItem: any) => {
              // 删除ID而不是设为undefined
              delete stItem.id;
              stItem.indicatorNdList = stItem.indicatorNdList.map((ndItem: any) => {
                delete ndItem.id;
                return ndItem;
              });
              return stItem;
            });

            setTemplateData(copiedIndicatorStList);
          }
        } else {
          message.error(res.message || '获取模板详情失败');
        }
      } catch (error) {
        console.error('获取模板详情失败:', error);
        message.error('获取模板详情失败');
      } finally {
        setLoading(false);
      }
    }
  };

  return (
    <div className="common-container">
      <Card bordered={false}>
        <div className="page-header">
          <Title level={4} style={{ margin: 0 }}>
            {isEdit ? '编辑评价模板' : '新增评价模板'}
          </Title>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回
          </Button>
        </div>

        <Form
          form={form}
          onFinish={handleSubmit}
          initialValues={{
            categoryLimitation: CategoryLimitationType.UNIVERSAL,
            status: TemplateStatus.DRAFT,
            indicatorStMore: IndicatorAddOption.CAN_ADD,
            indicatorNdMore: IndicatorAddOption.CAN_ADD,
          }}
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 17 }}
        >
          <Spin spinning={loading}>
            <Card title="基础信息" bordered={false} className="inner-card">
              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    label="模板名称"
                    name="templateName"
                    rules={[{ required: true, message: '请输入模板名称' }]}
                  >
                    <Input placeholder="请输入模板名称" maxLength={50} />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="是否限品类"
                    name="categoryLimitation"
                    rules={[{ required: true, message: '请选择是否限品类' }]}
                  >
                    <Radio.Group>
                      <Radio value={CategoryLimitationType.UNIVERSAL}>{CategoryLimitationTypeText[CategoryLimitationType.UNIVERSAL]}</Radio>
                      <Radio value={CategoryLimitationType.LIMITED}>{CategoryLimitationTypeText[CategoryLimitationType.LIMITED]}</Radio>
                    </Radio.Group>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) =>
                      prevValues.categoryLimitation !== currentValues.categoryLimitation
                    }
                  >
                    {({ getFieldValue }) => {
                      const categoryLimitation = getFieldValue('categoryLimitation');
                      return categoryLimitation === CategoryLimitationType.LIMITED ? (
                        <Form.Item
                          label="选择品类"
                          name="categoryId"
                          rules={[{ required: true, message: '请选择品类' }]}
                        >
                          <CategorySelector value={categoryLimitation} />
                        </Form.Item>
                      ) : null;
                    }}
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    label="选择模版"
                    name="copyTemplateId"
                  >
                    <Select
                      placeholder="选择模版"
                      loading={templateList.length === 0}
                      onSelect={handleTemplateSelect}
                    >
                      {templateList.map(template => (
                        template.id ? (
                          <Option key={template.id} value={template.id}>
                            {template.templateName}
                          </Option>
                        ) : null
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="是否启用"
                    name="status"
                    rules={[{ required: true, message: '请选择是否启用' }]}
                  >
                    <Radio.Group>
                      <Radio value={TemplateStatus.DRAFT}>{TemplateStatusText[TemplateStatus.DRAFT]}</Radio>
                      <Radio value={TemplateStatus.ENABLED}>{TemplateStatusText[TemplateStatus.ENABLED]}</Radio>
                      <Radio value={TemplateStatus.DISABLED}>{TemplateStatusText[TemplateStatus.DISABLED]}</Radio>
                    </Radio.Group>
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    label="是否可添加一级指标"
                    name="indicatorStMore"
                    valuePropName="checked"
                    getValueProps={(value) => ({ checked: value === IndicatorAddOption.CAN_ADD })}
                  >
                    <Switch
                      checked={indicatorStMore === IndicatorAddOption.CAN_ADD}
                      onChange={(checked) => handleSwitchChange('indicatorStMore', checked)}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="是否可添加二级指标"
                    name="indicatorNdMore"
                    valuePropName="checked"
                    getValueProps={(value) => ({ checked: value === IndicatorAddOption.CAN_ADD })}
                  >
                    <Switch
                      checked={indicatorNdMore === IndicatorAddOption.CAN_ADD}
                      onChange={(checked) => handleSwitchChange('indicatorNdMore', checked)}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Card>

            <Divider />

            <Card title="指标信息" bordered={false} className="inner-card">
              <EvaluateTemplateTable
                onChange={handleTemplateDataChange}
                value={templateData}
              />
            </Card>
          </Spin>

          <div className="form-actions">
            <Space>
              <Button onClick={handleBack}>取消</Button>
              <Button type="primary" htmlType="submit" loading={loading} icon={<SaveOutlined />}>
                {isEdit ? '更新' : '保存'}
              </Button>
            </Space>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default SupplierTemplateManageAdd;
