import React, { useState, useCallback, useMemo, useEffect } from "react";
import { Tabs, Button, Form, InputNumber, Modal, Tooltip, } from 'antd';
import { Link } from "react-router-dom";
import Paginationtable from "../../../components/paginationTable";
import { Info, Confirm } from '../../../components/ModalFun';
import WordsInput from 'military/expert/components/wordsInput';
import { getScoringDetails, initScoringDetails, getRules, updateScoringDetails, getCompetition } from "../../api";
import { readyCheckPapers } from "../../../task/api";
import { httpUrl, main_web_site_url } from '../../fetch';

import './index.scss';
import '../../index.scss';
const { TabPane } = Tabs;

function ReviewTasks({ showNotification, match, history, current_user }) {
  const containerId = match.params.containerId;
  const containerType = match.params.containerType;

  // 主table参数
  const [reload, setReload] = useState();
  const [loading, setLoading] = useState(false);
  const [dataList, setDataList] = useState([]);

  const [taskId, setTaskId] = useState();
  const [competitionId, setCompetitionId] = useState();

  // 评分规则
  const [rules, setRules] = useState({});

  // 模态框
  const [visible, setVisible] = useState(false);
  const [activeIndex, setActiveIndex] = useState(false);
  const [comments, setComments] = useState();

  // 按钮禁止提交 
  const [disabled, setDisabled] = useState(false);

  // 通用列
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 50,
      render: (text, record, index) => {
        return index + 1
      }
    },
    {
      title: '投稿详情',
      dataIndex: 'opsContent',
      key: 'opsContent',
      className: 'text-tooltip',
      render: (text, record, index) => {
        return <Tooltip overlayClassName="expert-tooltip" title={text} placement="top">{text}</Tooltip>
      }
    },
    {
      title: '附件下载',
      dataIndex: 'opsFilesAttachments',
      key: 'opsFilesAttachments',
      className: 'text-tooltip',
      render: (text, record) => {
        return text && text.map(item => {
          return <Tooltip key={item.id} overlayClassName="expert-tooltip" title={item.fileName} placement="top">
            <p className="link" onClick={() => { downFile(item) }}>{item.fileName}</p>
          </Tooltip>
        })
      }
    },

    {
      title: '平均分',
      dataIndex: 'gradesAverage',
      key: 'gradesAverage',
      width: 70,
    },
    {
      title: '评审意见',
      dataIndex: 'comments',
      key: 'comments',
      width: 80,
      render: (text, record, index) => {
        return <Tooltip overlayClassName="expert-tooltip" title={text} placement="top">
          <a className="link" onClick={() => { writeComments(text, index, 'comments') }}>{record.status === 2 ? text ? '编辑' : '填写' : '查看'}意见</a>
        </Tooltip>

      }
    },
  ];

  // 评分列
  const gradesColumns = [{
    title: '评分一',
    dataIndex: 'gradesOne',
    key: 'gradesOne',
    render: (text, record, index) => {
      return <InputNumber min={0} max={100} value={text} precision={0} disabled={disabled}
        onChange={(value) => { editGrade(value, index, 'gradesOne') }}
      />
    }
  },
  {
    title: '评分二',
    dataIndex: 'gradesTwo',
    key: 'gradesTwo',
    render: (text, record, index) => {
      return <InputNumber min={0} max={100} value={text} precision={0} disabled={disabled}
        onChange={(value) => { editGrade(value, index, 'gradesTwo') }}
      />
    }
  },
  {
    title: '评分三',
    dataIndex: 'gradesThree',
    key: 'gradesThree',
    render: (text, record, index) => {
      return <InputNumber min={0} max={100} value={text} precision={0} disabled={disabled}
        onChange={(value) => { editGrade(value, index, 'gradesThree') }}
      />
    }
  },
  {
    title: '评分四',
    dataIndex: 'gradesFour',
    key: 'gradesFour',
    render: (text, record, index) => {
      return <InputNumber min={0} max={100} value={text} precision={0} disabled={disabled}
        onChange={(value) => { editGrade(value, index, 'gradesFour') }}
      />
    }
  },
  {
    title: '评分五',
    dataIndex: 'gradesFive',
    key: 'gradesFive',
    render: (text, record, index) => {
      return <InputNumber min={0} max={100} value={text} precision={0} disabled={disabled}
        onChange={(value) => { editGrade(value, index, 'gradesFive') }}
      />
    }
  }];

  let gradesNum = rules.criterias && rules.criterias.length;

  if (gradesNum) {
    let thisGradesColumns = gradesColumns.slice(0, gradesNum);
    columns.splice(3, 0, ...thisGradesColumns);
  }

  useEffect(() => {
    getRules({ containerId, containerType }).then(res => {
      if (res && res.message === "success") {
        setRules(res.data);
        if (res.data.status === 1 || res.data.status === 2) {
          setDisabled(true);
        }
      }
    });
  }, [])

  // 获取成果列表
  useEffect(() => {
    let params = {
      taskId,
      checkStatus: '1',
      pageSize: 10000,
      curPage: 1,
      status: '',
      parentId: 0,
    }
    // 没有数据才能去查成果，并展示数据
    !dataList.length && taskId && current_user.expertId && readyCheckPapers(params).then(data => {
      let dataArr = [];
      if (data && Array.isArray(data.rows)) {
        for (const item of data.rows) {
          dataArr.push({
            comments: "",
            expertId: current_user.expertId,
            gradesAverage: '',
            gradesFive: '',
            gradesFour: '',
            gradesOne: '',
            gradesThree: '',
            gradesTwo: '',
            opsContent: item.paperDetail && item.paperDetail.content,
            opsFiles: item.paperDetail && item.paperDetail.files,
            opsFilesAttachments: item.paperDetail && item.paperDetail.busiAttachments,
            opsId: item.id,
            opsParentId: containerId,
            opsParentType: containerType,
            opsType: containerType,
            status: 2
          });
        }
      }
      setDataList(dataArr);
      disabled && setLoading(false);
      !disabled && dataArr.length && rules && initScoringDetails(dataArr).then(res => {
        if (res) {
          setReload(Math.random());
          setLoading(false);
        }
      });
    });
  }, [taskId, disabled, current_user.expertId]);

  // 获取竞赛作品列表
  useEffect(() => {
    // 没有数据才能去查作品列表，并展示数据
    !dataList.length && competitionId && current_user.expertId && getCompetition(competitionId).then(res => {
      let dataArr = [];
      if (res && Array.isArray(res.data)) {
        for (const item of res.data) {
          dataArr.push({
            comments: "",
            expertId: current_user.expertId,
            gradesAverage: '',
            gradesFive: '',
            gradesFour: '',
            gradesOne: '',
            gradesThree: '',
            gradesTwo: '',
            opsContent: item.works_remark,
            opsFiles: item.work_file.id,
            opsFilesAttachments: new Array(item.work_file),
            opsId: item.id,
            opsParentId: containerId,
            opsParentType: containerType,
            opsType: containerType,
            status: 2,
            competitionTeamName: item.name
          });
        }
      }
      setDataList(dataArr);
      !dataArr.length && setLoading(false);
      disabled && setLoading(false);
      !disabled && dataArr.length && rules && initScoringDetails(dataArr).then(res => {
        if (res) {
          setReload(Math.random());
          setLoading(false);
        }
      });
    });
  }, [competitionId, disabled, current_user.expertId]);


  function downFile(item) {
    if (containerType == 1) {
      let url = httpUrl + '/busiAttachments/download/' + item.id;
      window.open(url);
    } else {
      let url = main_web_site_url + `/attachments/send_file/${item.id}?disposition=attachment`;
      window.open(url);
    }
  }

  function editGrade(value, index, dataIndex) {
    let dataListNew = dataList.slice();
    dataListNew[index][dataIndex] = value;
    // 计算平均分
    if (gradesNum) {
      let gradesArr = [];
      let item = dataListNew[index];
      typeof item.gradesOne === 'number' && gradesArr.push(item.gradesOne);
      typeof item.gradesTwo === 'number' && gradesArr.push(item.gradesTwo);
      typeof item.gradesThree === 'number' && gradesArr.push(item.gradesThree);
      typeof item.gradesFour === 'number' && gradesArr.push(item.gradesFour);
      typeof item.gradesFive === 'number' && gradesArr.push(item.gradesFive);
      if (gradesArr.length === gradesNum) {
        const sum = gradesArr.reduce((previousValue, currentValue) => { return previousValue + currentValue }, 0);
        const ave = (sum / gradesNum).toFixed(2);
        dataListNew[index].gradesAverage = ave > 100 ? 100 : ave;
      } else {
        dataListNew[index].gradesAverage = '';
      }
    }

    setDataList(dataListNew);
  }

  // 获取评分列表
  useEffect(() => {
    setLoading(true);
    let params = {
      containerId,
      containerType,
      expertId: current_user.expertId,
    };
    current_user.expertId && getScoringDetails(params).then(res => {
      if (res.data && res.data.length) {
        setDataList(res.data);
        setLoading(false);
        if (res.data[0].status === 1) {
          setDisabled(true);
        }
      } else {
        containerType == 1 ? setTaskId(containerId) : setCompetitionId(containerId);
      }
    });
  }, [reload, current_user.expertId]);


  function cancel() {
    history.go(-1);
  }

  function writeComments(text, index) {
    setVisible(true);
    setActiveIndex(index);
    setComments(text);
  }

  // 修改意见
  function commit() {
    if (disabled) {
      setVisible(false);
      return;
    }
    if (comments) {
      let data = dataList[activeIndex];
      let dataListNew = dataList.slice();
      data.comments = comments;
      updateScoringDetails([data]).then(res => {
        if (res && res.message) {
          if (res.message.indexOf("成功")) {
            showNotification("保存成功");
            dataListNew[activeIndex].comments = comments;
            setDataList(dataListNew);
            setVisible(false);
          } else {
            showNotification(res.message);
          }
        }
      })
    }
  }

  // 提交草稿
  function draft() {
    updateScoringDetails(dataList).then(res => dealCommitRes(res));
  }

  // 提交评审结果
  function commitGrades() {
    if (verify()) {
      Confirm({
        title: '提醒',
        okText: '确定提交',
        content: <div>
          <p>提交后将完成此次评审，无法继续修改评分与评审意见</p>
          <p>确定提交此次评审结果？</p>
        </div>,
        onOk: () => {
          let dataArr = dataList.slice();
          for (const item of dataArr) {
            item.status = 1;
          }
          updateScoringDetails(dataArr).then(res => dealCommitRes(res));
        }
      });
    }
  }

  //  提交前校验
  function verify() {
    let errorArr = [];
    let commentsError = [];
    let scoringArr = [];
    for (const [index, item] of dataList.entries()) {
      let gradesArr = [];
      typeof item.gradesOne === 'number' && gradesArr.push(item.gradesOne);
      typeof item.gradesTwo === 'number' && gradesArr.push(item.gradesTwo);
      typeof item.gradesThree === 'number' && gradesArr.push(item.gradesThree);
      typeof item.gradesFour === 'number' && gradesArr.push(item.gradesFour);
      typeof item.gradesFive === 'number' && gradesArr.push(item.gradesFive);
      if (gradesArr.length < gradesNum && gradesArr.length) {
        errorArr.push(index + 1);
      } else if (!item.comments && gradesArr.length) {
        commentsError.push(index + 1);
      } else if (gradesArr.length) {
        scoringArr.push(index);
      }
    }

    if (errorArr.length) {
      Info({
        title: '提醒',
        content: `第${errorArr.join('，')}行数据请填写完整`,
      });
      return;
    }

    if (commentsError.length) {
      Info({
        title: '提醒',
        content: `第${commentsError.join('，')}行数据请填写意见`,
      });
      return;
    }

    if (!scoringArr.length) {
      Info({
        title: '提醒',
        content: '请至少填写一行分数',
      });
      return;
    }

    return !errorArr.length && !commentsError.length;
  }

  function dealCommitRes(res) {
    if (res && res.message) {
      if (res.message.indexOf("成功")) {
        showNotification("保存成功");
        setReload(Math.random());
      } else {
        showNotification(res.message);
      }
    }
  }

  return (
    <div className='register_right task_detail'>
      <p className="task-head">
        {containerType == 1 ? '创客成果' : '竞赛作品'}评审
        <button className="back-button but41_border" onClick={() => { history.goBack() }}>返回上一页</button>
      </p>

      <Tabs defaultActiveKey="0" animated={false}>

        <TabPane tab="评审信息" key="0">
          <div className="task-rules">
            <div className="rules-box">
              <p className="rules-head">{containerType == 1 ? '任务信息' : '赛事信息'}</p>
              <div className="rules-content">
                <div className="rules-content-item">
                  <span className="font-w">{containerType == 1 ? '任务' : '赛事'}名称</span>
                  <span className="ml10">{rules.containerName}</span>
                </div>
                <div className="rules-content-item">
                  <span className="font-w">{containerType == 1 ? '任务' : '赛事'}链接</span>
                  {containerType == 1 && <Link className="taskLink ml10" target="_blank" to={`/task/taskDetail/${rules.containerId}`} >{`${window.location.origin}/task/taskDetail/${rules.containerId}`}</Link>}
                  {containerType == 2 && <a className="taskLink ml10" target="_blank" href={`${main_web_site_url}/competitions/${rules.containerIdentifier}/home`} >{`${main_web_site_url}/competitions/${rules.containerIdentifier}/home`}</a>}
                </div>
              </div>
            </div>

            <div className="rules-box">
              <p className="rules-head">评审规则</p>
              <div className="rules-content">{rules.rule}</div>
            </div>

            <div className="rules-box">
              <p className="rules-head">评分标准</p>
              <div className="rules-content">
                {rules.criterias && rules.criterias.map((item, index) => { return <p className="rules-content-item" key={index}>{item}</p> })}
              </div>
            </div>

            <div className="rules-box">
              <p className="rules-head">评审时间</p>
              <div className="rules-content-last">{rules.reviewData}</div>
            </div>
          </div>

        </TabPane>
        <TabPane tab="专家评分" key="1">
          <div>
            <div className="box"></div>
            <div className="warning">对单个作品评分时，需填写完整每个评分项及评审意见，请勿少填、漏填</div>
            <Paginationtable
              loading={loading}
              dataSource={dataList}
              columns={columns}
              pagination={false}
            />

            <div className="text-center">
              <Button className="mr10" type="primary" disabled={disabled} onClick={commitGrades}>提交评审结果</Button>
              <Button className="mr10" disabled={disabled} onClick={draft}>保存评审结果</Button>
              <Button className="butE3_border" onClick={cancel}>取消</Button>
            </div>
          </div>
        </TabPane>
      </Tabs>


      <Modal
        title="填写意见"
        visible={visible}
        onOk={commit}
        onCancel={() => { setVisible(false) }}
        className="form-edit-modal"
      >
        <Form.Item >
          <WordsInput
            value={comments}
            placeholder="请填写"
            autoSize={{ minRows: 6 }}
            className="applyText"
            maxLength={250}
            onChange={setComments}
            disabled={disabled}
          />
        </Form.Item>
      </Modal>
    </div>
  )
}
export default ReviewTasks;