import React, { useEffect, useState } from "react";
import Link from "react-router-dom/Link";
import PaginationTable from "src/military/components/paginationTable";
import GradesModal from "./gradesModal";
import { getCompetitionDetail, getFinalScoreRankingList, getWinnersAndPublicists, selectWinnersAndPublicists } from "../api";
import { getTaskDetail } from "src/military/task/api";
import { Checkbox, Input, message, Modal, Spin } from "antd";
import sucess from './image/sucess.svg';
import './index.scss';
import '../index.scss';
import { queryString } from "educoder";

function ReviewResult({ history, match, mygetHelmetapi}) {
  const {main_web_site_url} = mygetHelmetapi;
  //id：竞赛或者创客任务id，containerType，1创客2竞赛
  const {containerId, containerType} = match.params;
  let {identifier, status, name, taskModeId} = queryString.parse(window.location.hash.slice(1));
  const [dataList, setDateList] = useState(undefined);
  const [openResultVisible, setOpenResultVisible] = useState(false);
  const [winIds, setWinIds] = useState(undefined);
  const [openRange, setOpenRange] = useState(undefined);
  const [errorMessage,setErrorMessage] = useState();
  const [result, setResult] = useState(undefined);
  const [goNum, setGoNum] = useState(-1);
  const [loading, setLoading] = useState(false);

  // 模态框
  const [opsDetail, setOpsDetail] = useState(undefined);
  const [visible, setVisible] = useState(false);

  const columns = [
    {
      title: '综合排名',
      dataIndex: 'id',
    },
    {
      title: '应征者',
      dataIndex: 'applicantInfo.nickname',
      key: 'expertName',
      render: (text, record) => {
        return containerType ==1 ? text === null ? record.applicantInfo.login : text : record.competitionTeamName || '--';
      }
    },
    {
      title: '最终得分',
      dataIndex: 'finalGrades',
      key: 'phone',
    },
    {
      title: '评审明细',
      ket: 'detali',
      render: (text, record) => {
        return <a className="lookDetail" onClick={()=>{detail(record)}}>查看明细</a>
      }
    }
  ];

  //如果是创客任务，那么多出一列 选择胜出者
  if(containerType == 1){
    columns.splice(4, 0, {
      title: '是否胜出',
      ket: 'isWin',
      align: 'center',
      render: (text, record) => {
        return record.isWin ? <div className="sucess df"><img src={sucess}/>胜出</div> : status == 4 ? <Checkbox onChange={(e)=>{changeIsWin(record.applicantInfo.id, e.target.checked)}}>胜出</Checkbox> : '未胜出';
      }
    });
  }else{
    columns[1].title = "战队名称";
  }

  useEffect(()=>{
    //获取评分
    const params = {
      containerId,
      containerType,
      orderBy: 'finalGradesDesc'
    }
    getFinalScoreRankingList(params).then(response=>{
      if(response && Array.isArray(response.data)){
        //finalGrades 最终得分为null 未到评审时间 0 专家未评审任务
        let index = 1;
        response.data.map(item=>{item.id = index++;setResult(item.finalGrades) })
        containerType == 1 && status >4 ? getWinnersAndPublicists({
          containerId,
          containerType
        }).then(res=>{
          if(res && res.message === "success"){
            response.data.map(item=>{
              item.isWin = res.data.winUserIds.indexOf(item.applicantInfo.id) !== -1;
              item.isPublic = res.data.publicityUserIds.indexOf(item.applicantInfo.id) !== -1;
            })
          }
          setDateList(response.data);
        }):setDateList(response.data)
      }
    })
  },[status])

  //监听status, name, taskModeId 的变化，如果其中任意一个没有值都去请求任务详情接口获取其数据
  useEffect(()=>{
    const bool = status && name && taskModeId;
    if(containerType == 1 && !bool){
      setLoading(true);
      //创客任务
      containerId && getTaskDetail(containerId).then(response=>{
        if(response){
          window.location.href=`${window.location.href}#status=${response.status}&name=${response.name}&taskModeId=${response.taskModeId}`;
        }
      }).finally(()=>{
        setLoading(false);
      })
    }

    const competitionBool = status && name && identifier;
    if(containerType == 2 && !competitionBool){
      setLoading(true);
      //竞赛
      containerId && getCompetitionDetail(containerId).then(response=>{
        if(response && response.message == "success"){
          window.location.href=`${window.location.href}#status=${response.data.current_status}&identifier=${response.data.identifier}&name=${response.data.title}`;
        }
      }).finally(()=>{
        setLoading(false);
      })
    }
  },[status, name, taskModeId, identifier])

  function detail(item){
    setOpsDetail(item);
    setVisible(true);
  }

  function changeIsWin(id, checked){
    const ids = new Set(winIds);
    checked ? ids.add(id) : ids.delete(id);
    setWinIds(Array.from(ids));
  }

  function openResult(){
    if(result === null){
      message.error("还没有到评审结束时间，不能公示结果! ");
      return;
    }
    containerType == 2 && setOpenResultVisible(true);
    if(containerType ==1 && winIds && winIds.length>0){
      taskModeId == 1 && winIds.length >1 ? message.error("此任务是单人悬赏模式， 只能设置一个中标者 ! ") : setOpenResultVisible(true);
    }
  }

  function onOk(){
    setErrorMessage("");
    let ids = [];
    if(!openRange){
      dataList.map(i=> {ids[ids.length] = i.applicantInfo.id;});
    }else if(openRange && isNaN(openRange)){
      setErrorMessage('请输入数字!');
    }else if(openRange && (openRange.indexOf('.')!==-1 || openRange.indexOf('-')!==-1)){
      setErrorMessage('请输入正整数!');
    }else if(openRange && containerType == 1 && openRange < winIds.length){
      setErrorMessage('公示范围不能少于获胜人数!');
    }else if(openRange && openRange > dataList.length){
      setErrorMessage('公示范围超过应征者总数!');
    }else{
      ids[ids.length] = dataList.filter(item=>item.id<=openRange).map(i=>i.applicantInfo.id);
    }
    let params = {
      containerId,
      containerType,
      id: 0,
      publicityUserIds : ids.toString()
    };
    containerType==1 && (params[`winUserIds`] = winIds.toString());
    ids.length!=0 && selectWinnersAndPublicists(params).then(response=>{
      if(response && response.message === "success"){
        message.success("操作成功");
        if(containerType==1){
          window.location.href=`${window.location.href.replace('status=4','status=5')}`;
          status = 5;
          setGoNum(-2);
        }
        setOpenResultVisible(false);
      }
    })
  }
  return (
    <Spin spinning={loading}>
      <div className="expert_review_system centerbox">
        <div className="head_title mb20">
          <div className="df pb10 pt10">
            <span className="font-16 font-w">评审结果</span>
            <button className="but41_border goback_but" onClick={()=>{history.go(goNum)}}>返回上一页</button>
          </div>
          <p className="mt10"><span className="font-w">{containerType ==1 ? '任务':'竞赛'}名称</span><span className="ml10">{decodeURI(name)}</span></p>
          <p className="mt10 pb20">
            <span className="font-w color-grey3">{containerType ==1 ? '任务':'竞赛'}链接</span>
            {containerType == 1 && <Link className="taskLink ml10" target="_blank" to={`/task/taskDetail/${containerId}`} >{`${window.location.origin}/task/taskDetail/${containerId}`}</Link>}
            {containerType == 2 && <a href={`${main_web_site_url}/competitions/${identifier}/home`} target="_blank" className="taskLink ml10">{`${main_web_site_url}/competitions/${identifier}/home`}</a>}
          </p>
        </div>
        {status > 3 ? <React.Fragment>
          <p className="font-16 font-w mb10">{containerType ==1 ? '应征者':'战队'}排名</p>
          <PaginationTable
            dataSource= {dataList}
            columns= {columns}
            scroll={{ y: 384 }}
          />
          <div className="openResult">
            {/* 公示结果仅保留给创客使用 */}
            {containerType == 1 && status == 4 && <button className={(containerType ==1 && winIds && taskModeId == 1 && winIds.length >1) || result === null ? 'disableBut': 'but41_fill'} onClick={openResult}>公示结果</button>}
          </div>
        </React.Fragment>:<div className="nodata font-20">暂无数据，此任务暂未进入{containerType ==1 ? '成果':'竞赛'}评选阶段。</div>}
        <Modal
          title= "请确认公示范围"
          visible= {openResultVisible}
          wrapClassName="openResultModal"
          width={390}
          onCancel= {()=>setOpenResultVisible(false)}
          onOk={onOk}>
            <div className="df">
              公示排名前
              <Input placeholder="请输入" onChange={(e)=>{setOpenRange(e.target.value)}}/>
              名
            </div>
            <p className={`mt5 ${errorMessage && 'errorMes'}`}>{errorMessage || "若未填写此排名，则公示所有名次"}</p>
        </Modal>

        <GradesModal
          visible={visible}
          setVisible={setVisible}
          taskId={containerId}
          opsDetail={opsDetail}
          containerType={containerType}
        />
      </div>
    </Spin>
  )
}
export default ReviewResult;