import React, { useEffect, useState } from 'react';
import { Button, Checkbox, Descriptions, message, Modal, Spin } from 'antd';
import DescriptionsItem from 'antd/lib/descriptions/Item';
import ProTable from '@ant-design/pro-table';
import { getProId, getProMethod} from '@/utils/session';
import { fetchbidslist, fetchJuryMemInfo, pushRedirectRe } from '@/services/bidev';
import { ProColumns } from '@ant-design/pro-table/es';
import CommitmentModal from './CommitmentModal';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { getDefId } from './service';

interface ExpertCommitmentProps {
  //展开收起
  modalVisible: boolean;
  //退出
  onCancel: () => void;
  //当前行的数据传入
  recordData?: any;
  //刷新方法
  onRefresh: () => void;
}

const ExpertCommitment: React.FC<ExpertCommitmentProps> = (props) => {
  const { modalVisible, onCancel, recordData,onRefresh } = props;
  //获取项目id
  const proId = recordData?.tpId;
  //获取roomId
  const roomId = recordData?.id;
  //获取采购方式
  const proMethod: any = getProMethod();
  //loading
  const [loading, setLoading] = useState<boolean>(false);
  //专家信息存储
  const [JuryInfo, setJuryInfo] = useState<any>();
  //供应商列表存储
  const [supplierList, setSupplierList] = useState<any>();
  //页面投标人字体
  const [roleName, setRoleName] = useState<any>('供应商');
  //页面评审 评标 谈判
  const [sectionType, setSectionType] = useState<any>('评审');
  //专家承诺书勾选
  const [checked, setChecked] = useState<boolean>(false);
  //专家承诺书显示弹窗
  const [commitmentVisible, setCommitmentVisible] = useState<boolean>(false);

  const { confirm } = Modal;

  const bidscolumns: ProColumns<any>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      width: '10%',
      align: 'center',
      render: (text: any, record: any, index: any) => {
        return index + 1;
      },
    },
    { title: `${roleName}名称`, dataIndex: 'companyName', align: 'center', width: '90%' },
  ];
  //checked状态存储
  const onChange = (props: any) => {
    setChecked(props.target.checked);
  };
  //打开专家承诺书
  const modalOpen = () => {
    setCommitmentVisible(true)
  };
  const onOk = async (code: any) => {
    setLoading(true)
    if (code == 1 && checked == false) {
      message.info('请您先阅读专家承诺书');
      setLoading(false)
    } else {
      const params = {
        assessRoomId: roomId,
        attitude: code,
        juryMemberId: JuryInfo?.id,
        sectionId: recordData?.sectionId,
      };
      //提交专家承诺书状态 -勾选确定或申请回避
      await pushRedirectRe(params).then((res) => {
        if (res?.code == 200) {
          if (res.success == true) {
            //勾选确定
            if (code == 1) {
              //获取流程id
              getDefId(getProId()).then(res => {
                if(res?.code == 200) {
                  sessionStorage.setItem('defId', JSON.stringify(res?.data));
                  window.open('/EvaRoom');
                }
              })
            } else if (code == 2) {
              message.success("申请回避成功")
              onRefresh();
            }
            setChecked(false)
            onCancel();
          }
        }
      }).finally(() => {
        setLoading(false)
      });
    }
  };

  useEffect(() => {
    if(modalVisible) {
      //修改显示字段
    if(proMethod == "procurement_mode_1" || proMethod == "procurement_mode_2") {
      setRoleName('投标人')
      setSectionType("评标")
    }
    const paramskt = {
      assessRoomId: roomId,
      projectId: proId,
    };
    const params = {
      roomId: roomId,
    };
      //获取供应商信息
      fetchbidslist(paramskt).then(async (res) => {
        if (res?.code == 200) {
          const data = res.data;
          const e = (
            <ProTable
              options={false}
              search={false}
              columns={bidscolumns}
              dataSource={data}
              pagination={false}
              size="small"
            />
          );
          setSupplierList(e);
          //获取专家数据
          await fetchJuryMemInfo(params).then((response) => {
            if (response?.code == 200) {
              const data = response?.data;
              setJuryInfo(data);
            }
          });
        }
      });
    }
  }, [recordData?.id,modalVisible]);
  return (
    <Modal
      destroyOnClose
      visible={modalVisible}
      onCancel={() => {
        setChecked(false)
        onCancel()
      }}
      title="请阅读并同意承诺书协议或申请回避"
      width={"60%"}
      centered
      footer={[
        <Button key="back" onClick={() => {
          setChecked(false)
          onCancel()
        }}>
          取消
        </Button>,
        <Button key="avoid" type="primary" loading={loading} onClick={() => {
          confirm({
            title: '您正在申请专家回避，确认要进行回避吗？',
            icon: <ExclamationCircleOutlined />,
            content: <span style={{color: '#b30000'}}>注意：申请回避后将不能参与此次{sectionType}</span>,
            centered: true,
            okText: "确认",
            onOk() {
              onOk(2)
            },
            onCancel() {},
          });
        }}>
          申请回避
        </Button>,
        <Button key="submit" type="primary" loading={loading} onClick={() => onOk(1)}>
          确定
        </Button>,
      ]}
    >
      <Spin spinning={loading} delay={300}>
      <div className="first-title">专家信息</div>
      <Descriptions column={3}>
        <DescriptionsItem label="姓名" style={{ padding: '1px 1px 0px' }}>
          {JuryInfo?.name}
        </DescriptionsItem>
        <DescriptionsItem label="手机号" style={{ padding: '1px 1px 0px' }}>
          {JuryInfo?.mobile}
        </DescriptionsItem>
        <DescriptionsItem label="身份证号" style={{ padding: '1px 1px 0px' }}>
          {JuryInfo?.certificate}
        </DescriptionsItem>
      </Descriptions>
      <div className="first-title">{roleName}信息</div>
      {supplierList}
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <span style={{ fontSize: '14px', fontWeight: 'bold', marginTop: 16 }}>
          <Checkbox onChange={onChange} checked={checked}></Checkbox>
          <span style={{ marginLeft: '8px' }}>我已阅读并同意了此承诺书</span>
          <span
            style={{ color: '#b30000', fontSize: '14px', cursor: 'pointer' }}
            onClick={modalOpen}
          >
            《承诺书协议》
          </span>
        </span>
      </div>
      </Spin>
      <CommitmentModal modalVisible={commitmentVisible} onCancel={() => setCommitmentVisible(false)}/>
    </Modal>
  );
};

export default ExpertCommitment;
