/*
 * @Author: yuananting
 * @Date: 2021-07-28 11:25:58
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-14 17:18:39
 * @Description: 任务中心-培训任务
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useEffect, useState } from 'react';
import TrainFilter from './components/TrainFilter';
import { Route, withRouter } from 'react-router-dom';
import TrainList from './components/TrainList';
import TaskCenterService from '@/domains/task-center-domain/TaskCenterService';
import DataCenter from '../data-center/Index';
import User from '@/common/js/user';
import Bus from '@/core/bus';

function TrainTaskPage(props) {
  const [trainListData, setTrainListData] = useState([]); // 培训任务列表
  const [query, setQuery] = useState({
    current: 1,
    endTime: null,
    issueState: 'ALL', // 发布状态
    myAssist: false, // 是否由我协同
    size: 10,
    sortMap: { UPDATED: 'SORT_DESC' }, // 排序(默认更新时间倒序)
    startTime: null,
    storeId: User.getStoreId(),
    storeUserId: User.getStoreUserId(),
    taskName: '',
  });
  const [totalCount, setTotalCount] = useState(0); // 总数
  const [storeTaskNum, setStoreTaskNum] = useState({});
  const { match } = props;

  useEffect(() => {
    getTrainingTaskPage();
  }, [query]);

  useEffect(() => {
    getStoreTaskNum();
    initPageData();
    return () => {
      removePageData();
    };
  }, []);

  useEffect(() => {}, []);

  const initPageData = () => {
    Bus.bind('getTrainingTaskPage', (filterData) => {
      getTrainingTaskPage(filterData);
    });
    Bus.bind('getStoreTaskNum', getStoreTaskNum);
  };

  const removePageData = () => {
    Bus.unbind('getTrainingTaskPage', getTrainingTaskPage);
    Bus.unbind('getStoreTaskNum', getStoreTaskNum);
  };

  // 获取计划列表
  function getTrainingTaskPage(filterData) {
    const _query = { ...query, ...filterData };
    if (_query.issueState === 'ALL') {
      delete _query.issueState;
    }
    TaskCenterService.getTrainingTaskPage(_query).then((res) => {
      const {
        result: { records = [], total },
      } = res;
      setTrainListData(records);
      setTotalCount(total);
    });
  }

  // 获取学院任务数量
  function getStoreTaskNum() {
    TaskCenterService.getStoreTaskNum({ storeId: User.getStoreId() }).then((res) => {
      setStoreTaskNum(res.result);
    });
  }

  // 搜索条件修改
  function queryChange(_query) {
    setQuery({ ...query, ..._query });
  }

  return (
    <div className='page'>
      <div className='content-header'>培训任务</div>
      <div className='box'>
        <TrainFilter onChange={queryChange} />
        <TrainList trainListData={trainListData} storeTaskNum={storeTaskNum} query={query} totalCount={totalCount} onChange={queryChange} />
      </div>
      <Route path={`${match.url}/data/:taskId`} component={DataCenter} />
    </div>
  );
}
export default withRouter(TrainTaskPage);
