import React, { useEffect , useState } from "react";
import { Modal, Button, Select, Input, Table, message, Form } from "antd";
import SupplierSelectModal from "./SupplierSelectModal";
import { add } from "../services";
import type { ColumnsType } from 'antd/es/table';
const { Option } = Select;
interface Supplier {
  id: number; // 作为 rowKey 用于唯一标识
  supplierName: string; // 供应商名称
  unit: string;         // 准入部门
  accessTime: string;   // 准入时间
  categoryName: string; // 准入品类
  lastEval: string;     // 最近一次评价
  lastEvalDate: string; // 评价时间
  supplierId: string;
  categoryId: string;
}

interface CreateBlacklistModalProps {
  visible: boolean;
  onOk: () => void;
  onCancel: () => void;
}

const DEPT_OPTIONS = [
  { value: "DEPT001", label: "部门A" },
  { value: "DEPT002", label: "部门B" },
];

const CreateBlacklistModal: React.FC<CreateBlacklistModalProps> = ({
  visible,
  onOk,
  onCancel,
}) => {
  const [selectVisible, setSelectVisible] = useState(false);
  const [suppliers, setSuppliers] = useState<Supplier[]>([]);
  const [form] = Form.useForm();

  const removeSupplier = (id: number) => {
    setSuppliers(suppliers.filter((s) => s.id !== id));
  };

  const handleSelectOk = (selected: Supplier[]) => {
    setSuppliers(selected);
    setSelectVisible(false);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (suppliers.length === 0) {
        message.error("请至少选择一个供应商");
        return;
      }

      const payload: {
        coscoSupplierexit: {
          exitTheme: string;
          exitReason: string;
          deptId: string;
        },
        supplierIdList: string[],
        coscoSupplierexitSupplierCategoryList: { supplierId: string; categoryId: string;  }[];

      } = {
        coscoSupplierexit: {...values},
        supplierIdList: suppliers.map((item) => item.supplierId),
        coscoSupplierexitSupplierCategoryList: suppliers.map((item) => ({ supplierId: item.supplierId, categoryId: item.categoryId }))
      }
      const res = await add(payload);
      if (res?.success) {
        message.success("提交成功");
        onOk();
      } else {
        message.error("提交失败");
      }
    } catch (err) {
      // 校验失败
    }
  };
  useEffect(() => {
    if (visible) {
      setSuppliers([]);
      form.resetFields();
    }
  }, [visible]);
  const columns: ColumnsType<Supplier> = [
    { title: "供应商名称", dataIndex: "supplierName", align: "center" },
    { title: "准入部门", dataIndex: "unit", align: "center" },
    { title: "准入时间", dataIndex: "accessTime", align: "center", render: () => "2023-04-20 13:00" },
    { title: "准入品类", dataIndex: "categoryName", align: "center" },
    { title: "最近一次评价", dataIndex: "lastEval", align: "center" },
    { title: "评价时间", dataIndex: "lastEvalDate", align: "center" },
    {
      title: "操作",
      dataIndex: "option",
      align: "center",
      render: (_: any, record: Supplier) => (
        <Button type="link" onClick={() => removeSupplier(record.id)}>移除</Button>
      ),
    },
  ];

  return (
    <>
      <Modal
        title="供应商退出"
        visible={visible}
        onCancel={onCancel}
        width={900}
        footer={null}
        destroyOnClose
        bodyStyle={{ padding: "36px 36px 16px" }}
      >
        <Button type="primary" style={{ marginBottom: 18 }} onClick={() => setSelectVisible(true)}>
          选择供应商
        </Button>

        <Table
          columns={columns}
          dataSource={suppliers}
          rowKey="id"
          bordered
          pagination={false}
        />

        <div style={{ marginTop: 24 }}>
          <Form
            form={form}
            labelCol={{ flex: '100px' }}  // label 固定宽度（也可写 'none'）
            wrapperCol={{ flex: 1 }}      // 输入框区域自适应剩余空间
            layout="horizontal"
          >
            <Form.Item
              label="申请主题"
              name="exitTheme"
              rules={[{ required: true, message: '请输入申请主题' }]}
            >
              <Input placeholder="请输入申请主题" />
            </Form.Item>

            <Form.Item
              label="发起部门"
              name="deptId"
              rules={[{ required: true, message: '请选择发起部门' }]}
            >
              <Select placeholder="请选择发起部门">
                {DEPT_OPTIONS.map((opt) => (
                  <Option key={opt.value} value={opt.value}>{opt.label}</Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="退出原因"
              name="exitReason"
              rules={[{ required: true, message: '请输入退出原因' }]}
            >
              <Input.TextArea placeholder="请输入退出原因" rows={4} />
            </Form.Item>
          </Form>
        </div>

        <div style={{ marginTop: 28, textAlign: "center" }}>
          <Button type="primary" style={{ marginRight: 24 }} onClick={handleSubmit}>提交审批</Button>
          <Button onClick={onCancel}>取消</Button>
        </div>
      </Modal>

      <SupplierSelectModal
        visible={selectVisible}
        selectedSuppliers={suppliers}
        onOk={handleSelectOk}
        onCancel={() => setSelectVisible(false)}
      />
    </>
  );
};

export default CreateBlacklistModal;
