import React, { useEffect, useState } from 'react';
import { Button, Table, Tabs, Space, Progress, Radio, Input, Checkbox, Select, Modal, Pagination, Spin, Form, message, Upload } from 'antd';
import { getTabList, getProgress, getScoreDetail, getRegister, submitDetail, updateJudgesStatus, findPriceScoreList, getEval } from './service';
import '@/assets/ld_style.less'
import FirstTrialTableDetailed from '../BidDetailedManager/module/FirstTrialTableDetailed';
import { getSessionProjectData, getSessionUserData, getRoomId } from '@/utils/session';
import FileDown from '@/utils/Download';
import { getURLInformation } from '@/utils/CommonUtils';
import { Link } from 'umi';

const { TabPane } = Tabs;
const { Option } = Select;
const { TextArea } = Input;
const CheckboxGroup = Checkbox.Group;

let assessRoomId: any, reviewTurnId: any, reviewType: any, bidEvalId: any

const Index: React.FC<{}> = () => {
  const [detailVisible, setDetailVisible] = useState<boolean>(false); // 详审记录表
  const [tabList, setTabList] = useState<any>([]); // tab
  const [typeId, setTypeId] = useState<any>(); // tabId
  const [tabListName, setTabListName] = useState<any>(); // tab名称
  const [typeCategory, setTypeCategory] = useState<any>(); // tab类型
  const [process, setProcess] = useState<any>(); // 我的进度
  const [totalSupplier, setTotalSupplier] = useState<any>([]); // 总供应商列头
  const [dataSource, setDataSource] = useState<any>([]); // 初审项配置 
  const [supplierColumns, setSupplierColumns] = useState<any>([]); // 当前显示供应商列头
  const [current, setCurrent] = useState<number>(1); // 当前页码
  const [total, setTotal] = useState<number>(1); // 共多少数据
  const [bidEvalDetailDTOList, setBidEvalDetailDTOList] = useState<any>([]); // 提交数组
  const [subId, setSubId] = useState<any>(); // 提交id
  const [spinVisible, setSpinVisible] = useState<boolean>(false); // 加载中
  const [remarkVisible, setRemarkVisible] = useState<boolean>(false); // 备注弹窗
  const [remarksVal, setRemarksVal] = useState<any>(); // 备注
  const [remarkForm] = Form.useForm(); // 备注表单
  const [isDisabled, setIsDisabled] = useState<boolean>(false); // 是否可编辑
  const [offerSource, setOfferSource] = useState<any>([]); // 报价总数据
  const [offerTotalSource, setOfferTotalSource] = useState<any>([]); // 报价数据 
  const [offerCurrent, setOfferCurrent] = useState<number>(1); // 当前页码
  const [offerTotal, setOfferTotal] = useState<number>(1); // 共多少数据
  const [isDisabledOffer, setIsDisabledOffer] = useState<boolean>(false); // 报价是否可编辑
  let projectName = getSessionProjectData().projectName
  //祥审记录表
  const [firstTrialTableDetailedTable, setFirstTrialTableDetailedTable] = useState<any>();

  const columns: any[] = [  // 详审表头
    {
      title: '详审项',
      dataIndex: 'scoreItem',
    },
    {
      title: '评分标准',
      dataIndex: 'rvwStandard',
    },
  ];

  const offerColumns: any[] = [ // 报价表头
    {
      title: '排序',
      render: (text: any, record: any, index: any) => `${index + 1}`
    },
    {
      title: '投标人姓名',
      dataIndex: 'supplierRegisterName',
    },
    {
      title: '投标人报价',
      dataIndex: 'bidContent',
    },
    {
      title: '查看报价文件',
      render: (text: any, record: any, index: any) => {
        return (
          <Button type="link" danger>查看</Button>
        )
      }
    },
    {
      title: '报价分录入',
      render: (text: any, record: any, index: any) => {
        if (record.judgesStatus == '2') {
          disabledOffer = true
        }
        if (record.priceScore) {
          return (
            <Input
              disabled={disabledOffer}
              onFocus={e => offerValueChange(e, record)}
              onChange={e => offerSourceChange(e, record)}
              value={record.priceScore} style={{ width: 160 }} />
          )
        } else {
          return (
            <Input disabled={disabledOffer} onChange={e => offerSourceChange(e, record)} value={record.priceScore} style={{ width: 160 }} />
          )
        }
      }
    }
  ]

  const saveSorce = () => { // 保存
    console.log(bidEvalDetailDTOList)
    if (bidEvalDetailDTOList.length > 0) {
      setSpinVisible(true)
      let date = {
        id: subId,
        bidEvalId: bidEvalId,
        categoryId: typeId,
        category: typeCategory,
        judgesStatus: '1',
        bidEvalDetailDTOList: bidEvalDetailDTOList
      }
      submitDetail({ ...date }).then((res) => {
        if (res.code == 200) {
          setSpinVisible(false)
          setBidEvalDetailDTOList([])
          if (tabListName == '报价') {
            myProcess(typeId)
            // changeOffer(offerCurrent, typeId, offerTotalSource)
          } else {
            // ratingData(typeId)
            // changePagination(current, typeId, totalSupplier)
            myProcess(typeId)
          }
        }
      })
    }
  }

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

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

  const getTabId = (key: any) => { // tab切换获取当前tab的key
    setTypeId(tabList[key].id)
    setTypeCategory(tabList[key].category)
    setTabListName(tabList[key].name)
    myProcess(tabList[key].id)
    if (tabList[key].name == '报价') {
      offerList(tabList[key].id)
    } else {
      changePagination(1, tabList[key].id, totalSupplier)
    }
  }

  let disabledOffer: any = false
  const offerList = (id: any) => { // 报价数据
    let date = {
      reviewType: reviewType,
      reviewTurnId: reviewTurnId,
      categoryId: id
    }
    findPriceScoreList({ ...date }).then((res) => {
      if (res.code == 200) {
        if (res.data.judgesStatus == '2') {
          disabledOffer = true
          setIsDisabledOffer(true)
        } else {
          disabledOffer = false
          setIsDisabledOffer(false)
        }
        setSubId(res.data.id)
        res.data.priceScoreMap.dataList.map((item: any) => {
          item.judgesStatus = res.data.judgesStatus
        })
        setOfferTotalSource(res.data.priceScoreMap.dataList) // 报价总数据
        setOfferTotal(res.data.priceScoreMap.dataList.length) // 分页
        changeOffer(1, id, res.data.priceScoreMap.dataList) // 分页数据
      }
    })
  }

  const offerSourceChange = (e: any, val: any) => { // 报价分数修改
    offerSource.map((item: any) => {
      if (item.supplierRegisterId == val.supplierRegisterId && item.detailId == val.detailId) {
        item.priceScore = e.target.value
      }
    })
    let x = false;
    bidEvalDetailDTOList.map((item: any) => {
      if (item.supplierRegisterId == val.supplierRegisterId && item.detailId == val.detailId) {
        item.resultValue = e.target.value
        x = true
      }
    })
    if (!x) {
      if (val.id) {
        bidEvalDetailDTOList.push({ 'resultValue': e.target.value, 'id': val.id, 'supplierRegisterId': val.supplierRegisterId, 'detailId': val.detailId });
      } else {
        bidEvalDetailDTOList.push({ 'resultValue': e.target.value, 'id': '', 'supplierRegisterId': val.supplierRegisterId, 'detailId': val.detailId });
      }
    }
    setOfferSource([...offerSource])
    console.log(bidEvalDetailDTOList)
  }

  const offerValueChange = (e: any, val: any) => { // 报价分数获取焦点
    offerSource.map((item: any, index: any) => {
      if (item.id && item.id == val.id) {
        item.priceScore = ''
      }
    })
    setOfferSource([...offerSource])
  }

  const changeOffer = (page: any, id: any, totalSource: any) => { // 报价数据分页
    if (bidEvalDetailDTOList.length > 0) {
      saveSorce() // 保存
    }
    setOfferCurrent(page)
    let currentDate = (page - 1) * 3
    setOfferSource(totalSource.slice(currentDate, currentDate + 3))
  }

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

  const getRemark = (val: any, id: any) => { // 备注
    if (val.remarks) {
      remarkForm.setFieldsValue({ remarks: val.remarks })
    } else {
      remarkForm.setFieldsValue({ remarks: '' })
    }
    if (val.detailId) {
      setRemarksVal({ 'id': val.id, 'supplierRegisterId': id, 'detailId': val.detailId, 'resultValue': val.resultValue, 'remarks': val.remarks })
    } else {
      setRemarksVal({ '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
          x = true
          return
        }
      })
      if (!x) {
        if (remarksVal.resultValue != '') {
          dataSource.map((item: any) => {
            if (remarksVal.detailId) {
              if (remarksVal.detailId == item.id && item.scoreMap[remarksVal.supplierRegisterId] && item.scoreMap[remarksVal.supplierRegisterId].remarks != remarkForm.getFieldsValue().remarks) {
                bidEvalDetailDTOList.push({ '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({ '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 supplierTab = (id: any) => { // 供应商列头接口
    let date = {
      assessRoomId: assessRoomId,
      reviewTurnId: reviewTurnId
    }
    getRegister({ ...date }).then((res) => {
      if (res.code == 200) {
        setTotal(res.data.length)
        setTotalSupplier(res.data)
        changePagination(1, id, res.data)
        getFirstTrialTableDetailed(res.data, date);
      }
    })
  }

  let supplierId: any = [] // 供应商数组id
  const changePagination = (page: any, id: 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,
        dataIndex: item.supplierRegisterId,
        editable: true,
        render: (text: any, record: any) => {
          if (record.scoreMethod == '0') { // 单选
            const radioOptions: any[] = [];
            record.standardList.map((item: any) => {
              radioOptions.push({ label: item.standardName + '(' + item.standardDetailScore + '分)' + item.id, value: item.standardDetailScore + '-' + item.id })
            })
            if (record.scoreMap && record.scoreMap[item.supplierRegisterId]) {
              return (
                <div>
                  <Radio.Group
                    disabled={disabled}
                    value={record.scoreMap[item.supplierRegisterId].resultValue + '-' + record.scoreMap[item.supplierRegisterId].standardId}
                    options={radioOptions}
                    onChange={e => onChange(e, record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)}
                  /><br />
                  <Button onClick={() => getRemark(record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)} type="link" danger>备注</Button>
                  <Button type="link" danger>
                    <Link to={`/viewOfTenderDocumentsSecond?id=${record.id}&supplierId=${item.supplierRegisterId}`}>查看应答文件</Link>
                  </Button>
                </div>
              )
            } else {
              return (
                <div>
                  <Radio.Group
                    value={''}
                    options={radioOptions}
                    onChange={e => onChange(e, record, item.supplierRegisterId)}
                  /><br />
                  <Button onClick={() => getRemark(record, item.supplierRegisterId)} type="link" danger>备注</Button>
                  <Button type="link" danger>
                    <Link to={`/viewOfTenderDocumentsSecond?id=${record.id}&supplierId=${item.supplierRegisterId}`}>查看应答文件</Link>
                  </Button>
                </div>
              )
            }
          } else if (record.scoreMethod == '1') {// 多选
            const checkboxOptions: any[] = [];
            record.standardList.map((item: any) => {
              checkboxOptions.push({ label: item.standardName + '(' + item.standardDetailScore + '分)' + item.id, value: item.standardDetailScore + '-' + item.id })
            })
            if (record.scoreMap && record.scoreMap[item.supplierRegisterId]) {
              let defaultArr = record.scoreMap[item.supplierRegisterId].standardId.split(",")
              let defaultValue: any = []
              record.standardList.map((item: any) => {
                defaultArr.map((val: any) => {
                  if (item.id == val) {
                    defaultValue.push(item.standardDetailScore + '-' + item.id)
                  }
                })
              })
              return (
                <div>
                  <CheckboxGroup
                    disabled={disabled}
                    options={checkboxOptions}
                    value={defaultValue}
                    onChange={e => checkChange(e, record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)}
                  /><br />
                  <Button type="link" danger onClick={() => getRemark(record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)}>备注</Button>
                  <Button type="link" danger>
                    <Link to={`/viewOfTenderDocumentsSecond?id=${record.id}&supplierId=${item.supplierRegisterId}`}>查看应答文件</Link>
                  </Button>
                </div>
              )
            } else {
              return (
                <div>
                  <CheckboxGroup
                    options={checkboxOptions}
                    value={[]}
                    onChange={e => checkChange(e, record, item.supplierRegisterId)}
                  /><br />
                  <Button type="link" danger onClick={() => getRemark(record, item.supplierRegisterId)}>备注</Button>
                  <Button type="link" danger>
                    <Link to={`/viewOfTenderDocumentsSecond?id=${record.id}&supplierId=${item.supplierRegisterId}`}>查看应答文件</Link>
                  </Button>
                </div>
              )
            }
          } else if (record.scoreMethod == '2') { // 人工
            if (record.scoreMap && record.scoreMap[item.supplierRegisterId]) {
              return (
                <div>
                  <Input
                    disabled={disabled}
                    value={record.scoreMap[item.supplierRegisterId].resultValue}
                    style={{ width: 160 }}
                    onChange={e => inputChange(e, record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)}
                    onFocus={e => inputFocus(e, record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)}
                  />
                  <br />
                  <Button type="link" danger onClick={() => getRemark(record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)}>备注</Button>
                  <Button type="link" danger>
                    <Link to={`/viewOfTenderDocumentsSecond?id=${record.id}&supplierId=${item.supplierRegisterId}`}>查看应答文件</Link>
                  </Button>
                </div>
              )
            } else {
              return (
                <div>
                  <Input onChange={e => inputChange(e, record, item.supplierRegisterId)} style={{ width: 160 }} /><br />
                  <Button type="link" danger onClick={() => getRemark(record, item.supplierRegisterId)}>备注</Button>
                  <Button type="link" danger><Link to={`/viewOfTenderDocumentsSecond?id=${record.id}&supplierId=${item.supplierRegisterId}`}>查看应答文件</Link></Button>
                </div>
              )
            }
          } else if (record.scoreMethod == '4') { // 步长
            let optionLength = record.highScore / record.lowScore
            let optionArr: any = []
            for (let i = 1; i <= optionLength; i++) {
              optionArr.push(record.lowScore * i)
            }
            if (record.scoreMap && record.scoreMap[item.supplierRegisterId]) {
              return (
                <div>
                  <Select
                    disabled={disabled}
                    value={record.scoreMap[item.supplierRegisterId].resultValue}
                    style={{ width: 160 }}
                    onChange={e => handleChange(e, record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)}
                  >
                    {
                      optionArr.map((item: any) => {
                        return (
                          <Option value={item}>{item}</Option>
                        )
                      })
                    }
                  </Select><br />
                  <Button type="link" danger onClick={() => getRemark(record.scoreMap[item.supplierRegisterId], item.supplierRegisterId)}>备注</Button>
                  <Button type="link" danger><Link to={`/viewOfTenderDocumentsSecond?id=${record.id}&supplierId=${item.supplierRegisterId}`}>查看应答文件</Link></Button>
                </div>
              )
            } else {
              return (
                <div>
                  <Select value="" style={{ width: 160 }} onChange={e => handleChange(e, record, item.supplierRegisterId)}>>
                    {
                      optionArr.map((item: any) => {
                        return (
                          <Option value={item}>{item}</Option>
                        )
                      })
                    }
                  </Select><br />
                  <Button type="link" danger onClick={() => getRemark(record, item.supplierRegisterId)}>备注</Button>
                  <Button type="link" danger><Link to={`/viewOfTenderDocumentsSecond?id=${record.id}&supplierId=${item.supplierRegisterId}`}>查看应答文件</Link></Button>
                </div>
              )
            }
          }
        },
      })
    })
    setSupplierColumns([...newColumns])
    ratingData(id)
  }

  let disabled: any = false
  let totalQualified: any = []
  const ratingData = async (id: any) => { // 评分数据
    let query = {
      bidEvalId: bidEvalId,
      categoryId: id,
      supplierRegisterIds: supplierId
    }
    await getScoreDetail({ ...query }).then((res) => { // 评分数据
      if (res.code == 200) {
        if (res.data.judgesStatus == '2') {
          disabled = true
          setIsDisabled(true)
        } else {
          disabled = false
          setIsDisabled(false)
        }
        setSubId(res.data.id)
        setDataSource(res.data.detailList)
        totalQualified = res.data.detailList
      }
    })
  }

  const onChange = (e: any, val: any, id: any) => { // 单选框操作
    let detailValue = e.target.value.split("-")[0]
    let standardId = e.target.value.split("-")[1]
    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 = detailValue
              item.scoreMap[supplierId[i]].detailValue = detailValue
              item.scoreMap[supplierId[i]].standardId = standardId
            }
          }
        }
      } 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]] = { 'detailValue': detailValue, 'resultValue': detailValue, 'standardId': standardId, 'id': '', 'supplierRegisterId': supplierId[i], 'detailId': val.id, 'remarks': '' }
            }
          }
        }
      }
    })
    let x = false;
    if (val.detailId) {
      bidEvalDetailDTOList.map((item: any) => {
        if (item.supplierRegisterId == id && item.detailId == val.detailId) {
          item.resultValue = detailValue
          item.detailValue = detailValue
          item.standardId = standardId
          x = true
        }
      })
    }
    if (!x) {
      if (val.detailId) {
        bidEvalDetailDTOList.push({ 'detailValue': detailValue, 'resultValue': detailValue, 'standardId': standardId, 'id': val.id, 'supplierRegisterId': val.supplierRegisterId, 'detailId': val.detailId, 'remarks': val.remarks });
      } else {
        bidEvalDetailDTOList.push({ 'detailValue': detailValue, 'resultValue': detailValue, 'standardId': standardId, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'remarks': '' });
      }
    }
    setDataSource([...totalQualified])
    console.log(bidEvalDetailDTOList)
  }

  const checkChange = (list: any, val: any, id: any) => { // 复选框操作
    let detailValue: any, resultValue: any = 0, standardId: any
    let detailValueArr: any = []
    let standardIdArr: any = []
    if (val.detailId) {
      for (let i = 0; i < list.length; i++) {
        detailValueArr.push(list[i].split("-")[0])
        standardIdArr.push(list[i].split("-")[1])
        resultValue += Number(list[i].split("-")[0])
      }
      detailValue = detailValueArr.toString()
      standardId = standardIdArr.toString()
    } else {
      detailValue = list[0].split("-")[0]
      resultValue = list[0].split("-")[0]
      standardId = list[0].split("-")[1]
    }
    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 = resultValue
              item.scoreMap[supplierId[i]].detailValue = detailValue
              item.scoreMap[supplierId[i]].standardId = standardId
            }
          }
        }
      } 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]] = { 'detailValue': detailValue, 'resultValue': resultValue, 'standardId': standardId, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'remarks': '' }
            }
          }
        }
      }
    })
    let x = false;
    if (val.detailId) { // 处理数据选中
      bidEvalDetailDTOList.map((item: any) => {
        if (item.supplierRegisterId == id && item.detailId == val.detailId) {
          item.resultValue = resultValue
          item.detailValue = detailValue
          item.standardId = standardId
          x = true
        }
      })
    }
    if (!x) { // 向保存数组添加数据
      if (val.detailId) {
        bidEvalDetailDTOList.push({ 'detailValue': detailValue, 'resultValue': resultValue, 'standardId': standardId, 'id': val.id, 'supplierRegisterId': val.supplierRegisterId, 'detailId': val.detailId, 'remarks': val.remarks });
      } else {
        bidEvalDetailDTOList.push({ 'detailValue': detailValue, 'resultValue': resultValue, 'standardId': standardId, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'remarks': '' });
      }
    }
    setDataSource([...totalQualified])
    console.log(bidEvalDetailDTOList)
  }

  const handleChange = (e: any, val: any, id: any) => { // 下拉框操作
    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
              item.scoreMap[supplierId[i]].detailValue = e
            }
          }
        }
      } 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]] = { 'detailValue': e, 'resultValue': e, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'remarks': '' }
            }
          }
        }
      }
    })
    let x = false;
    if (val.detailId) {
      bidEvalDetailDTOList.map((item: any) => {
        if (item.supplierRegisterId == id && item.detailId == val.detailId) {
          item.resultValue = e
          item.detailValue = e
          x = true
        }
      })
    }
    if (!x) {
      if (val.detailId) {
        bidEvalDetailDTOList.push({ 'detailValue': e, 'resultValue': e, 'id': val.id, 'supplierRegisterId': val.supplierRegisterId, 'detailId': val.detailId, 'remarks': val.remarks });
      } else {
        bidEvalDetailDTOList.push({ 'detailValue': e, 'resultValue': e, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'remarks': '' });
      }
    }
    setDataSource([...totalQualified])
    console.log(bidEvalDetailDTOList)
  }

  const inputChange = (e: any, val: any, id: any) => { // 输入框操作
    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
            }
          }
        }
      } 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]] = { 'detailValue': e.target.value, 'resultValue': e.target.value, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'remarks': '' }
            }
          }
        }
      }
    })
    let x = false;
    if (val.detailId) {
      bidEvalDetailDTOList.map((item: any) => {
        if (item.supplierRegisterId == id && item.detailId == val.detailId) {
          item.resultValue = e.target.value
          item.detailValue = e.target.value
          x = true
        }
      })
    }
    if (!x) {
      if (val.detailId) {
        bidEvalDetailDTOList.push({ 'detailValue': e.target.value, 'resultValue': e.target.value, 'id': val.id, 'supplierRegisterId': val.supplierRegisterId, 'detailId': val.detailId, 'remarks': val.remarks });
      } else {
        bidEvalDetailDTOList.push({ 'detailValue': e.target.value, 'resultValue': e.target.value, 'id': '', 'supplierRegisterId': id, 'detailId': val.id, 'remarks': '' });
      }
    }
    setDataSource([...totalQualified])
    console.log(bidEvalDetailDTOList)
  }

  const inputFocus = (e: any, val: any, id: any) => { // 手动输入框获取焦点
    totalQualified.map((item: any) => { // 处理页面回显
      if (val.detailId == item.id) {
        for (let i = 0; i < supplierId.length; i++) {
          if (id == supplierId[i]) {
            item.scoreMap[supplierId[i]].resultValue = ''
          }
        }
      }
    })
    setDataSource([...totalQualified])
  }

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

  /**
   * 获取祥审记录表数据
   * @param defaultSupplierData 
   * @param findScoreRecordParams 
   */
  const getFirstTrialTableDetailed = (defaultSupplierData: any, findScoreRecordParams: any) => {
    setFirstTrialTableDetailedTable(
      <FirstTrialTableDetailed
        defaultNumber={3}
        defaultSupplierData={defaultSupplierData}
        supplierParams={null}
        findScoreRecordParams={{ ...findScoreRecordParams, reviewType: "2" }}
      />)
  }

  // const getWord = () => { // 初审摘录表导出
  //   let projectName = getSessionProjectData().projectName
  //   window.open('http://125.32.114.204:8760/api/biz-service-ebtp-rsms/v1/abstract/getJuryAbstracet?reviewTurnId=1331563852545916928&reviewType=2&projectName=' + projectName)
  // }

  let JwtToken = getSessionUserData().userId
  const props = { // 初审摘录表导入
    name: 'file',
    data: {
      // reviewTurnId: getURLInformation("turnId"),
      assessRoomId: getRoomId(),
      reviewType: '2'
    },
    showUploadList: false,
    accept: 'application/vnd.ms-application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    action: 'http://125.32.114.204:8760/api/biz-service-ebtp-rsms/v1/abstract/upload',
    headers: {
      authorization: 'authorization-text',
      JwtToken: JwtToken
    },
    onChange(info: any) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success('初审摘录表导入成功');
        myProcess(typeId)
        changePagination(1, typeId, totalSupplier)
      } else if (info.file.status === 'error') {
        message.error('初审摘录表导入失败');
      }
    },
  };

  useEffect(() => {
    let date = {
      reviewTurnId: getURLInformation("turnId"),
      reviewType: '2',
    }
    getEval({ ...date }).then((res) => {
      if (res.code == 200) {
        assessRoomId = res.data.assessRoomId
        reviewTurnId = res.data.reviewTurnId
        reviewType = res.data.reviewType
        bidEvalId = res.data.id
        gettabList()
      }
    })
  }, []);

  return (
    <>
      <Spin spinning={spinVisible}>
        <div className="bidContent">
          {/* <h3 className="name">项目名称：测试项目<span>标段名称：标包1</span></h3> */}
          <div>
            <Space>
              {/* <Button onClick={() => getWord()} type="primary" size="small">初审摘录表导出</Button> */}
              <FileDown apiUrl={`/api/biz-service-ebtp-rsms/v1/abstract/getJuryAbstracet?reviewTurnId=${getURLInformation("turnId")}&reviewType=2&projectName=${projectName}`} fileName='详审摘录表' type='xlsx' method='GET' btnName='详审摘录表导出' />
              <Upload {...props}>
                <Button type="primary">详审摘录表导入</Button>
              </Upload>
            </Space>
          </div>
          <Tabs defaultActiveKey="0" onChange={getTabId}>
            {
              tabList.map((item: any, index: any) => {
                if (item.name == '报价') {
                  return (
                    <TabPane tab={item.name} key={index}>
                      <div className="p10 mb20">
                        <div className="process">我的进度：<Progress percent={process} /></div>
                        <div className="block">
                          <Space>
                            {
                              isDisabledOffer ? null : <Button onClick={() => saveSorce()} type="primary" danger>保存</Button>
                            }
                            {
                              (process > 100 || process == 100) && !isDisabledOffer ? <Button onClick={() => submit()} type="primary" danger>提交</Button> : null
                            }
                          </Space>
                        </div>
                        <Table className="labelTable" pagination={false} columns={offerColumns} dataSource={offerSource} />
                        <Pagination
                          defaultCurrent={offerCurrent}
                          total={offerTotal}
                          defaultPageSize={3}
                          showSizeChanger={false}
                          onChange={(e) => changeOffer(e, typeId, offerTotalSource)}
                        />
                      </div>
                    </TabPane>
                  )
                } else {
                  return (
                    <TabPane tab={item.name} key={index}>
                      <div className="p10">
                        <div className="mb20">
                          <div className="process">我的进度：<Progress percent={process} /></div>
                          <div className="block">
                            <Space>
                              {
                                isDisabled ? null : <Button onClick={() => saveSorce()} type="primary" danger>保存</Button>
                              }
                              {
                                (process > 100 || process == 100) && !isDisabled ? <Button onClick={() => submit()} type="primary" danger>提交</Button> : null
                              }
                              {
                                isDisabled ? <Button onClick={() => setDetailVisible(true)} type="primary" danger>详审记录表</Button> : null
                              }
                            </Space>
                          </div>
                        </div>
                        <div>
                          <Pagination
                            defaultCurrent={current}
                            total={total}
                            defaultPageSize={3}
                            showSizeChanger={false}
                            onChange={(e) => changePagination(e, typeId, totalSupplier)}
                          />
                          <Table className="labelTable" pagination={false} columns={supplierColumns} dataSource={dataSource} />
                        </div>
                      </div>
                    </TabPane>
                  )
                }
              })
            }
          </Tabs>
        </div>
        <Modal // 备注
          title="备注"
          width={600}
          visible={remarkVisible}
          onCancel={() => closeRemarks()}
          onOk={() => closeRemarks()}
        >
          <Form form={remarkForm}>
            <Form.Item name='remarks'>
              <TextArea disabled={isDisabled} rows={4} />
            </Form.Item>
          </Form>
        </Modal>
        <Modal // 详审记录表
          width={800}
          title="详审记录表"
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={null}
        >
          {firstTrialTableDetailedTable}
        </Modal>
      </Spin>
    </>
  )
}
export default Index