/*
 * @Author: yuananting
 * @Date: 2021-07-28 14:56:52
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-18 12:37:50
 * @Description: 描述一下咯
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState } from 'react';
import { withRouter } from 'react-router-dom';
import { Tooltip, Checkbox, Dropdown, Radio, Button, Space, Modal, message } from 'antd';
import './TrainList.less';
import { XMTable, PageControl } from '@/components';
import User from '@/common/js/user';
import ENUM from '../../enum';
import TaskCenterService from '@/domains/task-center-domain/TaskCenterService';
import ShareTrainTaskModal from '../modal/ShareTrainTaskModal';
import ChooseAssignorModal from '../modal/ChooseAssignorModal';
import { LIVE_SHARE } from '@/domains/course-domain/constants';
import Bus from '@/core/bus';

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

  const [shareTrainTaskModal, setShareTrainTaskModal] = useState(null);
  const [chooseAssignorModal, setChooseAssignorModal] = useState(null);

  // 发布或取消发布培训任务
  function updateIssueStateTrain(taskId, state) {
    Modal.confirm({
      title: '提示',
      content:
        state === 'YES' ? '发布后，被指派学员将任务列表中看到该任务，确定要发布？' : '取消发布后，任务对学员暂不可见，可能会影响正在学习学员，确定要取消？',
      okText: '确定',
      cancelText: '取消',
      icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
      onOk: () => {
        TaskCenterService.updateIssueStateTraining({
          taskId,
          issueState: state,
        }).then((res) => {
          message.success(state === 'YES' ? '发布成功' : '取消发布成功');
          Bus.trigger('getTrainingTaskPage', { issueState, myAssist });
          Bus.trigger('getStoreTaskNum');
        });
      },
    });
  }

  // 删除培训任务
  function deleteTrainTask(taskId) {
    Modal.confirm({
      title: '你确定要删除吗？',
      content: '删除后，此培训任务的用户将无法继续学习，所有学习数据将同步删除不可恢复',
      okText: '确定',
      cancelText: '取消',
      icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
      onOk: () => {
        TaskCenterService.deleteTrainingTask({
          taskId,
        }).then((res) => {
          message.success('删除成功');
          Bus.trigger('getTrainingTaskPage', { issueState, myAssist });
          Bus.trigger('getStoreTaskNum');
        });
      },
    });
  }

  // 编辑培训任务-跳转新建/编辑页
  function editTrainingTask(item) {
    window.RCHistory.push({
      pathname: `/create-train-task?type=edit&taskId=${item.taskId}&taskState=${item.taskState}&timeType=${item.timeType}`,
    });
  }

  // 显示指派弹窗
  function handleShowAssignModal(item) {
    let _assignList = [];
    if (item.assignList?.length > 0) {
      _assignList = item.assignList.map((childItem) => {
        childItem.checkedId = childItem.assignId;
        childItem.checkedName = childItem.assignName;
        childItem.checkedType = childItem.assignType;
        return childItem;
      });
    }

    const chooseAssignorModal = (
      <ChooseAssignorModal
        currentAssignorList={_assignList}
        visible={true}
        onClose={() => {
          setChooseAssignorModal(null);
        }}
        onConfirm={(data) => {
          confirmUpdatedAssignor(data, item.taskId);
        }}
      />
    );
    setChooseAssignorModal(chooseAssignorModal);
  }

  // 显示分享弹窗
  function handleShowShareModal(item) {
    const htmlUrl = `${LIVE_SHARE}training_task_detail/${item.taskId}?id=${User.getStoreId()}&storeUserId=${User.getStoreUserId()}`;
    const longUrl = htmlUrl;
    const shareData = { ...item, longUrl };
    const shareTrainTaskModal = (
      <ShareTrainTaskModal
        data={shareData}
        type='liveClass'
        close={() => {
          setShareTrainTaskModal(null);
        }}
      />
    );
    setShareTrainTaskModal(shareTrainTaskModal);
  }

  // 确定指派人员
  function confirmUpdatedAssignor(data, id) {
    const assignList = data.map((item) => {
      return {
        assignType: item.checkedType,
        assignId: item.checkedId,
      };
    });

    const params = {
      assignList,
      id,
    };

    if (assignList.length === 0) {
      return message.warning('指派列表不能为空');
    }
    TaskCenterService.updateTrainingTaskAssign(params).then((res) => {
      message.success('指派成功');
      Bus.trigger('getTrainingTaskPage', { issueState, myAssist });
      setChooseAssignorModal(null);
    });
  }

  function renderMoreOperate(item) {
    const isUnableIssue = item.issueState === 'YES'; // 已发布
    const isUnableAbleEdit = item.issueState === 'YES' || item.taskState === 'FINISH'; // 已发布或已结束
    const isUnableShare = item.issueState === 'NO' || item.taskState === 'FINISH'; //未发布或已结束
    return (
      <div className='train-list-more-menu'>
        {!isUnableIssue && (
          <div className='operate__item' onClick={() => updateIssueStateTrain(item.taskId, 'YES')}>
            发布
          </div>
        )}
        {isUnableIssue && (
          <div className='operate__item' onClick={() => updateIssueStateTrain(item.taskId, 'NO')}>
            取消发布
          </div>
        )}
        <div
          className={`operate__item ${isUnableAbleEdit && 'disabled'} `}
          onClick={() => {
            editTrainingTask(item);
          }}>
          编辑
        </div>
        <div className={`operate__item ${isUnableShare && 'disabled'} `} onClick={() => handleShowShareModal(item)}>
          分享
        </div>
        {/* <div className='operate__item'>审批作业</div> */}
        <div
          className='operate__item'
          onClick={() => {
            deleteTrainTask(item.taskId);
          }}>
          删除
        </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: '12%',
        key: 'cultureCustomerNum',
        dataIndex: 'cultureCustomerNum',
        render: (val, record) => {
          return (
            <Tooltip
              title={
                <div>
                  <div>未完成：{record.startingCustomerNum}人</div>
                  <div>已完成：{record.finishCustomerNum}人</div>
                  <div>已逾期：{record.overdueCustomerNum}人</div>
                </div>
              }>
              <span
                style={{ color: '#2966FF', cursor: 'pointer' }}
                onClick={() => {
                  props.history.push(`${match.path}/data/${record.taskId}`);
                }}>
                {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: '11.5%',
        key: 'finishPercent',
        dataIndex: 'finishPercent',
        render: (val) => {
          return <span>{val}%</span>;
        },
      },
      {
        title: '培训时间',
        width: '17%',
        key: 'trainTime',
        dataIndex: 'trainTime',
        render: (val, record) => {
          if (record.timeType === 'FOREVER') {
            return <span>不限时</span>;
          }
          return (
            <span>
              {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: '14%',
        key: 'created',
        dataIndex: 'created',
        sorter: true,
        render: (val) => {
          return <span style={{ whiteSpace: 'nowrap' }}>{window.formatDate('YYYY-MM-DD H:i', val)}</span>;
        },
      },
      {
        title: '更新时间',
        width: '14%',
        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: '18%',
        render: (val, record) => {
          return (
            <div className='operate'>
              <div
                className='operate__item'
                onClick={() => {
                  props.history.push(`${match.path}/data/${record.taskId}`);
                }}>
                数据
              </div>
              <span className='split'> | </span>
              <div
                className={`operate__item ${record.taskState === 'FINISH' && 'disabled'} `}
                onClick={() => {
                  handleShowAssignModal(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,
      current: 1,
    };
    props.onChange(_query);
  }

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

    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: {
        UPDATED: 'SORT_DESC',
      },
    };
    _query.sortMap[_columnKey] = _order;
    props.onChange(_query);
  }

  function handleCreateTask() {
    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={handleCreateTask}>
            新建培训任务
          </Button>
        )}
        <Space size={16}>
          <Radio.Group
            size='middle'
            value={issueState}
            onChange={(e) => {
              handleChangeQuery('issueState', e.target.value);
            }}>
            <Radio.Button value='ALL'>全部({props.storeTaskNum.allNum})</Radio.Button>
            <Radio.Button value='YES'>已发布({props.storeTaskNum.issueNum})</Radio.Button>
            <Radio.Button value='NO'>未发布({props.storeTaskNum.notIssueNum})</Radio.Button>
          </Radio.Group>
          <Checkbox style={{ lineHeight: '32px' }} value={myAssist} onChange={(e) => handleChangeQuery('myAssist', e.target.checked)}>
            只看我协同的 ({props.storeTaskNum.myAssistNum})
          </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: 1400 }}
          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) => {
              const _query = {
                ...props.query,
                current: page + 1,
              };
              props.onChange(_query);
            }}
            showSizeChanger={false}
          />
        </div>
      </div>
      {shareTrainTaskModal}
      {chooseAssignorModal}
    </div>
  );
}

export default withRouter(TrainList);
