/*
 * @Author: yuananting
 * @Date: 2021-07-28 14:56:52
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-09 11:13:14
 * @Description: 描述一下咯
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useEffect } from 'react';
import { Route, withRouter } from 'react-router-dom';
import { Tooltip, Checkbox, Dropdown, Radio, Button, Space, Badge } from 'antd';
import './TrainList.less';
import { XMTable, PageControl } from '@/components';
import User from '@/common/js/user';
import ENUM from '../../enum';

function TrainList(props) {
  const {
    query: { issueState, myAssist, current, size },
    totalCount,
    match,
  } = props;

  function renderMoreOperate(item) {
    return (
      <div className='live-course-more-menu'>
        <div className='operate__item'>取消发布</div>
        <div className='operate__item'>编辑</div>
        <div className='operate__item'>分享</div>
        <div className='operate__item'>审批作业</div>
        <div className='operate__item'>删除 </div>
      </div>
    );
  }

  function parseColumns() {
    const columns = [
      {
        title: '培训任务',
        key: 'taskName',
        dataIndex: 'taskName',
        width: '18%',
        fixed: 'left',
        render: (val, record) => {
          return (
            <div className='train-task-name'>
              <img className='train-cover' src={record.coverUrl || 'https://image.xiaomaiketang.com/xm/rEAetaTEh3.png'} alt='' />
              <Choose>
                <When condition={record.taskName?.length > 25}>
                  <Tooltip title={record.taskName}>
                    <div className='train-name'>{val}</div>
                  </Tooltip>
                </When>
                <Otherwise>
                  <div className='train-name'>{val}</div>
                </Otherwise>
              </Choose>
            </div>
          );
        },
      },
      {
        title: '任务状态',
        width: '12%',
        key: 'taskState',
        dataIndex: 'taskState',
        render: (val) => {
          return (
            <div className='task-state'>
              <span className='status-point' style={{ backgroundColor: ENUM.trainStatus[val || 'UN_START'].color }}></span>
              <span>{ENUM.trainStatus[val || 'UN_START'].text}</span>
            </div>
          );
        },
      },
      {
        title: '任务数',
        width: '8%',
        key: 'contentNum',
        dataIndex: 'contentNum',
        render: (val, record) => {
          return <span>{val}</span>;
        },
      },
      {
        title: '学习人数',
        width: '10%',
        key: 'cultureCustomerNum',
        dataIndex: 'cultureCustomerNum',
        sorter: true,
        render: (val, record) => {
          return (
            <Tooltip
              title={
                <div>
                  <div>未完成：{record.startingCustomerNum}人</div>
                  <div>已完成：{record.finishCustomerNum}人</div>
                  <div>已逾期：{record.overdueCustomerNum}人</div>
                </div>
              }>
              <span style={{ color: '#2966FF' }}>{val}</span>
            </Tooltip>
          );
        },
      },
      {
        title: (
          <span>
            完成率
            <Tooltip title='完成培训任务的人数/学习总人数'>
              <i
                className='icon iconfont'
                style={{
                  marginLeft: '4px',
                  cursor: 'pointer',
                  color: '#bfbfbf',
                  fontSize: '14px',
                  fontWeight: 'normal',
                }}>
                &#xe61d;
              </i>
            </Tooltip>
          </span>
        ),
        width: '10%',
        key: 'finishPercent',
        dataIndex: 'finishPercent',
        sorter: true,
        render: (val) => {
          return <span>{val}%</span>;
        },
      },
      {
        title: '培训时间',
        width: '14%',
        key: 'trainTime',
        dataIndex: 'trainTime',
        render: (val, record) => {
          if (record.timeType === 'FOREVER') {
            return <span>不限时</span>;
          }
          return (
            <span style={{ whiteSpace: 'nowrap' }}>
              {window.formatDate('YYYY-MM-DD H:i', record.startTime)}~{window.formatDate('YYYY-MM-DD H:i', record.endTime)}
            </span>
          );
        },
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: '12%',
        render: (val) => {
          return <span>{val}</span>;
        },
      },
      {
        title: '创建时间',
        width: '12%',
        key: 'created',
        dataIndex: 'created',
        sorter: true,
        render: (val) => {
          return <span style={{ whiteSpace: 'nowrap' }}>{window.formatDate('YYYY-MM-DD H:i', val)}</span>;
        },
      },
      {
        title: '更新时间',
        width: '12%',
        key: 'updated',
        dataIndex: 'updated',
        sorter: true,
        render: (val) => {
          return <span style={{ whiteSpace: 'nowrap' }}>{window.formatDate('YYYY-MM-DD H:i', val)}</span>;
        },
      },

      {
        title: '操作',
        key: 'operate',
        dataIndex: 'operate',
        fixed: 'right',
        width: '16%',
        render: (val, record) => {
          return (
            <div className='operate'>
              <div
                className='operate__item'
                onClick={() => {
                  props.history.push(`${match.path}/data?planId=${record.planId}`);
                }}>
                数据
              </div>
              <span className='split'> | </span>
              <div
                className='operate__item'
                onClick={() => {
                  handleShowShareModal(record);
                }}>
                指派
              </div>
              <span className='split'> | </span>
              <Dropdown overlay={renderMoreOperate(record)}>
                <span className='more-operate'>
                  <span className='more-text'>更多</span>
                  <span className='iconfont icon' style={{ color: '#2966FF' }}>
                    &#xe824;
                  </span>
                </span>
              </Dropdown>
            </div>
          );
        },
      },
    ];
    return columns;
  }

  // 改变搜索条件(状态 协同与否)
  function handleChangeQuery(field, value) {
    const _query = {
      ...props.query,
      [field]: value,
    };
    props.onChange(_query);
  }

  function handleChangeTable(pagination, filters, sorter) {
    const { columnKey, order } = sorter;
    const { query } = props;
    let _columnKey;
    let _order;

    if (columnKey == 'cultureCustomerNum' && order === 'ascend') {
      // 按学习人数升序排序
      _columnKey = 'CUSTOMER_NUM';
      _order = 'SORT_ASC';
    }
    if (columnKey == 'cultureCustomerNum' && order === 'descend') {
      // 按学习人数降序排序
      _columnKey = 'CUSTOMER_NUM';
      _order = 'SORT_DESC';
    }

    if (columnKey == 'finishPercent' && order === 'ascend') {
      // 按完成率升序排序
      _columnKey = 'FINISH_PERCENT';
      _order = 'SORT_ASC';
    }
    if (columnKey == 'finishPercent' && order === 'descend') {
      // 按完成率降序排序
      _columnKey = 'FINISH_PERCENT';
      _order = 'SORT_DESC';
    }

    if (columnKey === 'created' && order === 'ascend') {
      // 按创建时间升序排序
      _columnKey = 'CREATED';
      _order = 'SORT_ASC';
    }
    if (columnKey === 'created' && order === 'descend') {
      // 按创建时间降序排序
      _columnKey = 'CREATED';
      _order = 'SORT_DESC';
    }

    if (columnKey === 'updated' && order === 'ascend') {
      // 按更新时间升序排序
      _columnKey = 'UPDATED';
      _order = 'SORT_ASC';
    }
    if (columnKey === 'updated' && order === 'descend') {
      // 按更新时间降序排序
      _columnKey = 'UPDATED';
      _order = 'SORT_DESC';
    }

    const _query = {
      ...query,
      sortMap: {},
    };
    _query.sortMap[_columnKey] = _order;
    props.onChange(_query);
  }

  function handleCreatePlan() {
    window.RCHistory.push({
      pathname: '/create-train-task?type=add',
    });
  }

  return (
    <div className='train-list-page'>
      <div className='header-line'>
        {(User.getUserRole() === 'CloudManager' || User.getUserRole() === 'StoreManager') && (
          <Button type='primary' className='mr12' onClick={handleCreatePlan}>
            新建培训任务
          </Button>
        )}
        <Space size={16}>
          <Radio.Group
            size='middle'
            value={issueState}
            onChange={(e) => {
              handleChangeQuery('issueState', e.target.value);
            }}>
            <Radio.Button value='ALL'>全部(2)</Radio.Button>
            <Radio.Button value='YES'>已发布(2)</Radio.Button>
            <Radio.Button value='NO'>未发布(10)</Radio.Button>
          </Radio.Group>
          <Checkbox style={{ lineHeight: '32px' }} value={myAssist} onChange={(e) => handleChangeQuery('myAssist', e.target.checked)}>
            只看我协同的 ({10})
          </Checkbox>
        </Space>
      </div>
      <div className='list-content'>
        <XMTable
          rowKey={(record) => record.id}
          showSorterTooltip={false}
          dataSource={props.trainListData}
          columns={parseColumns()}
          pagination={false}
          onChange={handleChangeTable}
          bordered
          size='middle'
          scroll={{ x: 1600 }}
          className='train-list-table'
          renderEmpty={{
            description: <span style={{ display: 'block', paddingBottom: 24 }}>暂无数据</span>,
          }}
        />
        <div className='box-footer'>
          <PageControl
            current={current - 1}
            pageSize={size}
            total={totalCount}
            toPage={(page) => {
              handleChangeQuery('current', page + 1);
            }}
            showSizeChanger={false}
          />
        </div>
      </div>
    </div>
  );
}

export default withRouter(TrainList);
