import React, { useState, useEffect, useRef } from 'react';
import { Button, Table, Tabs, Space, Progress, Radio, Modal, Menu, Checkbox, Pagination, Input, message, Upload, Spin, Form, Collapse } from 'antd';
import { getTabList, getProgress, getScoreDetail, getRegister, submitDetail, updateJudgesStatus, getMemberInfo, getEval, getUnlock, isStatus, checkShowData, getFile, submitSummary, submQualified, beforeRiskControl } from './service';
import '@/assets/ld_style.less'
import BidPreliminarySpeed from './components/BidPreliminarySpeed';
import BidPreliminarySummary from './components/BidPreliminarySummary';
import FirstTrialTable from '../BidPreliminaryManager/module/FirstTrialTable';
import { getExperts } from '../BidPreliminaryManager/service';
import { getProMethod, getRoomId, getSessionUserData, getUserToken } from '@/utils/session';
import FileDown from '@/utils/Download';
import { getURLInformation, isEmpty } from '@/utils/CommonUtils';
import ExtendUpload from '@/utils/ExtendUpload';
import { btnAuthority } from '@/utils/authority';
import MACAddressPrompt from '../../BidControl/BidControlManager/components/MACAddressPrompt';
import RiskPreventionSoft from '@/utils/RiskPreventionSoft';

const { TabPane } = Tabs;
const { SubMenu } = Menu;
const { TextArea } = Input;
const { Panel } = Collapse;
const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 16 },
};
const validateMessages = {
  required: '请填写${label}',
};

let assessRoomId: any, reviewTurnId: any, reviewType: any, bidEvalId: any, reviewStatus: any
let bidEvalDetailDTOList: any = [];
let totalQualified: any = [];

let disabled: any = false;
let endProgress: any = false;

const Index: React.FC<{}> = () => {
  const [tabList, setTabList] = useState<any>([]); // tab
  const [process, setProcess] = useState<any>(); // 我的进度
  const [typeId, setTypeId] = useState<any>(); // tabId
  const [typeCategory, setTypeCategory] = useState<any>(); // tab类型
  const [totalSupplierColumns, setTotalSupplierColumns] = useState<any>([]); // 总供应商列头
  const [supplierColumns, setSupplierColumns] = useState<any>([]); // 当前显示供应商列头
  const [current, setCurrent] = useState<number>(1); // 当前页码
  const [total, setTotal] = useState<number>(1); // 共多少数据
  const [remarkVisible, setRemarkVisible] = useState<boolean>(false); // 备注
  const [dataSource, setDataSource] = useState<any>([]); // 初审项配置 
  const [detailVisible, setDetailVisible] = useState<boolean>(false); // 初审详情
  const [lockVisible, setLockVisible] = useState<boolean>(false); // 解锁
  const [plainList, setPlainList] = useState([]); // 解锁专家
  const [remarksVal, setRemarksVal] = useState<any>(); // 备注
  const [subId, setSubId] = useState<any>(); // 提交id
  const [spinVisible, setSpinVisible] = useState<boolean>(false); // 加载中
  const [remarkForm] = Form.useForm(); // 备注表单
  const [isDisabled, setIsDisabled] = useState<boolean>(false); // 是否可编辑
  const [unLockArr, setUnLockArr] = useState<any>([]); // 解锁专家数组
  const [dateLength, setDateLength] = useState<any>([]); // tab签长度
  const [isModalVisible, setIsModalVisible] = useState(false); // 全局全部合格弹窗
  const [submitLoading, setSubmitLoading] = useState<boolean>(false); // 提交汇总loading
  //风控弹窗 2022.8.17 zhoujianlong
  const [riskVisible, setRiskVisible] = useState<boolean>(false);
  //风控数据 2022.8.17 zhoujianlong
  const [riskData, setRiskData] = useState<any[]>([]);

  //获取数据的参数
  const [findScoreRecordData, setFindScoreRecordData] = useState<any>();
  //所有人员初审表数据
  const [allFirstTrialTableData, setAllFirstTrialTableData] = useState<any>(null);
  //用于显示初审表数据
  const [preliminaryDetails, setPreliminaryDetails] = useState<any>();
  // //当前页面评审汇总显隐
  // const [submitStatus, setSubmitStatus] = useState<boolean>(false);
  // 汇总表进度和汇总表显示
  const [tableDisplay, setTableDisplay] = useState<boolean>(false);
  //上传文件id存储
  const [uploadId, setUploadId] = useState<any>();
  //单选数值存储
  const [radioValue, setRadioValue] = useState<number>();
  //比选一阶段二次项目自定义评审流程单选数值存储
  const [processValue, setProcessValue] = useState<number>();
  //合格供应商数量
  const [qualifyNumber, setQualifyNumber] = useState<number>(3);
  //是否公开比选一阶段二次项目
  const [isBxOneSecond, setIsBxOneSecond] = useState<boolean>(false);
  //二次项目是否可编辑两个单选
  const [isNodeEnd, setIsNodeEnd] = useState<boolean>(false);
  //动态获取表单
  const [form] = Form.useForm();
  //当前页 初审详情
  const [theCurrent, setTheCurrent] = useState<string>('1');
  const [count, setCount] = useState<any>(0);
  const modalHeight = (innerHeight * 96) / 100;
  const ref = useRef<Array<{}>>();
  const [isEndProgress, setIsEndProgress] = useState<boolean>(false); // 是否可编辑
  const proMethod = getProMethod();//获取采购方式
  let showNameT: any = { tbr: '', pb: '', tb: '' }//投标人供应商
  if (proMethod === 'procurement_mode_1' || proMethod === 'procurement_mode_2') {//招标
    showNameT = { tbr: '投标人', pb: '评标', tb: '投标' };
  } else {
    showNameT = { tbr: '供应商', pb: '评审', tb: '应答' }

  }

  const columns: any[] = [  // 列表数据
    {
      title: '类别名称',
      dataIndex: 'categoryName',
      render: (_: any, record: any, index: number) => {
        return {
          children: _,
          props: {
            rowSpan: record.rowSpan,
          }
        }
      }
    },
    {
      title: '初审项&审查标准',
      dataIndex: 'scoreItem',
      render: (_: any, record: any) => {
        return (
          <>
            <div>{record.scoreItem}</div>
            <div>{record.rvwStandard}</div>
          </>
        )
      }
    },
    {
      title: '操作',
      render: (_: any, record: any) => {
        return (
          <Button type="link" disabled={disabled || endProgress} onClick={() => getQualified(record)} danger>全部合格</Button>
        )
      }
    },
  ];

  const createNewArr = (data: any[], fieldName: string) => {
    return data.reduce((result: any[], item: any) => {
      //首先将name字段作为新数组result取出
      if (result.indexOf(item[fieldName]) < 0) {
        result.push(item[fieldName]);
      }
      return result
    }, []).reduce((result: any[], name: any) => {
      //将name相同的数据作为新数组取出，并在其内部添加新字段**rowSpan**
      const children = data.filter(item => item[fieldName] === name);
      result = result.concat(
        children.map((item: any, index: number) => ({
          ...item,
          rowSpan: index === 0 ? children.length : 0,//将第一行数据添加rowSpan字段
        }))
      )
      return result;
    }, [])
  }

  const saveSorce = () => { // 保存
    if (bidEvalDetailDTOList.length > 0) {
      setSpinVisible(true)
      let date = {
        id: subId,
        bidEvalId: bidEvalId,
        // categoryId: typeId,
        category: typeCategory,
        judgesStatus: '1',
        bidEvalDetailDTOList: bidEvalDetailDTOList,
        assessRoomId: assessRoomId,
      }
      submitDetail({ ...date }).then((res) => {
        if (res.code == 200) {
          bidEvalDetailDTOList = []
          ratingData(typeCategory)
          myProcess(typeCategory)
        } else {
          myProcess(typeCategory)
          ratingData(typeCategory)
          bidEvalDetailDTOList = []
          // setCount(count + 1)
        }
      }).finally(() => {
        setSpinVisible(false)
        bidEvalDetailDTOList = []
      })
    }
  }

  const tabSaveSorce = () => { // tab保存
    if (bidEvalDetailDTOList.length > 0) {
      setSpinVisible(true)
      let date = {
        id: subId,
        bidEvalId: bidEvalId,
        // categoryId: typeId,
        category: typeCategory,
        judgesStatus: '1',
        bidEvalDetailDTOList: bidEvalDetailDTOList,
        assessRoomId: assessRoomId,
      }
      submitDetail({ ...date }).then((res) => {
        if (res.code == 200) {
          bidEvalDetailDTOList = []
        } else {
          bidEvalDetailDTOList = []
        }
      }).finally(() => {
        setSpinVisible(false)
        bidEvalDetailDTOList = []
      })
    }
  }

  const submitApi = () => { // 提交接口
    setSpinVisible(true)
    let date = {
      // categoryId: typeId,
      category: typeCategory,
      judgesStatus: '2',
      bidEvalId: bidEvalId,
    }
    updateJudgesStatus({ ...date }).then((res) => {
      if (res.code == 200) {
        message.success('提交成功！');
        setSpinVisible(false)
        // ratingData(typeId)
        setIsDisabled(true)
        supplierTab(typeCategory) // 防止提交成功禁用按钮不生效
      }
    }).finally(() => {
      setSpinVisible(false)
    })
  }

  const submit = () => { // 提交
    if (bidEvalDetailDTOList.length > 0) {
      let date = {
        id: subId,
        bidEvalId: bidEvalId,
        // categoryId: typeId,
        category: typeCategory,
        judgesStatus: '1',
        bidEvalDetailDTOList: bidEvalDetailDTOList,
        assessRoomId: assessRoomId,
      }
      submitDetail({ ...date }).then((res) => {
        if (res.code == 200) {
          setSpinVisible(false)
          bidEvalDetailDTOList = []

          let date = {
            bidEvalId: bidEvalId,
            reviewTurnId: reviewTurnId,
            category: typeCategory,
            assessRoomId: assessRoomId,
            reviewType: '1'
          }
          getProgress({ ...date }).then((res) => {
            if (res.code == 200) {
              if (res.data == 100) {
                setProcess(res.data)
                submitApi()
              } else {
                message.error("您有未完成的打分项，请完成后再提交！")
              }
            }
          })

        }
      }).finally(() => {
        setSpinVisible(false)
        bidEvalDetailDTOList = []
      })
    } else {
      let date = {
        bidEvalId: bidEvalId,
        reviewTurnId: reviewTurnId,
        category: typeCategory,
        assessRoomId: assessRoomId,
        reviewType: '1'
      }
      getProgress({ ...date }).then((res) => {
        if (res.code == 200) {
          if (res.data == 100) {
            submitApi()
          } else {
            message.error("您有未完成的打分项，请完成后再提交！")
          }
        }
      })
    }
  }

  const onChange = (e: any, val: any, id: any) => { // 单选合格不合格
    let x = false;
    bidEvalDetailDTOList.map((item: any) => {
      if (val.detailId && item.supplierRegisterId == id && item.detailId == val.detailId) {
        item.resultValue = e.target.value
        x = true
      }
    })
    if (!x) {
      if (val.detailId) {
        bidEvalDetailDTOList.push({ 'categoryId': val.categoryId, 'id': val.id, 'supplierRegisterId': val.supplierRegisterId, 'detailId': val.detailId, 'resultValue': e.target.value, 'remarks': val.remarks });
      } else {
        bidEvalDetailDTOList.push({ 'categoryId': val.categoryId, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'resultValue': e.target.value, 'remarks': '' });
      }
    }
    totalQualified.map((item: any) => {
      if (val.detailId) {
        if (val.detailId == item.id) {
          for (let i = 0; i < supplierId.length; i++) {
            if (id == supplierId[i] && item.scoreMap[supplierId[i]].resultValue != e.target.value) {
              item.scoreMap[supplierId[i]].resultValue = e.target.value
            }
          }
        }
      } else {
        if (val.id == item.id) {
          for (let i = 0; i < supplierId.length; i++) {
            if (id == supplierId[i]) {
              if (item.scoreMap == null) {
                item.scoreMap = []
              }
              item.scoreMap[supplierId[i]] = { 'categoryId': val.categoryId, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'resultValue': e.target.value, 'remarks': '' }
            }
          }
        }
      }
    })
    setDataSource([...totalQualified])
  }

  const openDetail = () => { // 初审详情
    setDetailVisible(true)
    setPreliminaryDetails(theCurrent == '1' ? findScoreRecordData : allFirstTrialTableData);
  }

  const handleClick = (e: any) => { // 初审详情树切换
    setTheCurrent(e.key);
    if (e.key == 1) { // 初审记录表
      setPreliminaryDetails(findScoreRecordData);
    } else if (e.key == 2) { // 专家个人初审表
      setPreliminaryDetails(allFirstTrialTableData);
    }
  }

  /**
   * 获取初审记录表数据
   */
  const getFirstTrialTable = async (findScoreRecordParams: any, supplierData: any) => {
    let data = <FirstTrialTable
      defaultSupplierData={supplierData}
      defaultNumber={3}
      supplierParams={null}
      findScoreRecordParams={{ ...findScoreRecordParams, reviewType: "1" }}
    />;
    let finalData = (
      <div className="right-content">
        {data}
      </div>
    )
    setPreliminaryDetails(finalData);
    setFindScoreRecordData(finalData);
    return data;
  }
  /**
   * 获取所有人员初审记录表数据
   */
  const getAllFirstTrialTable = async (findScoreRecordParams: any, supplierData: any) => {
    //获取专家数据
    getExperts(assessRoomId).then((res: any) => {
      let data = res.data.map((item: any) => {
        return (
          <>
            <Panel className='h45' header={item.name} key={item.id}>
              <FirstTrialTable
                key={item.id}
                findScoreRecordParams={{ ...findScoreRecordParams, reviewType: "1", createBy: item.userId }}
                defaultNumber={3}
                supplierParams={null}
                defaultSupplierData={supplierData}
              />
            </Panel>
          </>
        )
      })
      setAllFirstTrialTableData(
        <>
          <div className="right-content">
            <Collapse>
              {data}
            </Collapse>
          </div>
        </>
      );
    })
  }

  const getTabId = (key: any) => { // tab切换获取当前tab的key
    setCurrent(1)
    if (tabList[key].name == '初审汇总') {
      setCount(count + 1)
      setQualifyNumber(3)
    } else {
      if (bidEvalDetailDTOList.length > 0) {
        tabSaveSorce()
        bidEvalDetailDTOList = []
      }
      if (key < tabList.length - 1) {
        changePagination(1, tabList[key].category, totalSupplierColumns)
        // setTypeId(tabList[key].id)
        setTypeCategory(tabList[key].category)
        myProcess(tabList[key].category)
      }
    }
  }

  const myProcess = (category: any) => { // 我的进度
    let date = {
      bidEvalId: bidEvalId,
      reviewTurnId: reviewTurnId,
      category: category,
      assessRoomId: assessRoomId,
      reviewType: '1'
    }
    getProgress({ ...date }).then((res) => {
      if (res.code == 200) {
        setProcess(res.data)
      }
    })
  }

  const supplierTab = (category: any) => {
    let date = {
      assessRoomId: assessRoomId,
      reviewTurnId: reviewTurnId,
      reviewType: "1"
    }
    getRegister({ ...date }).then((res) => { // 供应商列头
      if (res.code == 200) {
        setTotal(res.data.length)
        setTotalSupplierColumns(res.data)
        changePagination(1, category, res.data)
        getAllFirstTrialTable(date, res.data);
        getFirstTrialTable(date, res.data);
      }
    })
  }

  let supplierId: any = [] // 供应商数组id
  const changePagination = (page: any, category: any, totalSupplierColumns: any) => { // 供应商列头分页
    if (bidEvalDetailDTOList.length > 0) {
      saveSorce() // 保存
    }
    setCurrent(page)
    let currentDate = (page - 1) * 3
    let newColumns = [...columns];
    totalSupplierColumns.slice(currentDate, currentDate + 3).map((item: any) => {
      supplierId.push(item.supplierRegisterId)
      newColumns.push({
        title: (
          <>
            {item.supplierRegisterName}
            {item.macConflictStatus && <MACAddressPrompt type='score' />}
          </>
        ),
        dataIndex: item.supplierRegisterId,
        render: (text: any, record: any) => {
          if (record.scoreMap && record.scoreMap[item.supplierRegisterId]) {
            return (
              <div>
                <Radio.Group
                  disabled={disabled || endProgress}
                  value={Number(record.scoreMap[item.supplierRegisterId].resultValue)}
                  onChange={e => onChange(e, record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)}
                >
                  <Radio value={1}>合格</Radio>
                  <Radio value={2}>不合格</Radio>
                </Radio.Group><br />
                <Button type="link" onClick={() => getRemark(record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)} danger>备注</Button>
                <Button hidden={btnAuthority(['ebtp-expert'])} type="link" danger onClick={() => lookFile(record.id, item.supplierRegisterId)}>查看{showNameT.tb}文件</Button>
              </div>
            )
          } else {
            return (
              <div>
                <Radio.Group
                  disabled={disabled || endProgress}
                  value={0}
                  onChange={e => onChange(e, record, item.supplierRegisterId)}
                >
                  <Radio value={1}>合格</Radio>~
                  <Radio value={2}>不合格</Radio>
                </Radio.Group><br />
                <Button type="link" onClick={() => getRemark(record, item.supplierRegisterId)} danger>备注</Button>
                <Button hidden={btnAuthority(['ebtp-expert'])} type="link" danger onClick={() => lookFile(record.id, item.supplierRegisterId)}>查看{showNameT.tb}文件</Button>
              </div>
            )
          }
        },
      })
    })

    setSupplierColumns([...newColumns])
    ratingData(category)
  }

  const lookFile = (id: any, supplierRegisterId: any) => {
    getFile(id).then((res) => { // 查看是否有应答文件
      if (res.code == 200) {
        if (res.data.length > 0) {
          window.open("/viewOfTenderDocumentsSecond?id=" + id + "&supplierId=" + supplierRegisterId);
        } else {
          message.info(`无关联${showNameT.tb}文件`)
        }
      }
    })
  }

  const ratingData = (category: any) => { // 评分数据
    setSpinVisible(true)
    totalQualified = []
    let query = {
      bidEvalId: bidEvalId,
      reviewTurnId: reviewTurnId,
      reviewType: "1",
      assessRoomId: assessRoomId,
      category: category,
      supplierRegisterIds: supplierId
    }
    getScoreDetail({ ...query }).then((res) => { // 评分数据
      if (res.code == 200) {
        // setTypeId(res.data.categoryId) // 设置类别id
        setTypeCategory(res.data.category) // 设置类别
        setSpinVisible(false)
        if (res.data.judgesStatus != '1') {
          disabled = true
          setIsDisabled(true)
        } else {
          disabled = false
          setIsDisabled(false)
        }
        setSubId(res.data.id)
        setDataSource(createNewArr(res.data.detailList, 'categoryName'))
        totalQualified = createNewArr(res.data.detailList, 'categoryName')
      } else {
        setSpinVisible(false)
      }
    }).finally(() => {
      setSpinVisible(false)
    })
  }

  const getRemark = (val: any, id: any) => { // 备注
    if (val.remarks) {
      remarkForm.setFieldsValue({ remarks: val.remarks })
    } else {
      remarkForm.setFieldsValue({ remarks: '' })
    }
    if (val.detailId) {
      setRemarksVal({ 'categoryId': val.categoryId, 'id': val.id, 'supplierRegisterId': id, 'detailId': val.detailId, 'resultValue': val.resultValue, 'remarks': val.remarks })
    } else {
      setRemarksVal({ 'categoryId': val.categoryId, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'resultValue': '', 'remarks': '' })
    }
    setRemarkVisible(true)
  }

  const closeRemarks = () => { // 关闭备注
    if (!isDisabled) {
      let x = false;
      bidEvalDetailDTOList.map((item: any) => {
        if (item.supplierRegisterId == remarksVal.supplierRegisterId && item.detailId == remarksVal.detailId) {
          item.remarks = remarkForm.getFieldsValue().remarks
          dataSource.map((item: any) => {
            if (remarksVal.detailId == item.id) {
              item.scoreMap[remarksVal.supplierRegisterId].remarks = remarkForm.getFieldsValue().remarks
            }
          })
          x = true
        }
      })
      if (!x) {
        dataSource.map((item: any) => {
          if (remarksVal.detailId) {
            if (remarksVal.detailId == item.id && item.scoreMap && item.scoreMap[remarksVal.supplierRegisterId] && item.scoreMap[remarksVal.supplierRegisterId].remarks != remarkForm.getFieldsValue().remarks) {
              bidEvalDetailDTOList.push({ 'categoryId': remarksVal.categoryId, 'id': remarksVal.id, 'supplierRegisterId': remarksVal.supplierRegisterId, 'detailId': remarksVal.detailId, 'resultValue': remarksVal.resultValue, 'remarks': remarkForm.getFieldsValue().remarks });
              item.scoreMap[remarksVal.supplierRegisterId].remarks = remarkForm.getFieldsValue().remarks
            } else if (remarksVal.detailId == item.id && remarksVal.id == '') {
              bidEvalDetailDTOList.push({ 'categoryId': remarksVal.categoryId, 'id': remarksVal.id, 'supplierRegisterId': remarksVal.supplierRegisterId, 'detailId': remarksVal.detailId, 'resultValue': remarksVal.resultValue, 'remarks': remarkForm.getFieldsValue().remarks });
              if (item.scoreMap == null) {
                item.scoreMap = []
              }
              item.scoreMap[remarksVal.supplierRegisterId] = { 'categoryId': remarksVal.categoryId, 'id': '', 'supplierRegisterId': remarksVal.supplierRegisterId, 'detailId': remarksVal.detailId, 'resultValue': '', 'remarks': remarkForm.getFieldsValue().remarks }
            } else if (remarksVal.detailId == item.id) {
              bidEvalDetailDTOList.push({ 'categoryId': remarksVal.categoryId, 'id': remarksVal.id, 'supplierRegisterId': remarksVal.supplierRegisterId, 'detailId': remarksVal.detailId, 'resultValue': remarksVal.resultValue, 'remarks': remarkForm.getFieldsValue().remarks });
              item.scoreMap[remarksVal.supplierRegisterId].remarks = remarkForm.getFieldsValue().remarks
            }
          } else {
            if (remarkForm.getFieldsValue().remarks != '') {
              bidEvalDetailDTOList.push({ 'categoryId': remarksVal.categoryId, 'id': '', 'supplierRegisterId': remarksVal.supplierRegisterId, 'detailId': remarksVal.detailId, 'resultValue': remarksVal.resultValue, 'remarks': remarkForm.getFieldsValue().remarks });
              item.scoreMap[remarksVal.supplierRegisterId] = { 'remarks': remarkForm.getFieldsValue().remarks }
            }
          }
        })
        setDataSource([...dataSource])
      }
    }
    setRemarkVisible(false)
  }

  const getQualified = (val: any) => { // 全部合格
    let x = false;
    totalQualified.map((item: any) => {
      if (val.id == item.id) {
        for (let i = 0; i < supplierId.length; i++) {
          if (item.scoreMap && item.scoreMap[supplierId[i]]) {
            item.scoreMap[supplierId[i]].resultValue = '1'

            bidEvalDetailDTOList.map((value: any) => {
              if (value.supplierRegisterId == item.scoreMap[supplierId[i]].supplierRegisterId && value.detailId == item.scoreMap[supplierId[i]].detailId) {
                value.resultValue = '1'
                x = true
              }
            })
            if (!x) {
              bidEvalDetailDTOList.push({ 'categoryId': item.scoreMap[supplierId[i]].categoryId, 'id': item.scoreMap[supplierId[i]].id, 'supplierRegisterId': item.scoreMap[supplierId[i]].supplierRegisterId, 'detailId': item.scoreMap[supplierId[i]].detailId, 'resultValue': '1', 'remarks': item.scoreMap[supplierId[i]].remarks });
            }
          } else {
            if (item.scoreMap == null) {
              item.scoreMap = []
            }
            item.scoreMap[supplierId[i]] = { 'categoryId': val.categoryId, 'id': '', 'supplierRegisterId': supplierId[i], 'detailId': val.id, 'resultValue': '1', 'remarks': '' }
            bidEvalDetailDTOList.push({ 'categoryId': val.categoryId, 'id': '', 'supplierRegisterId': supplierId[i], 'detailId': val.id, 'resultValue': '1', 'remarks': '' });
          }
        }
      }
    })
    setDataSource([...totalQualified])
  }

  const makeQualified = () => { // 确认全部合格
    bidEvalDetailDTOList = []
    setSpinVisible(true)
    let date = {
      id: subId,
      bidEvalId: bidEvalId,
      reviewTurnId: reviewTurnId,
      category: typeCategory,
      assessRoomId: assessRoomId,
      reviewType: '1',
    }
    submQualified(date).then((res) => {
      if (res.code == 200) {
        ratingData(typeCategory)
        myProcess(typeCategory)
        message.success('操作成功！');
        setIsModalVisible(false)
      } else {
        ratingData(typeCategory)
        myProcess(typeCategory)
        setIsModalVisible(false)
      }
    }).finally(() => {
      setSpinVisible(false)
      setIsModalVisible(false)
    })
  }

  const getLock = () => { // 初审解锁
    setLockVisible(true)
    getMemberInfo(assessRoomId).then((res) => {
      let userArr: any = []
      if (res.code == 200) {
        res.data.map((item: any) => {
          userArr.push({ label: item.name, value: item.userId })
        })
      }
      setPlainList(userArr)
    })
  }

  const changeLock = (val: any) => { // 解锁专家
    setUnLockArr(val)
  }

  const handleOk = () => { // 确认解锁
    if (unLockArr != '') {
      let date = {
        bidEvalId: bidEvalId,
        judgesStatus: '1',
        userIds: unLockArr,
        assessRoomId: assessRoomId
      }
      getUnlock({ ...date }).then((res) => {
        if (res.code == 200) {
          setLockVisible(false)
          message.success('专家解锁成功！')
          setCount(count + 1)
        }
      })
    } else {
      message.error('请选择需要解锁的专家')
    }
  }

  const gettabList = () => { // tab
    let date = {
      assessRoomId: assessRoomId,
      reviewTurnId: reviewTurnId,
      rvwType: reviewType
    }
    getTabList({ ...date }).then((res) => {
      if (res.code == 200) {
        res.data.push({ 'name': '初审汇总' })
        setDateLength(res.data.length)
        setTabList(res.data) // tab数据
        supplierTab(res.data[0].category) // 供应商列头
        if (res.data.length > 1) {
          myProcess(res.data[0].category) // 进度
          // setTypeId(res.data[0].id) // 设置类别id
          setTypeCategory(res.data[0].category) // 设置类别
        }
      }
    })
  }

  const finalSubmit = async () => {
    if (qualifyNumber < 3) {
      form.submit();
    } else {
      const remarkList = getRemarkList(ref.current)
      if (remarkList) {
        let submitData = {
          reviewStatus: '2',
          reviewTurnId: getURLInformation("turnId"),
          reviewType: '1',
          remarkList: remarkList,
        }
        await toSubmit(submitData)
      }
    }
  }

  const toSubmit = async (params: any) => {
    setSubmitLoading(true)
    setSpinVisible(true)
    await submitSummary(params).then(res => { //提交汇总方法
      if (res?.code == 200) {
        message.success('提交成功');
        setCount(count + 1)
      }
    }).finally(() => {
      setSubmitLoading(false)
      setSpinVisible(false)
    })
  }
  //处理汇总表返回的数据
  const getRemarkList = (data: any) => {
    const List: any[] = []
    for (const item of totalSupplierColumns) {
      const obj = data[data.length - 1][item?.supplierRegisterId]
      if (obj.judgesResult == false) {//判断为不合格情况
        if (isEmpty(obj.remarks)) {
          message.info(`请填写【${item?.supplierRegisterName}】的不合格原因说明`)
          return false;
        }
      }
      if (obj.macConflictStatus && obj.judgesResult) {//mac地址重复供应商选为合格
        message.info(`${item?.supplierRegisterName}与其他供应商MAC地址重复，不可选为初审合格`);
        return false;
      }
      List.push({
        supplierRegisterId: item?.supplierRegisterId,
        qualifiedStatus: obj?.judgesResult ? '1' : '2',
        remarks: obj?.judgesResult ? null : obj?.remarks,
        originalResult: obj?.originalResult ? '1' : '2',
        modifyResultStatus: obj?.judgesResult != obj?.originalResult,
      })
    }
    return List
  }

  let JwtToken = getSessionUserData().userId
  const props = { // 初审摘录表导入
    name: 'file',
    data: {
      // reviewTurnId: getURLInformation("turnId"),
      assessRoomId: getRoomId(),
      reviewType: '1'
    },
    showUploadList: false,
    accept: 'application/vnd.ms-application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    action: '/api/biz-service-ebtp-rsms/v1/abstract/upload',
    headers: {
      Authorization: getUserToken(),
      JwtToken: JwtToken
    },
    onChange(info: any) {
      setSpinVisible(true)
      bidEvalDetailDTOList = []
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        if (info.file.response.code == 200) {
          message.success('初审摘录表导入成功');
          myProcess(typeCategory)
          changePagination(1, typeCategory, totalSupplierColumns)
          setSpinVisible(false)
        } else {
          message.error(info.file.response.message);
          myProcess(typeCategory)
          changePagination(1, typeCategory, totalSupplierColumns)
          setSpinVisible(false)
        }
      } else if (info.file.status === 'error') {
        message.error('初审摘录表导入失败');
        setSpinVisible(false)
      }
    },
  };
  //radio单选onChange方法
  const radioOnChange = (e: any) => {
    setRadioValue(e.target.value);
  };
  //流程单选onChange方法
  const processOnChange = (e: any) => {
    setProcessValue(e.target.value);
  };
  //表单提交
  const onFinish = async (values: any) => {
    let data = {
      continueStatus: radioValue
    }
    if (radioValue == 1) {
      data["remarks"] = values.remarks
      data["fileId"] = values.fileId
      if (isBxOneSecond && qualifyNumber == 1) {//比选一阶段二次项目 只有一家供应商合格
        data["operationType"] = 1
        data["customizeFlowStatus"] = processValue
      } else {
        data["operationType"] = 0
      }
    } else if (radioValue == 0) {
      if (isBxOneSecond) {//比选一阶段二次项目
        data["operationType"] = 1
        data["customizeFlowStatus"] = 0
      }
    }
    const remarkList = getRemarkList(ref.current)
    if (remarkList) {
      let submitData = {
        reviewStatus: '2',
        reviewTurnId: getURLInformation("turnId"),
        reviewType: '1',
        earlyWarn: { ...data },
        remarkList: remarkList,
      }
      await toSubmit(submitData)
    }
  };

  useEffect(() => {
    bidEvalDetailDTOList = []
    let date = {
      reviewTurnId: getURLInformation("turnId"),
      reviewType: '1',
    }
    getEval({ ...date }).then(async (res) => {
      if (res?.code == 200) {
        assessRoomId = res.data.assessRoomId
        reviewTurnId = res.data.reviewTurnId
        reviewType = res.data.reviewType
        bidEvalId = res.data.id
        reviewStatus = res.data.reviewStatus
        if (res.data.reviewStatus != 1) {
          endProgress = true
          setIsEndProgress(true)
        } else {
          endProgress = false
          setIsEndProgress(false)
        }
        gettabList()
        let statusProps = {
          assessRoomId: res.data.assessRoomId,
          reviewType: 1,
          reviewTurnId: getURLInformation("turnId"),
          createBy: 101
        }
        //初始化汇总表显示状态
        await isStatus(statusProps).then(async res => {
          if (res?.code == 200) {
            setTableDisplay(res.data)
            //初始化三家供应商判断数据
            await checkShowData(assessRoomId, getURLInformation('nodeId')).then(response => {
              if (response?.code == 200) {
                setUploadId(response?.data?.fileId)
                setRadioValue(response?.data?.continueStatus == undefined ? 1 : response?.data?.continueStatus)
                setProcessValue(response?.data?.customizeFlowStatus == undefined ? 1 : response?.data?.customizeFlowStatus);
                setIsBxOneSecond(response?.data?.bxOneSecondProjectStatus);
                setIsNodeEnd(response?.data?.nodeEndStatus);
                form.setFieldsValue({
                  remarks: response.data?.remarks
                })
              }
            })
          }
        })
      }
    })
  }, [count]);

  /**
   * 风控中心校验
   */
  const verificationRiskControl = () => {
    const remarkList = getRemarkList(ref.current);
    if (remarkList) {
      let submitData = {
        reviewStatus: '2',
        reviewTurnId: getURLInformation("turnId"),
        reviewType: '1',
        remarkList: remarkList,
      }
      beforeRiskControl(submitData).then(res => {
        if (res?.code == 200) {
          if (res?.data.length > 0) {
            setRiskData(res?.data);
            setRiskVisible(true);
          } else {
            finalSubmit();
          }
        }
      })
    }
  }

  return (
    <>
      <Spin spinning={spinVisible || submitLoading}>
        <div className="bidContent pl0">
          <div>
            {
              dateLength > 1 && !isDisabled && !isEndProgress ?
                <div hidden={btnAuthority(['ebtp-expert'])}>
                  <Space>
                    <FileDown apiUrl={`/api/biz-service-ebtp-rsms/v1/abstract/getJuryAbstracet?reviewTurnId=${getURLInformation("turnId")}&reviewType=1`} fileName='11' type='xlsx' method='GET' btnName='初审摘录表导出' />
                    <Upload {...props}>
                      <Button type="primary">初审摘录表导入</Button>
                    </Upload>
                  </Space>
                </div> : null
            }
          </div>
          <Tabs defaultActiveKey="0" className="tab-mb10" onChange={getTabId}>
            {
              tabList.map((item: any, index: any) => {
                if (item.name == '初审汇总') {
                  return (
                    <TabPane tab={item.name} key={index}>
                      {reviewStatus == 2 || reviewStatus == 3 ? null : (
                        <div>
                          {tableDisplay == true ? (
                            <Button hidden={btnAuthority(['ebtp-expert'])} type="primary" size="small" className="fr ml10 mb10" onClick={() => verificationRiskControl()} loading={submitLoading}>提交汇总</Button>
                          ) : null}
                          <Button hidden={btnAuthority(['ebtp-expert'])} onClick={getLock} type="primary" size="small" className="fr mb10">评审解锁</Button>
                        </div>
                      )}
                      {tableDisplay == true ? (
                        <>
                          <p className="red mb0">初审结果汇总表</p>
                          <BidPreliminarySummary readOnly={reviewStatus == 2 || reviewStatus == 3} summaryRef={ref} reload={count} totalSupplier={totalSupplierColumns} onSubmit={(value) => {
                            setQualifyNumber(value);
                          }} isBxOneSecond={isBxOneSecond} isNodeEnd={isNodeEnd} />
                          {qualifyNumber < 3 ? (
                            <div>
                              <div style={{ margin: '8px 0px' }}>
                                <span style={{ color: '#b30000' }}>{qualifyNumber == 1 && isBxOneSecond ? '合格供应商仅一家，是否继续进行' : '合格供应商不足三家，是否继续进行详审'}：</span>
                                <Radio.Group onChange={radioOnChange} value={radioValue} disabled={reviewStatus == 2 || reviewStatus == 3 || (qualifyNumber == 1 && isBxOneSecond && isNodeEnd)}>
                                  <Radio value={1}>是，继续进行</Radio>
                                  <Radio value={0}>否，终止评审</Radio>
                                </Radio.Group>
                              </div>
                              {qualifyNumber == 1 && isBxOneSecond && radioValue == 1 && <div style={{ margin: '8px 70px' }}>
                                <span style={{ color: '#b30000' }}>是否需自定义评审流程：</span>
                                <Radio.Group onChange={processOnChange} value={processValue} disabled={reviewStatus == 2 || reviewStatus == 3 || (qualifyNumber == 1 && isBxOneSecond && isNodeEnd)}>
                                  <Radio value={1}>是，需自定义评审流程</Radio>
                                  <Radio value={0}>否，继续原流程</Radio>
                                </Radio.Group>
                              </div>}
                              <Form
                                {...layout}
                                form={form}
                                name="control-hooks"
                                onFinish={onFinish}
                                validateMessages={validateMessages}
                              >
                                <Form.Item
                                  name="remarks"
                                  label="说明"
                                  rules={[{ required: !(reviewStatus == 2 || reviewStatus == 3 || (qualifyNumber == 1 && isBxOneSecond && isNodeEnd)) && radioValue == 1 }]}
                                  hidden={radioValue == 0}
                                >
                                  <TextArea maxLength={500} disabled={reviewStatus == 2 || reviewStatus == 3 || (qualifyNumber == 1 && isBxOneSecond && isNodeEnd)} bordered={!(reviewStatus == 2 || reviewStatus == 3 || (qualifyNumber == 1 && isBxOneSecond && isNodeEnd))} placeholder="请填写说明" rows={3} autoSize={reviewStatus == 2 || reviewStatus == 3 || (qualifyNumber == 1 && isBxOneSecond && isNodeEnd)} />
                                </Form.Item>
                                {reviewStatus == 2 || reviewStatus == 3 || (qualifyNumber == 1 && isBxOneSecond && isNodeEnd) ? (
                                  <Form.Item
                                    name="fileId"
                                    label="说明文件"
                                    hidden={radioValue == 0}
                                  >
                                    <ExtendUpload bid={uploadId} uploadProps={{ disabled: true }} />
                                  </Form.Item>
                                ) : (

                                  <Form.Item
                                    name="fileId"
                                    label="说明文件"
                                    hidden={radioValue == 0}
                                    extra="最多上传一个文件，每个最大30MB"
                                  >
                                    <ExtendUpload maxSize={30} bid={uploadId} uploadProps={{}} maxCount={1}></ExtendUpload>
                                  </Form.Item>
                                )}
                              </Form>
                            </div>
                          ) : null}
                        </>
                      ) : (
                        <>
                          <p className="red">初审进度表</p>
                          <BidPreliminarySpeed reload={count} />
                        </>
                      )}
                    </TabPane>
                  )
                } else {
                  return (
                    <TabPane tab={item.name} key={index}>
                      <div>
                        <div className="mb10">
                          <div className="process">我的进度：<Progress percent={process} /></div>
                          <div className="block">
                            <Space>
                              {
                                isDisabled || isEndProgress ? null : <Button hidden={btnAuthority(['ebtp-expert'])} onClick={() => setIsModalVisible(true)} type="primary">全部合格</Button>
                              }
                              {
                                isDisabled || isEndProgress ? null : <Button hidden={btnAuthority(['ebtp-expert'])} onClick={() => saveSorce()} type="primary">保存</Button>
                              }
                              {
                                (process > 100 || process == 100) && !isDisabled && !isEndProgress ? <Button hidden={btnAuthority(['ebtp-expert'])} onClick={() => submit()} type="primary">提交</Button> : null
                              }
                              <Button onClick={openDetail} type="primary">初审详情</Button>
                            </Space>
                          </div>
                        </div>
                        <div>
                          <Pagination
                            current={current}
                            total={total}
                            defaultPageSize={3}
                            showSizeChanger={false}
                            onChange={(e) => changePagination(e, typeCategory, totalSupplierColumns)}
                            size="small"
                            className="mb8"
                          />
                          <Table pagination={false} columns={supplierColumns} dataSource={dataSource} />
                        </div>
                      </div>
                    </TabPane>
                  )
                }
              })
            }
          </Tabs>
        </div>
        <Modal // 初审详情
          width={1000}
          title="初审详情"
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={null}
          className="tableTop"
          centered
          style={{ maxHeight: modalHeight }}
          bodyStyle={{ maxHeight: modalHeight - 107, overflowY: 'auto' }}
        >
          <Menu
            onClick={handleClick}
            style={{ width: 180 }}
            defaultSelectedKeys={['1']}
            defaultOpenKeys={['sub1']}
            mode="inline"
            className="left-menu"
          >
            <SubMenu key="sub1" title="评审记录表">
              <Menu.Item key="1">初审记录表</Menu.Item>
              <Menu.Item key="2">专家个人初审表</Menu.Item>
            </SubMenu>
          </Menu>
          {preliminaryDetails}
        </Modal>
        <Modal // 初审解锁
          title="初审解锁"
          width={600}
          visible={lockVisible}
          onCancel={() => setLockVisible(false)}
          onOk={handleOk}
          centered
        >
          <label>解锁专家：</label>
          <Checkbox.Group options={plainList} onChange={changeLock} />
        </Modal>
        <Modal // 备注
          title="备注"
          width={600}
          visible={remarkVisible}
          destroyOnClose
          onCancel={() => setRemarkVisible(false)}
          onOk={() => closeRemarks()}
          centered
        >
          <Form form={remarkForm}>
            <Form.Item name='remarks'>
              <TextArea maxLength={500} disabled={isDisabled || isEndProgress} rows={4} />
            </Form.Item>
          </Form>
        </Modal>
        <Modal title="全部合格" visible={isModalVisible} onOk={() => makeQualified()} onCancel={() => setIsModalVisible(false)}>
          <p>此操作会删除原有数据，是否继续？</p>
        </Modal>
        {/**风控组件 */}
        {riskVisible && <RiskPreventionSoft
          modalVisible={riskVisible}
          onCancel={() => {
            setRiskVisible(false);
            setRiskData([]);
          }}
          onSubmit={() => finalSubmit()}
          data={riskData}
        />}
      </Spin>
    </>
  )
}
export default Index
