import React, { useEffect, useState } from 'react';
import { Modal, Table, Tooltip, Breadcrumb, Tabs, Button } from 'antd';
import { Link } from 'react-router-dom';
import moment from 'moment';
import './index.scss';
import { auditPassTask, getStudentList, getAuditList, hasAuditRole } from '../api';
import {httpUrl} from '../fetch';
const { TabPane } = Tabs;



function Check({ current_user, showNotification, history }) {

  // 输入搜索框
  const [data, setData] = useState([]);
  const [visible, setVisible] = useState(false);
  const [picture, setPicture] = useState('');
  const [reload, setReload] = useState();
  const [loading, setLoading] = useState(false);
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);

  const [taskList, setTaskList] = useState([]);
  const [taskId, setTaskId] = useState();
  const [havePass, setHavePass] = useState(false);

  const disabledCheck =  new Date().getTime() > new Date('2022/07/01 00:00:00').getTime();

  const columns = [
    {
      title: '学生姓名',
      className: "taskTableColumns",
      dataIndex: 'studentName',
      key: 'studentName',
      width: '12%',
      ellipsis: true,
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span>{text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '报名时间',
      key: 'createdOn',
      dataIndex: 'createdOn',
      className: "taskTableColumns",
      width: '10%',
      render: (text, record) => {
        return (
          text && moment(text).format('YYYY-MM-DD')
        );
      },
    },
    {
      title: '所在高校',
      key: 'school',
      dataIndex: 'school',
      className: "taskTableColumns",
      width: '14%',
      ellipsis: true,
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span>{text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '联系电话',
      key: 'phone',
      dataIndex: 'phone',
      className: "taskTableColumns",
      width: '12%',
      ellipsis: true,
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span>{text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '邮箱地址',
      key: 'mail',
      dataIndex: 'mail',
      className: "taskTableColumns",
      width: '15%',
      ellipsis: true,
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span>{text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '申请自荐书',
      key: 'memo',
      dataIndex: 'memo',
      className: 'taskTableColumns',
      ellipsis: true,
      width: '18%',
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span>{text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '',
      key: 'more',
      dataIndex: 'more',
      className: 'taskTableColumns moreColumns',
      width: '11%',
    },
    {
      title: '操作',
      dataIndex: 'passStatus',
      align: 'center',
      width: '11%',
      className: "actionColumns taskTableColumns",
      render: ((text, record, index) => {
        return (
          <div className='actionBox'>
            {/* 学生已入选并且锁定 */}
            {record.locked && !record.used && <Tooltip title="恭喜，该学生已成功入选您的课题!"><Button disabled type="primary" className='greenColBor'>已入选</Button></Tooltip>}
            {/* 学生已经被其他导师锁定 */}
            {record.locked && record.used && <Tooltip title="此学生已入选其他课题"><Button disabled type="primary" className='redColBor'>已被选</Button></Tooltip>}
            {/* 学生未被锁定 */}
            {!record.locked && !record.used && (text ? <Button disabled={disabledCheck} type="default" onClick={() => { checkStudent(record.id, 0) }}>撤销</Button> :
                <Button disabled={disabledCheck || havePass} type="primary" onClick={() => { checkStudent(record.id, 1) }}>通过</Button>)}
          </div>
        )
      })
    },
  ];

  useEffect(() => {
    if(new Date().getTime() > new Date('2022/07/01 0:0').getTime()){
      history.push('/403');
    }
    if (!current_user.user_id) {
      history.push('/403');
    }
    hasAuditRole({ userId: current_user.user_id }).then(res => {
      if (!(res && res.message == 'success' && res.data.hasRole)) {
        history.push('/403');
      }
    })
  }, [])


  useEffect(() => {
    getAuditList({ userId: current_user.user_id }).then(res => {
      if (res.message == 'success') {
        setTaskList(res.data.rows);
        res.data.rows.length && setTaskId(res.data.rows[0].id);
      } else {
        res && showNotification(res.message || '查询课题列表失败');
      }
    })
  }, [])

  function checkStudent(id, status) {
    auditPassTask({
      id,
      status,
    }).then(res => {
      if (res && res.message === 'success') {
        showNotification(status ? '已通过该学生课题申请' : '撤销成功')
        setReload(Math.random());
      } else {
        showNotification(res ? res.message : '操作失败');
      }
    })
  }

  // 数组元素置顶方法
  function toFirst(data, index){
    if(index != 0){
      data.unshift(data.splice(index,1)[0]);
    }
  }

  const customExpandIcon = (props) => {
    if (props.expanded) {
      return <a className='actionBox' style={{ marginRight: 8 }} onClick={e => {
        props.onExpand(props.record, e);
      }}>更多详情<i className="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu- font-12 ml5 down"></i></a>
    } else {
      return <a className='actionBox' style={{ marginRight: 8 }} onClick={e => {
        props.onExpand(props.record, e);
      }}>更多详情<i className="iconfont icon-jiantou9 font-12 ml5 down"></i></a>
    }
  }

  const expandRow = (record) => {
    return <div className="student-expand">
      <div className="info-line">
        {(record.grade || record.profession) && <div className="info-item">
          <span className="info-tit">所学专业</span>
          <span className="info-content">{record.grade} | {record.profession}</span>
        </div>}
        {record.location && <div className="info-item">
          <span className="info-tit">所在地区</span>
          <span className="info-content">{record.location}</span>
        </div>}
      </div>

      {record.memoAttachment && <div className="info-line">
        <div className="info-item">
          <span className="info-tit">自荐书附件</span>
          <i className='iconfont icon-lianjie3 font-14 color6 mr5'></i>
          <a
            className="link"
            href={
              `${httpUrl}/busiAttachments/download/${record.memoAttachment.id}`
            }
          >
            {record.memoAttachment.fileName}
          </a>
        </div>
      </div>}

      {record.proveAttachmentId && <div className="info-line">
        <div className="info-item">
          <span className="info-tit">学生证明</span>
          <img className="info-img"
            alt=''
            onClick={() => { setVisible(true); setPicture(record.proveAttachmentId) }}
            src={`${window.location.href.indexOf('test') > -1 ||
              window.location.href.indexOf('localhost') > -1
              ? 'https://testforgeplus.trustie.net'
              : ''
              }/api/attachments/${record.proveAttachmentId}`}
          ></img>
        </div>
      </div>}
    </div>
  }


  // 展开收起行回调
  function onExpand(expanded, record) {
    const keys = new Set(expandedRowKeys);
    if (expanded) {
      keys.add(record.id);
    } else {
      keys.delete(record.id);
    }
    setExpandedRowKeys(Array.from(keys));
  }


  useEffect(() => {
    setExpandedRowKeys([]);
    setLoading(true);
    const params = {
      curPage: 1,
      pageSize: 10000,
      keyword: '',
      taskId,
    }
    taskId && getStudentList(params).then(res => {
      if (res.data && Array.isArray(res.data.rows)) {
        const data = res.data.rows;
        // 已入选数据置顶
        data.map((item, index)=>{
          if(item.locked && !item.used){
            toFirst(data, index);
          }
        })
        setData(data);
        let isPass = res.data.rows.some((item) => { return (item.passStatus && !(item.locked&&item.used)) || (item.locked && !item.used) });
        setHavePass(isPass);
      }
      setLoading(false);
    })
  }, [taskId, reload])

  return (
    <div className="glcc-container glcc-check">
      <div className="glcc-main">
        <Breadcrumb className='glcc_breadcrumb font-16'>
          <Breadcrumb.Item><Link to="/glcc">开源夏令营</Link></Breadcrumb.Item>
          <Breadcrumb.Item style={{ color: '#202D40' }}>导师审核</Breadcrumb.Item>
        </Breadcrumb>
        <div className="head_introduce">
          <h4 className="head_tit">审核说明：</h4>
          <div className="head_content">1、欢迎进入导师审核页！各位导师可查看到您发布课题的全部学生报名信息</div>
          <div className="head_content">2、您可根据学生报名信息与学生进行邮箱或电话沟通了解学生详细情况，选择满意的学生</div>
          <div className="head_content">3、每个课题仅允许审核通过一个学生，在审核过程中，您可以随时调整各学生的审核状态，直到与学生匹配成功</div>
          {/* <div className="head_content">4、6月28日后，各导师可访问 <a href='/glcc/result'>https://www.gitlink.org.cn/glcc/result</a> 查询匹配结果（需使用导师账号登录）</div> */}
          <div className="head_content">4、请各位导师在7月1日前完成课题申请的审核，7月1日凌晨1点平台将根据各导师审核信息，正式公布各课题学生入选名单</div>
        </div>

        <Tabs className="task-tabs" onChange={(e) => { setTaskId(e) }} activeKey={taskId + ''}>
          {
            taskList.map((item, i) => {
              return <TabPane tab={`课题${i + 1}`} key={item.id} >
                <div className="task-title">{item.taskName}</div>
              </TabPane>
            })
          }
        </Tabs>

        <div className="taskList listBox">
          <div className='line'></div>
          <Table
            loading={loading}
            columns={columns}
            dataSource={data}
            expandedRowRender={expandRow}
            expandIconColumnIndex={6}
            expandIconAsCell={false}
            expandIcon={customExpandIcon}
            rowKey={'id'}
            expandedRowKeys={expandedRowKeys}
            onExpand={onExpand}
            pagination={false}
          />
        </div>

        <Modal
          visible={visible && picture}
          title="学生证明"
          onCancel={() => { setVisible(false) }}
          onOk={() => { setVisible(false) }}
          className="picture-modal"
          width={900}
          footer={null}
        >
          <img
            alt=''
            src={`${window.location.href.indexOf('test') > -1 ||
              window.location.href.indexOf('localhost') > -1
              ? 'https://testforgeplus.trustie.net'
              : ''
              }/api/attachments/${picture}`}
          ></img>
        </Modal>
      </div>
    </div>
  )
}
export default Check;