import React, { Fragment, useEffect, useState } from 'react';
import { Checkbox, Input, message, Modal, Table, Tooltip } from 'antd';
import './index.scss';
import { cancelTaskApply, taskList } from '../../api';
import ProjectDetail from '../component/projectDetail';
import bgPng from "../../img/bgPng.png";
const { Search } = Input;

// 课题列表
function TaskList({applyTaskId, setStudentInfoReset, current_user, showLoginDialog, isStudentApplyDate, studentApplyEnd}) {
  const [visible, setVisible] = useState(false);
  const [deleteTaskId, setDeleteTaskId] = useState(undefined);
  // 输入搜索框
  const [keyword, setKeyword] = useState(undefined);
  const [data, setData] = useState([]);
  // table
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useState(20);
  const [loading, setLoading] = useState(false);
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  // 已报名
  const [apply, setApply] = useState(false);

  const columns = [
    { title: '序号', dataIndex: 'index', align: 'center', className:"taskTableColumns", width: '6%', render: (text, item, index) => <span>{(current-1)*pageSize+index + 1}</span> },
    { title: '课题名称', dataIndex: 'taskName', className:"taskTableColumns taskName", width: '28%', ellipsis: true, render: (text, item) => <Tooltip title={text} placement="topLeft"><span onClick={()=>{window.open(`/glcc/subjects/detail/${item.id}`)}}>{text}</span></Tooltip> },
    { title: '项目名称', dataIndex: 'projectName', className:"taskTableColumns", width: '28%', ellipsis: true, render: (text) => <Tooltip title={text} placement="topLeft">{text}</Tooltip> },
    { title: '课题奖金', dataIndex: 'taskReward', className:"taskTableColumns", ellipsis: true, width: `${isStudentApplyDate || studentApplyEnd ? '15%' : ''}`, render: (text) => <Tooltip title={text} placement="topLeft"><span>{text}</span></Tooltip> },
    {
      title: '操作', dataIndex: 'action', align: 'center', className:"actionColumns taskTableColumns", render: ((text, item, index) => {
        return (
          <div className='actionBox'>
            {(isStudentApplyDate || studentApplyEnd) && (applyTaskId && Object.keys(applyTaskId).includes(item.id.toString()) ? <Fragment>
              <span onClick={()=>{window.location.href=`/glcc/student/apply/${item.id}`}}><i className='iconfont icon-baomingxiangqingicon mr5'></i>报名详情</span>
              <Tooltip title={"取消申请"}><i className='iconfont icon-shanchuicon3 ml20 cancelApply' onClick={()=>{setDeleteTaskId(item.id);setVisible(true)}}></i></Tooltip>
            </Fragment>:isStudentApplyDate && <Fragment>
              <span onClick={()=>{applyTask(item.id)}}><i className='iconfont icon-shenqingketiicon applyTask mr5'></i><span className='applyTask'>申请课题</span></span></Fragment>)}
          </div>
        )
      })
    },
  ]

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

  const expandRow = (record) => {
    return <ProjectDetail detail={null} projectId={record.regId} applyTaskId={applyTaskId} current_user={current_user} showLoginDialog={showLoginDialog} isStudentApplyDate={isStudentApplyDate} studentApplyEnd={studentApplyEnd}/>
  }

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

  // 申请课题按钮点击函数
  function applyTask(id){
    // 判断用户是否已经登录
    if(current_user && current_user.login){
      // 判断用户是否已经报名两个课题
      if(applyTaskId && Object.keys(applyTaskId).length >= 2){
        message.error('最多只能同时报名两个课题');
      }else{
        // 跳转到学生报名页
        window.location.href=`/glcc/student/apply/${id}`;
      }
    }else{
      showLoginDialog();
    }
  }

  // 取消课题按钮点击函数
  function cancelApply(){
    const id = [];
    id.push(applyTaskId[deleteTaskId]);
    const params = {
      ids: id
    }
    cancelTaskApply(params).then(response=>{
      if(response && response.message === "success"){
        setVisible(false);
        setStudentInfoReset(Math.random());
        message.success('取消成功');
      }
    })
  }

  // 改变pagesize
  function onShowSizeChange(current, pageSize){
    window.scrollTo(0, 0);
    setCurrent(1);
    setPageSize(pageSize);
  }

  // 切换页数
  function changePage(page, pageSize){
    window.scrollTo(0, 0);
    setCurrent(page);
  }

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

  useEffect(() => {
    setExpandedRowKeys([]);
    setLoading(true);
    const params = {
      curPage: current,
      keyword,
      pageSize,
      userId: apply ? current_user.user_id : ''
    }
    taskList(params).then(response => {
      if (response && response.message === "success") {
        // 将已报名task任务置顶
        const ids = Object.keys(applyTaskId);
        const data = response.data.rows;
        data.map((item, index)=>{
          ids.includes(item.id.toString()) && toFirst(data, index);
        })
        setData(data);
        setTotal(response.data.total);
      }
      setLoading(false);
    })
  }, [keyword, current, pageSize, applyTaskId, apply])

  return (
    <div className="taskList listBox">
      <div className="list">
        <div className='search task'>
          {current_user && current_user.login ? <Checkbox onChange={(e)=>{setCurrent(1);setApply(e.target.checked)}}>已报名</Checkbox> : <div></div>}
          <Search className='taskSearch' placeholder='请输入课题/项目名称进行搜索' allowClear enterButton onSearch={(value) => { setCurrent(1); setKeyword(value) }} />
          <div></div>
        </div>
        <Table
          loading={loading}
          columns={columns}
          dataSource={data}
          expandedRowRender={expandRow}
          expandIconColumnIndex={4}
          expandIconAsCell={false}
          expandIcon={customExpandIcon}
          rowKey={'id'}
          expandedRowKeys={expandedRowKeys}
          onExpand={onExpand}
          pagination={{current: current, pageSize: pageSize, total: total, showSizeChanger: true, onShowSizeChange:onShowSizeChange, showQuickJumper: true, onChange: changePage}}
        />
      </div>
      <img src={bgPng} alt='' className='bgPng3'/>
      <img src={bgPng} alt='' className='bgPng4'/>
      <Modal
        okText="确认删除"
        okType='default'
        title="删除"
        visible={visible}
        onCancel={()=>{setVisible(false)}}
        onOk={cancelApply}
        wrapClassName='cancelApplyTask'
      >
        <div className='tilTask mt20'><span className='carefulIcon'>!</span>取消申请即删除本次报名记录，确定取消？</div>
        <p className='tipTask'>此操作将永久删除该报名记录，请进行确认以防数据的丢失</p>
      </Modal>
    </div>
  )
}
export default TaskList;