import { Button, message, Modal, Select, Tooltip } from "antd";
import React, { useEffect, useMemo, useState } from "react";
import Link from "react-router-dom/Link";
import { publishExpertsAndRules } from "src/military/task/api";
import PaginationTable from "../../components/paginationTable";
import { expertReviewArr } from "../../task/static";
import { getCompetitionList, getRules, selectExpertList, updateCompetitionReview } from "../api";
import { competitionStatus } from "../static";

import './index.scss';
const Option = Select.Option;

const statusArr = [];
for (const item of competitionStatus) {
  statusArr[item.value] = item.label;
}

// 竞赛任务状态 current_status 1报名中 2即将开始 3比赛进行中 4作品评选中 5公示中 6已结束
function Competition(props){
  const {mygetHelmetapi, showNotification, history} = props;
  const {main_web_site_url} = mygetHelmetapi;
  const {hash} = history && history.location;
  const [loading, setLoading] = useState(false);
  const [curPage, setCurPage] = useState(hashDate(hash) || 1);
  //是否加入专家评审流程
  const [expertReview,setExpertReview] = useState(undefined);
  //竞赛任务总数
  const [total, setTotal] = useState()
  //竞赛任务列表
  const [competitionList, setCompetitionList] = useState(undefined);
  
  //查看评审规则、查看选取专家、发布评审任务
  const [lookRules, setLookRules] = useState(false);
  const [lookExperts, setLookExperts] = useState(false);
  const [pulicReview, setPublicReview] = useState(false);
  const [rules, setRules] = useState(undefined);
  const [selectedExperts, setSelectedExperts] = useState(undefined);
  const [publicTaskId, setPublicTaskId] = useState(undefined);
  const [reload, setReload] = useState(undefined);

  //竞赛任务列表 表格
  const columns = useMemo(() => {
    return [
      {
        title: "序号",
        dataIndex: "index",
        width: 50,
        align: "center",
      },
      {
        title: "竞赛主标题",
        dataIndex: "title",
        key: "title",
        align: "center",
        render:(text, record)=>{
          return <Tooltip title={`标识: ${record.identifier}, 竞赛副标题: ${record.subtitle}`}><a href={`${main_web_site_url}/competitions/${record.identifier}/home`} target="_blank" className="primary-link">{text}</a></Tooltip>
        }
      },
      {
        title: <Select
          className="column-select"
          showArrow
          defaultValue={' '}
          onChange={(value)=>{setExpertReview(value);updateUrl(1);}}
        >
          <Option key={' '} >专家评审</Option>
          <Option key={true} >已提交评审</Option>
          <Option key={false} >未提交评审</Option>
        </Select>,
        dataIndex: 'is_expert_audit',
        align: "center",
        render: (text, record) => {
          return <Select
            className="column-select"
            showArrow
            defaultValue={text?1:-1}
            onChange={(key) => { changeExpertReviewStatus(key, record.id) }}
            disabled={record.current_status >3 || record.assignRuleAndExperts}
          >
            {
              expertReviewArr.map(item => {
                return <Option key={item.dicItemCode} value={item.dicItemCode}>{item.dicItemName}</Option>
              })
            }
          </Select>
        }
      },
      {
        title: "竞赛状态",
        dataIndex: "current_status",
        key: "current_status",
        align: "center",
        render:(text, record)=>{
          return statusArr[text];
        }
      },
      {
        title: "比赛时间",
        dataIndex: "start_time",
        key: "time",
        align: "center",
        render:(text, record)=>{
          return text +' ~ '+ record.end_time;
        }
      },
      {
        title: "报名人数",
        dataIndex: "team_members_count",
        key: "teamMembersCount",
        align: "center",
      },
      {
        title: '评审规则',
        dataIndex: 'current_status',
        key: "rules",
        render: (text, record) => {
          return record.assignRuleAndExperts ? <Button size='small' type="primary" onClick={()=>{viewRules(record)}}>查看</Button> : record.is_expert_audit && text<4 ? <Link className="primary-link" to={`/managements/expert/task/review/rules/${2}/${record.id}/?identifier=${record.identifier}&status=${record.current_status}&name=${record.title}&reviewStartTime=${record.end_time}&reviewEndTime=${record.review_time}`}>编辑</Link> : <span className='gary_span'>编辑</span>
        }
      },
      {
        title: '专家选取',
        dataIndex: 'current_status',
        key: "experts",
        render: (text, record) => {
          return record.assignRuleAndExperts ? <Button size='small' type="primary" onClick={()=>{viewExperts(record)}}>查看</Button> : record.is_expert_audit && text<4 ? <Link className="primary-link" to={`/managements/expert/task/review/select/${2}/${record.id}/?identifier=${record.identifier}&name=${record.title}`}>选择</Link> : <span className='gary_span'>选择</span>
        }
      },
      {
        title: '评审任务',
        dataIndex: 'current_status',
        key: "review",
        render: (text, record) => {
          return record.assignRuleAndExperts ? <span className='gary_span'>已发布</span> : record.is_expert_audit && text<4 ? <Button size='small' type="primary" onClick={()=>{publishTaskReview(record)}}>发布</Button> : <span className='gary_span'>发布</span>
        }
      },
      {
        title: '评审结果',
        dataIndex: 'assignRuleAndExperts',
        key: "results",
        render: (text, record) => {
          return text ? <Link className="primary-link" to={`/managements/expert/task/review/results/${2}/${record.id}/#status=${record.current_status}&identifier=${record.identifier}&name=${record.title}`}>查看</Link>:<span className='gary_span'>查看</span>
        }
      }
    ];
  }, [competitionList, curPage]);

  //已选取专家 表格
  const columnsExperts = useMemo(() => {
    return [
      {
        title: '编号',
        dataIndex: 'index',
        width: 80,
        align: 'center',
      },
      {
        title: '专家姓名',
        dataIndex: 'expertName',
        key: 'expertName',
        width: 120,
      },
      {
        title: '手机号码',
        dataIndex: 'phone',
        width: 130,
        key: 'phone',
      },
      {
        title: '最高学历',
        dataIndex: 'highestDegree',
        key: 'highestDegree',
      },
      {
        title: '专业职称',
        dataIndex: 'professionalTitle',
      },
      {
        title: '专家类别',
        dataIndex: 'expertType',
      },
      {
        title: '评审领域',
        dataIndex: 'reviewAreas',
        align: 'center',
        width: 260,
      },
      {
        title: '专家评分',
        dataIndex: 'expertScore',
        align: 'center',
        render:(text,record)=>{
          return record.expertScore || '--';
        }
      }
    ];
  }, []);

  //发布评审任务
  function publishTaskReview(record){
    if(!record.ruleEdited || !record.expertSelected){
      message.error("请先编辑评审规则以及选取评选专家再发布此任务");
    }else{
      getRules({containerId: record.id, containerType: 2, statusString: 3}).then(response=>{
        if(response && response.message === "success"){
          setRules(response.data);
        }
      })
      selectExpertList({containerId: record.id, containerType: 2, pageSize: 10000, curPage: 1}).then(response=>{
        if(response && response.message === "success" && Array.isArray(response.data.rows)){
          let index = 1;
          for (const item of response.data.rows) {
            item.reviewAreas = `${item.reviewAreaOne} ${item.reviewAreaTwo ? `、${item.reviewAreaTwo}`:''} ${item.reviewAreaThree ? `、${item.reviewAreaThree}`:''}`;
            item.index = (index++) + (curPage > 1 ? (curPage - 1) * 10 : 0);
          }
          setPublicTaskId(record.id);
          setSelectedExperts(response.data.rows);
          setPublicReview(true);
        }
      });
    }
  }

  //已发布任务  查看评审规则
  function viewRules(record){
    getRules({containerId: record.id, containerType: 2, statusString: '-1,1,2'}).then(response=>{
      if(response && response.message === "success"){
        setRules(response.data);
        setLookRules(true);
      }
    });
  }

  //已发布任务  查看已选专家
  function viewExperts(record){
    selectExpertList({containerId: record.id, containerType: 2, pageSize: 10000, curPage: 1,}).then(response=>{
      if(response && response.message === "success" && Array.isArray(response.data.rows)){
        let index = 1;
        for (const item of response.data.rows) {
          item.reviewAreas = `${item.reviewAreaOne} ${item.reviewAreaTwo ? `、${item.reviewAreaTwo}`:''} ${item.reviewAreaThree ? `、${item.reviewAreaThree}`:''}`;
          item.index = (index++) + (curPage > 1 ? (curPage - 1) * 10 : 0);
        }
        setSelectedExperts(response.data.rows);
        setLookExperts(true);
      }
    });
  }

  // 修改竞赛是否加入专家评审流程
  function changeExpertReviewStatus(expertReviewStatus, taskId) {
    updateCompetitionReview({id: taskId, is_expert_audit: expertReviewStatus==1}).then(res => {
      if (res && res.message === '更新成功') {
        showNotification('操作成功!');
        setReload(Math.random());
      } else {
        showNotification('操作失败');
      }
    })
  }

  // 修改路由,跳转到第几页
  function updateUrl(page){
    setCurPage(page);
    window.location.href=`/managements/expert/competition/#page=${page}`;
  }

  function hashDate(hash) {
    return parseInt(hash.split("&")[0].substring(hash.split("&")[0].indexOf("=")+1));
  }

  //获取竞赛任务列表
  useEffect(()=>{
    setLoading(true);
    const params = {
      curPage,
      pageSize: 10,
      isExpertAudit: expertReview
    }
    getCompetitionList(params).then(response=>{
      if(response && response.message === "success"){
        response.data.map((item, i)=>{
          item.index = ++i;
          item.start_time = item.start_time.replace('T', ' ').substring(0,16);
          item.end_time = item.end_time.replace('T', ' ').substring(0,16);
        })
        setCompetitionList(response.data || []);
        setTotal(response.total);
      }
    }).finally(()=>{
      setLoading(false);
    })
  }, [curPage, expertReview, reload])

  //监听lookRules,lookExperts,pulicReview的变化，弹框
  useEffect(()=>{
    //评审规则
    lookRules && rules && Modal.info({
      className: 'publishReview',
      title: "评审规则",
      content:
        <React.Fragment>
          <div>{rules && rules.rule}</div>
          <p>评分标准</p>
          <div>
            {rules.criterias.map(item=>{return <p key={Math.random()}>{item}</p>})}
          </div>
          <p>评审时间</p>
          <div>{rules.reviewData}</div>
        </React.Fragment>
      ,
    });
    lookRules && setLookRules(false);

    //已选取评审专家
    lookExperts && selectedExperts && Modal.info({
      className: 'publishReview',
      title: "已选取评审专家",
      content:
        <PaginationTable
        dataSource={selectedExperts}
        columns={columnsExperts}
        scroll={{ y: 395 }}/>,
    });
    lookExperts && setLookExperts(false);

    //发布评审任务
    pulicReview && rules && selectedExperts && Modal.confirm({
      className: 'publishReview',
      title: "发布评审任务",
      centered: true,
      content:
        <React.Fragment>
          <div className='tip'>
            <i className='iconfont icon-erciqueren_icon'></i>
            <span className='publicTitle'>确定发布此评审任务？确定发布后评审规则与评审专家信息将无法重新编辑</span>
          </div>
          <p>评审规则</p>
          <div>{rules && rules.rule}</div>
          <p>评分标准</p>
          <div>
            {rules.criterias.map(item=>{return <p key={Math.random()}>{item}</p>})}
          </div>
          <p>评审时间</p>
          <div>{rules.reviewData}</div>
          <p>已选取评审专家</p>
          <PaginationTable
            dataSource={selectedExperts}
            columns={columnsExperts}
            scroll={{ y: 230 }}/>
        </React.Fragment>
      ,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        publishExpertsAndRules(publicTaskId, 2).then(response=>{
          if(response && response.message==="发布成功"){
            setReload(Math.random());
          }
        })
      },
    });
    pulicReview && setPublicReview(false);
  },[lookRules,lookExperts,pulicReview])

  //监听hash路由的变化，由此控制页数
  useEffect(()=>{
    setCurPage(hashDate(hash) || 1);
  },[hash])
  
  return(
    <div className="centerbox competitionList">
      <PaginationTable
        loading={loading}
        dataSource={competitionList}
        columns={columns}
        total={total}
        setCurPage={(page)=>{updateUrl(page)}}
        current={curPage}
      />
    </div>
  )
}
export default Competition;