import React, { useEffect, useState } from 'react';
import { Modal, Table, Button, Radio, Input, Upload, message, Spin } from 'antd';
import { reviewInfo, uploadFile, update } from '../services';
import type { ColumnsType } from 'antd/es/table';
//主体参数接口
interface ResultModalProps {
  visible: boolean;
  view: boolean;
  record?: { id?: string; [key: string]: any } | null;
  onCancel: () => void;
  onSubmit: () => void;
}
interface RowData {
  key: string;
  itemName: string;
  // 其他如有
}
type CellValue = {
  reviewResult?: '0' | '1';
  remark?: string;
  file?: any;
};

// 只读备注弹窗
const RemarkViewModal: React.FC<{
  visible: boolean;
  onCancel: () => void;
  remark: string;
  file?: any;
}> = ({ visible, onCancel, remark, file }) => (
  <Modal
    visible={visible}
    title="备注信息"
    footer={null}
    onCancel={onCancel}
    destroyOnClose
  >
    <div>
      <div style={{ marginBottom: 12 }}>
        <b>备注：</b>{remark || '无'}
      </div>
      {file && file.fileUrl && (
        <div>
          <b>附件：</b>
          <a href={file.fileUrl} target="_blank" rel="noopener noreferrer">
            {file.fileName}
          </a>
        </div>
      )}
    </div>
  </Modal>
);


//主体
const ResultModal: React.FC<ResultModalProps> = ({
  visible,
  view,
  record,
  onCancel,
  onSubmit
}) => {
  // type: 'teamMembers' | 'groupLeader'
  // 供应商、评审项、单元格数据
  const [suppliers, setSuppliers] = useState<any[]>([]);
  const [items, setItems] = useState<any[]>([]);
  const [userItemMatrix, setUserItemMatrix] = useState<any[][]>([]);
  // userItemId为唯一key
  const [cellData, setCellData] = useState<{ [userItemId: string]: CellValue }>({});
  const [loading, setLoading] = useState(false);
// 查看备注弹窗
  const [remarkModal, setRemarkModal] = useState({ open: false, remark: '', file: undefined as any });
  // 备注弹窗
  const [remarksModalVisible, setRemarksModalVisible] = useState(false);
  const [remarks, setRemarks] = useState('');
  const [fileList, setFileList] = useState<any[]>([]);
  const [currentUserItemId, setCurrentUserItemId] = useState<string | null>(null);

  // 拉取并整理表格数据
  useEffect(() => {
    if (visible && record?.id) {
      setLoading(true);
      reviewInfo({ id: record.id })
        .then((res: any) => {
          const supplierList = res?.data || [];
          setSuppliers(supplierList);

          // 用第一家供应商取所有“非summary”的评审项
          const baseItems = (supplierList[0]?.coscoAccessItemList || []).filter(
            (item: any) => item.itemType !== 'summary'
          );
          setItems(baseItems);

          // 构建userItem二维矩阵：[row][col]=userItem/null
          // userItemMatrix[row][col]为对应格的userItem
          const matrix: any[][] = [];
          const newCellData: { [userItemId: string]: CellValue } = {};
          baseItems.forEach((item: any, rowIdx: number) => {
            matrix[rowIdx] = [];
            supplierList.forEach((sup: any, colIdx: number) => {
              const cur = (sup.coscoAccessItemList || []).find((it: any) => it.itemName === item.itemName && it.itemType !== 'summary');
              const userItem =
                cur?.coscoAccessUserItemList?.length > 0
                  ? cur.coscoAccessUserItemList[0]
                  : null;
              matrix[rowIdx][colIdx] = userItem;

              // 初始化cellData
              if (userItem) {
                newCellData[userItem.id] = {
                  reviewResult: userItem.reviewResult,
                  remark: userItem.remark,
                  file: userItem.coscoAccessTtemAttachments
                };
              }
            });
          });
          setUserItemMatrix(matrix);
          setCellData(newCellData);
        })
        .finally(() => setLoading(false));
    } else if (!visible) {
      setSuppliers([]);
      setItems([]);
      setUserItemMatrix([]);
      setCellData({});
    }
  }, [visible, record]);

  // 单选（只用userItemId为唯一key）
  const handleRadioChange = (userItemId: string, value: string) => {
    setCellData(prev => ({
      ...prev,
      [userItemId]: {
        ...prev[userItemId],
        reviewResult: value === '合格' ? '0' : '1'
      }
    }));
  };

  // 打开备注弹窗
  const openRemarksModal = (userItemId: string) => {
    setCurrentUserItemId(userItemId);
    const cell = cellData[userItemId] || {};
    setRemarks(cell.remark || '');
    setFileList(
      cell.file
        ? [
            {
              uid: '-1',
              name: cell.file.fileName,
              status: 'done',
              url: cell.file.fileUrl,
              response: cell.file
            }
          ]
        : []
    );
    setRemarksModalVisible(true);
  };

  // 上传附件
  const uploadProps = {
    fileList,
    maxCount: 1,
    onRemove: () => setFileList([]),
    customRequest: async (options: any) => {
      const res = await uploadFile(options.file);
      setFileList([
        {
          uid: options.file.uid,
          name: res.fileName,
          status: 'done',
          url: res.fileUrl,
          response: { ...res, fileUrl: res.url }
        }
      ]);
      message.success('文件上传成功');
      options.onSuccess && options.onSuccess(res, options.file);
    }
  };

  // 备注提交
  const handleSubmitRemarks = () => {
    if (!currentUserItemId) return;
    setCellData(prev => ({
      ...prev,
      [currentUserItemId]: {
        ...prev[currentUserItemId],
        remark: remarks,
        file: fileList[0]?.response || undefined
      }
    }));
    setRemarksModalVisible(false);
  };

  // 提交数据
  const handleSubmit = () => {
    // 遍历userItemMatrix拼装参数
    let result: any[] = [];
    userItemMatrix.forEach(row => {
      row.forEach(userItem => {
        if (userItem && cellData[userItem.id]?.reviewResult !== undefined) {
          result.push({
            id: userItem.id,
            reviewResult: cellData[userItem.id]?.reviewResult,
            remark: cellData[userItem.id]?.remark || '',
            coscoAccessTtemAttachments: cellData[userItem.id]?.file
            ? {
                ...cellData[userItem.id]?.file,
                accessWorkId: userItem.accessWorkId // 补充
              }
            : undefined
          });
        }
      });
    });
    let accessWorkId = ''
    if(record?.id) {
      accessWorkId = record?.id
    }
    // 提交审核
    update( {coscoAccessUserItemList: result, accessWorkId  }).then((res) => {
      if(res.code == 200) {
        message.success('提交成功');
        onSubmit()
      }
    })
  };

  // 组装表头
  const columns: ColumnsType<RowData> = [
    {
      title: '评审项',
      dataIndex: 'itemName',
      key: 'itemName',
      width: 200,
      fixed: 'left'
    },
    ...suppliers.map((sup, colIdx) => ({
      title: sup.supplierName,
      dataIndex: sup.supplierId,
      key: sup.supplierId,
      width: 300,
      render: (_: any, row: any, rowIdx: number) => {
        const userItem = userItemMatrix[rowIdx]?.[colIdx];
        if (!userItem) return null; // 无userItem不渲染
        const v = cellData[userItem.id] || {};
        return (
          <>

            {view && (
              <>
                <span style={{color: v.reviewResult  === '0'? '#52c41a': '#f5222d' }}> {v.reviewResult  === '0'? '合格': '不合格'}</span>
                <Button type="link" size="small" onClick={() =>
                   setRemarkModal({ open: true, remark: v.remark || '', file: v.file })
                 }>查看备注</Button>
                </>
            )}
          
          
            { !view && (
              <div>
                <Radio.Group
                  value={
                    v.reviewResult === '0'
                      ? '合格'
                      : v.reviewResult === '1'
                      ? '不合格'
                      : undefined
                  }
                  onChange={e => handleRadioChange(userItem.id, e.target.value)}
                >
                  <Radio value="合格">合格</Radio>
                  <Radio value="不合格">不合格</Radio>
                </Radio.Group>
                <Button type="link" onClick={() => openRemarksModal(userItem.id)}>
                  备注
                </Button>
                {v.remark && (
                  <span style={{ color: '#aaa', fontSize: 12 }}>已备注</span>
                )}
                {v.file && (
                  <span style={{ color: '#52c41a', fontSize: 12, marginLeft: 8 }}>
                    已上传
                  </span>
                )}
              </div>
            )}
          
          </>
        );
      }
    }))
  ];

  // 表格数据
  const tableData = items.map((item: any) => ({
    key: item.id,
    itemName: item.itemName
  }));

  return (
    <>
    <Modal
      title="评审结果"
      visible={visible}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          {view ? '关闭' : '取消'}
        </Button>,
        !view && (
          <Button key="submit" type="primary" onClick={handleSubmit}>
            提交评审结果
          </Button>
        )
      ]}
      width={1000}
      bodyStyle={{ maxHeight: '60vh', overflowY: 'auto' }}
      centered
      destroyOnClose
    >
      <Spin spinning={loading}>
        <Table
          dataSource={tableData}
          columns={columns}
          pagination={false}
          bordered
          scroll={{ x: 300 * suppliers.length + 200 }}
        />
      </Spin>
      <Modal
        title="备注/上传附件"
        visible={remarksModalVisible}
        onCancel={() => setRemarksModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setRemarksModalVisible(false)}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleSubmitRemarks}>
            提交
          </Button>
        ]}
        destroyOnClose
      >
        <Input.TextArea
          rows={4}
          placeholder="请输入备注"
          value={remarks}
          onChange={e => setRemarks(e.target.value)}
        />
        <Upload {...uploadProps}>
          <Button style={{ marginTop: 12 }}>点击上传</Button>
        </Upload>
      </Modal>
    </Modal>
    <RemarkViewModal
      visible={remarkModal.open}
      onCancel={() => setRemarkModal({ open: false, remark: '', file: undefined })}
      remark={remarkModal.remark}
      file={remarkModal.file}
    />
  </>
  );
};

export default ResultModal;
