import React from 'react';
import { withRouter } from 'react-router-dom';
import { Modal, message, Tooltip } from 'antd';
import { PageControl, XMTable } from '@/components';
import college from '@/common/lottie/college';
import UserLearningDataFilter from './UserLearningDataFilter';
import PlanService from '@/domains/plan-domain/planService';
import UserLearnDetailModal from '../modal/UserLearnDetailModal';
import UnbundEmployeeModal from '../modal/UnbundEmployeeModal';
import User from '@/common/js/user';
import './UserLearningData.less';
const { confirm } = Modal;
const LearnState = {
  UN_PLAY: {
    text: '未开始',
  },
  UNDER_WAY: {
    text: '进行中',
  },
  FINISH: {
    text: '已完成',
  },
};

class UserLearningData extends React.Component {
  constructor(props) {
    super(props);
    const id = getParameterByName('id');
    this.state = {
      id,
      dataSource: [],
      size: 10,
      query: {
        current: 1,
      },
      totalCount: 0,
      userLearnDetailModalSHow: false,
      unbundEmployeeModalVisible: false,
    };
  }
  componentDidMount() {
    this.handleFetchDataList();
  }
  handleFetchDataList = (_query) => {
    const { query, size, id } = this.state;
    const params = {
      ...query,
      ..._query,
      size,
      planId: id,
      storeId: User.getStoreId(),
      storeUserId: User.getStoreUserId(),
    };
    this.setState({ query: params });
    PlanService.getPlanCustomerRecordPage(params).then((res) => {
      const { result = {} } = res;
      const { records = [], total = 0 } = result;
      this.setState({
        dataSource: records,
        totalCount: Number(total),
      });
    });
  };
  onShowSizeChange = (current, size) => {
    if (current == size) {
      return;
    }
    this.setState(
      {
        size,
      },
      () => {
        this.handleFetchDataList();
      }
    );
  };
  handleChangeTable = (pagination, filters, sorter) => {
    const { columnKey, order } = sorter;
    const { query } = this.state;
    let _columnKey;
    let _order;
    if (columnKey === 'latelyLearnTime' && order === 'ascend') {
      _columnKey = 'LATE_LEARN_TIME';
      _order = 'SORT_ASC';
    }

    if (columnKey === 'latelyLearnTime' && order === 'descend') {
      _columnKey = 'LATE_LEARN_TIME';
      _order = 'SORT_DESC';
    }

    if (columnKey === 'startLearnTime' && order === 'ascend') {
      _columnKey = 'START_LEARN_TIME';
      _order = 'SORT_ASC';
    }

    if (columnKey === 'startLearnTime' && order === 'descend') {
      _columnKey = 'START_LEARN_TIME';
      _order = 'SORT_DESC';
    }

    if (columnKey === 'learnNum' && order === 'ascend') {
      _columnKey = 'LEARN_NUM';
      _order = 'SORT_ASC';
    }

    if (columnKey === 'learnNum' && order === 'descend') {
      _columnKey = 'LEARN_NUM';
      _order = 'SORT_DESC';
    }
    const _query = {
      ...query,
      sortMap: {},
    };
    _query.sortMap[_columnKey] = _order;
    this.setState(
      {
        query: _query,
      },
      () => this.handleFetchDataList()
    );
  };
  watchDetail = (record) => {
    this.setState({
      userLearnDetailModalSHow: true,
      storeCustomerId: record.storeCustomerId,
      planId: record.planId,
    });
  };
  closeUserLearnDetailModal = () => {
    this.setState({
      userLearnDetailModalSHow: false,
    });
  };
  UnbundEmployee = (record) => {
    if (User.getUserRole() === 'CloudOperator') {
      return confirm({
        title: '你确定要解绑与学员的关系吗？',
        content: '解绑后，学员该培训计划的学习数据将同步移出',
        icon: <span className='icon iconfont default-confirm-icon'>&#xe839; </span>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.handleConfirmUnbundEmployee(record.storeCustomerId);
        },
      });
    } else {
      this.setState({
        unbundEmployeeModalVisible: true,
        storeCustomerId: record.storeCustomerId,
      });
    }
  };

  handleConfirmUnbundEmployee = (storeCustomerId) => {
    let removeUserIds = [];
    removeUserIds.push(storeCustomerId);
    const params = {
      planId: getParameterByName('id'),
      removeUserIds,
      storeCustomerId: storeCustomerId,
      storeId: User.getStoreId(),
      storeUserId: User.getStoreUserId(),
    };
    PlanService.removePlanCustomer(params).then((res) => {
      this.handleFetchDataList();
      message.success('解绑成功');
    });
  };
  handleCloseUnbundEmployeeModal = () => {
    this.setState({
      unbundEmployeeModalVisible: false,
    });
  };
  // 请求表头
  parselumns = () => {
    let columns;
    if (User.getUserRole() === 'CloudManager' || User.getUserRole() === 'StoreManager') {
      columns = [
        {
          title: '学员',
          key: 'storeCustomerName',
          dataIndex: 'storeCustomerName',
          render: (val, record) => {
            return <div>{val}</div>;
          },
        },
        {
          title: '学习状态',
          key: 'learnState',
          dataIndex: 'learnState',
          render: (val, record) => {
            return <div>{LearnState[val].text}</div>;
          },
        },
        {
          title: (
            <span>
              <span>负责人</span>
              <Tooltip title='培训计划的分享者/跟进人'>
                <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: '400' }}>
                  &#xe61d;
                </i>
              </Tooltip>
            </span>
          ),
          key: 'userNameList',
          dataIndex: 'userNameList',
          render: (val, record) => {
            return (
              <div>
                {record.userNameList.map((item, index) => {
                  return (
                    <span>
                      {item} {index < record.userNameList.length - 1 && <span> 、</span>}{' '}
                    </span>
                  );
                })}
              </div>
            );
          },
        },
        {
          title: '最近学习时间',
          key: 'latelyLearnTime',
          dataIndex: 'latelyLearnTime',
          sorter: true,
          width: 240,
          render: (val, record) => {
            return `${formatDate('YYYY-MM-DD H:i', parseInt(record.latelyLearnTime))}`;
          },
        },
        {
          title: '开始学习时间',
          key: 'startLearnTime',
          dataIndex: 'startLearnTime',
          width: 240,
          sorter: true,
          render: (val, record) => {
            return <div>{formatDate('YYYY-MM-DD H:i', val)}</div>;
          },
        },
        {
          title: (
            <span>
              <span>学习进度</span>
              <Tooltip title='学员培训计划中达到“已完成”状态的课程数/总课程数'>
                <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: '400' }}>
                  &#xe61d;
                </i>
              </Tooltip>
            </span>
          ),
          key: 'learnNum',
          dataIndex: 'learnNum',
          width: 130,
          sorter: true,
          render: (val, record) => {
            return (
              <div className='learn-num'>
                <span>{record.courseFinishNum}</span>
                <span>/</span>
                <span>{record.courseNum}</span>
              </div>
            );
          },
        },
        {
          title: '操作',
          key: 'operate',
          dataIndex: 'operate',
          render: (val, record) => {
            return (
              <div className='operate-area'>
                <span className='operate-item' onClick={() => this.watchDetail(record)}>
                  学习详情
                </span>
                <span className='split'>|</span>
                <span
                  className='operate-item'
                  onClick={() => {
                    this.UnbundEmployee(record);
                  }}>
                  解绑
                </span>
              </div>
            );
          },
        },
      ];
    } else {
      columns = [
        {
          title: '学员',
          key: 'storeCustomerName',
          dataIndex: 'storeCustomerName',
          render: (val, record) => {
            return <div>{val}</div>;
          },
        },
        {
          title: '学习状态',
          key: 'learnState',
          dataIndex: 'learnState',
          render: (val, record) => {
            return <div>{LearnState[val].text}</div>;
          },
        },
        {
          title: '最近学习时间',
          key: 'latelyLearnTime',
          dataIndex: 'latelyLearnTime',
          sorter: true,
          render: (val, record) => {
            return <div>{formatDate('YYYY-MM-DD H:i', val)}</div>;
          },
        },
        {
          title: '开始学习时间',
          key: 'startLearnTime',
          dataIndex: 'startLearnTime',
          sorter: true,
          render: (val, record) => {
            return <div>{formatDate('YYYY-MM-DD H:i', val)}</div>;
          },
        },
        {
          title: (
            <span>
              <span>学习进度</span>
              <Tooltip title='学员培训计划中达到“已完成”状态的课程数/总课程数'>
                <i className='icon iconfont' style={{ marginLeft: '5px', cursor: 'pointer', color: '#bfbfbf', fontSize: '14px', fontWeight: 'normal' }}>
                  &#xe61d;
                </i>
              </Tooltip>
            </span>
          ),
          key: 'learnNum',
          dataIndex: 'learnNum',
          sorter: true,
          render: (val, record) => {
            return (
              <div>
                <span>{record.courseFinishNum}</span>
                <span>/</span>
                <span>{record.courseNum}</span>
              </div>
            );
          },
        },
        {
          title: '操作',
          key: 'operate',
          dataIndex: 'operate',
          render: (val, record) => {
            return (
              <div className='operate-area'>
                <span className='operate-item' onClick={() => this.watchDetail(record)}>
                  学习详情
                </span>
                <span className='split'>|</span>
                <span
                  className='operate-item'
                  onClick={() => {
                    this.UnbundEmployee(record);
                  }}>
                  解绑
                </span>
              </div>
            );
          },
        },
      ];
    }

    return columns;
  };
  render() {
    const { dataSource, query, size, totalCount, userLearnDetailModalSHow, storeCustomerId, planId, unbundEmployeeModalVisible } = this.state;
    return (
      <div className='user-learning-data'>
        <div className='search-container'>
          <UserLearningDataFilter onChange={this.handleFetchDataList} />
        </div>
        <div>
          <XMTable
            renderEmpty={{
              image: college,
              description: '暂无数据',
            }}
            rowKey={(record) => record.storeCustomerId}
            dataSource={dataSource}
            columns={this.parselumns()}
            pagination={false}
            className='user-learning-table'
            onChange={this.handleChangeTable}
            showSorterTooltip={false}
            bordered
          />
          {dataSource.length > 0 && (
            <div className='box-footer'>
              <PageControl
                current={query.current - 1}
                pageSize={size}
                total={totalCount}
                toPage={(page) => {
                  const _query = { ...query, current: page + 1 };
                  this.setState(
                    {
                      query: _query,
                    },
                    () => {
                      this.handleFetchDataList();
                    }
                  );
                }}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          )}
        </div>
        {userLearnDetailModalSHow && (
          <UserLearnDetailModal storeCustomerId={storeCustomerId} planId={planId} visible={userLearnDetailModalSHow} onClose={this.closeUserLearnDetailModal} />
        )}
        {unbundEmployeeModalVisible && (
          <UnbundEmployeeModal
            visible={unbundEmployeeModalVisible}
            onClose={this.handleCloseUnbundEmployeeModal}
            storeCustomerId={storeCustomerId}
            onConfirm={() => {
              this.handleFetchDataList();
              this.handleCloseUnbundEmployeeModal();
            }}
          />
        )}
      </div>
    );
  }
}

export default withRouter(UserLearningData);
