/*
 * @Author: yuananting
 * @Date: 2021-07-29 13:57:03
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-18 10:53:45
 * @Description: 任务中心-培训任务-新建页面
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useEffect, useState, useRef } from 'react';
import { Button, message, Modal } from 'antd';
import ShowTips from '@/components/ShowTips';
import Breadcrumbs from '@/components/Breadcrumbs';
import BasicInfo from './components/BasicInfo';
import TrainContent from './components/TrainContent';
import User from '@/common/js/user';
import _ from 'underscore';
import './AddTrainTask.less';
import Upload from '@/core/upload';
import { randomString } from '@/domains/basic-domain/utils';
import TaskCenterService from '@/domains/task-center-domain/TaskCenterService';
import Bus from '@/core/bus';
import $ from 'jquery';

function AddTrainTask() {
  const type = window.getParameterByName('type');
  const taskId = window.getParameterByName('taskId');
  const taskState = window.getParameterByName('taskState');

  const defaultCover = 'https://image.xiaomaiketang.com/xm/rEAetaTEh3.png';

  const DEFAULT_BASIC_INFO = {
    createId: User.getStoreUserId(),
    taskName: '', // 培训任务名称
    coverUrl: defaultCover,
    coverId: null,
    helpStoreUserIds: [
      {
        checkedId: User.getStoreUserId(),
        checkedName: User.getStoreUserName(),
      },
    ], // 指定协同者id
    timeType: 'FOREVER', // 培训时间，默认永久有效
    startTime: null, // 固定时间段-开始时间
    endTime: null, // 固定时间段-结束时间
    learnType: 'FREEDOM', // 学习模式，默认自由学习
    assignList: [], // 指派列表-assignId assignType
    introduce: null, // 培训目的
    loadintroduce: false,
  };

  const DEFAULT_STAGE_LIST = [
    {
      stageName: '阶段一',
      contentList: [],
      check: false,
      sequence: 1,
    },
  ];

  const DEFAULT_ORIGIN_STAGE_LIST = [
    {
      stageName: '阶段一',
      contentList: [],
      check: false,
      sequence: 1,
    },
  ];

  const [activeStep, setActiveStep] = useState('BASIC_INFO');
  const [basicInfo, setBasicInfo] = useState(DEFAULT_BASIC_INFO);
  const [stageList, setStageList] = useState(DEFAULT_STAGE_LIST);
  const [percentCompleteLive, setPercentCompleteLive] = useState(80); // 完成百分比
  const [percentCompleteVideo, setPercentCompleteVideo] = useState(80); // 完成百分比
  const [percentCompletePicture, setPercentCompletePicture] = useState(80); // 完成百分比
  const [startCheck, setStartCheck] = useState(false); // 是否启动校验
  const basicInfoRef = useRef(null);

  const [originBasicInfo, setOriginBasicInfo] = useState(DEFAULT_BASIC_INFO);

  const [originStageList, setOriginStageList] = useState(DEFAULT_ORIGIN_STAGE_LIST);

  const [originPercentCompleteLive, setOriginPercentCompleteLive] = useState(80); // 完成百分比
  const [originPercentCompleteVideo, setOriginPercentCompleteVideo] = useState(80); // 完成百分比
  const [originPercentCompletePicture, setOriginPercentCompletePicture] = useState(80); // 完成百分比

  useEffect(() => {
    basicInfoRef.current = basicInfo;
  }, [basicInfo]);

  useEffect(() => {
    if (type === 'edit') {
      initTaskData();

      // 编辑回显数据详情
      function initTaskData() {
        TaskCenterService.getTrainingTaskDetail({
          taskId,
        }).then((res) => {
          const {
            result: {
              created,
              createId,
              taskName,
              courseMediaVOS,
              helpStoreUsers,
              timeType,
              startTime,
              endTime,
              learnType,
              assignList,
              percentCompleteLive,
              percentCompletePicture,
              percentCompleteVideo,
              trainingStageList,
            },
          } = res;

          const _assignList = assignList
            ? assignList.map((item) => {
                item.checkedId = item.assignId;
                item.checkedName = item.assignName;
                item.checkedType = item.assignType;
                return item;
              })
            : [];

          const coverInfo = courseMediaVOS.filter((item) => item.contentType === 'COVER')[0];
          const coverUrl = coverInfo ? coverInfo.mediaUrl : defaultCover;
          const coverId = coverInfo ? coverInfo.mediaContent : null;

          const _helpStoreUserIds = helpStoreUsers.map((item) => {
            item.checkedName = item.storeUserName;
            item.checkedId = item.storeUserId;
            return item;
          });

          const ITEM_BASIC_INFO = {
            createId,
            assignList: _assignList,
            taskName,
            coverUrl,
            coverId,
            helpStoreUserIds: _helpStoreUserIds,
            timeType,
            startTime: timeType === 'FOREVER' ? created : startTime,
            endTime,
            learnType,
          };

          const _stageList = trainingStageList.map((item) => {
            item.contentList = item.contentVOList;
            item.type = 'text';
            return item;
          });

          const _originStageList = _stageList.map((item) => Object.assign({}, item));

          const introduceInfo = courseMediaVOS.filter((item) => item.contentType === 'INTRO')[0];
          setBasicInfo({ ...basicInfoRef.current, ...ITEM_BASIC_INFO, loadintroduce: !introduceInfo });
          setOriginBasicInfo({ ...basicInfoRef.current, ...ITEM_BASIC_INFO, loadintroduce: !introduceInfo });
          setPercentCompleteLive(percentCompleteLive);
          setPercentCompleteVideo(percentCompleteVideo);
          setPercentCompletePicture(percentCompletePicture);
          setOriginPercentCompleteLive(percentCompleteLive);
          setOriginPercentCompleteVideo(percentCompleteVideo);
          setOriginPercentCompletePicture(percentCompletePicture);
          setStageList(_stageList);
          setOriginStageList(_originStageList);

          introduceInfo && getTextDetail('introduce', introduceInfo);
        });
      }
    }
  }, [taskId, type]);

  // 获取培训目的内容
  function getTextDetail(key, info) {
    if (info.mediaType === 'RESOURCE_ID') {
      $.ajax({
        data: {},
        type: 'GET',
        url: info.mediaUrl,
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        success: (res) => {
          setBasicInfo({
            ...basicInfoRef.current,
            [key]: res,
            [`load${key}`]: true,
          });
          setOriginBasicInfo({
            ...basicInfoRef.current,
            [key]: res,
            [`load${key}`]: true,
          });
        },
      });
    } else if (info.mediaType === 'TEXT') {
      setBasicInfo({
        ...basicInfoRef.current,
        [key]: info.mediaContent,
        [`load${key}`]: true,
      });
      setOriginBasicInfo({
        ...basicInfoRef.current,
        [key]: info.mediaContent,
        [`load${key}`]: true,
      });
    }
  }

  // 渲染底部操作按钮
  function renderFooter() {
    return (
      <Choose>
        <When condition={activeStep === 'BASIC_INFO'}>
          <div className='footer shrink-footer'>
            <Button onClick={handleGoBack}>取消</Button>
            <Button onClick={() => handleSubmit('NO')}>保存</Button>
            <Button type='primary' onClick={() => setActiveStep('TRAIN_CONTENT')}>
              下一步
            </Button>
          </div>
        </When>
        <Otherwise>
          <div className='footer shrink-footer'>
            <Button onClick={handleGoBack}>取消</Button>
            <Button onClick={() => setActiveStep('BASIC_INFO')}>上一步</Button>
            <Button onClick={() => handleSubmit('NO')}>保存</Button>
            <Button type='primary' onClick={() => handleSubmit('YES')}>
              保存并发布
            </Button>
          </div>
        </Otherwise>
      </Choose>
    );
  }

  // 确认保存新建
  function submitRemote(introduceId, issue) {
    const { createId, assignList, endTime, helpStoreUserIds, learnType, startTime, taskName, timeType, coverId } = basicInfo;

    let _scheduleMediaRequests = [];

    if (coverId) {
      _scheduleMediaRequests.push({
        contentType: 'COVER',
        mediaContent: coverId,
        mediaType: 'PICTURE',
      });
    }

    if (introduceId) {
      _scheduleMediaRequests.push({
        contentType: 'INTRO',
        mediaContent: introduceId,
        mediaType: 'RESOURCE_ID',
      });
    }

    const _stageList = stageList.map((item, index) => {
      delete item.contentVOList;
      delete item.check;
      delete item.type;
      delete item.liveFailure;
      item.sequence = index + 1;
      return item;
    });

    const _helpStoreUserIds = helpStoreUserIds.map((item) => {
      return item.checkedId;
    });

    const _assignList = assignList.map((item) => {
      return {
        assignId: item.checkedId,
        assignType: item.checkedType,
      };
    });

    const commonParams = {
      assignList: _assignList,
      createId,
      endTime,
      helpStoreUserIds: _helpStoreUserIds, // 协同者集合
      issueState: issue, // 是否发布
      learnType, // 学习模式
      scheduleMediaRequests: _scheduleMediaRequests,
      startTime,
      storeId: User.getStoreId(),
      taskName,
      timeType,
      percentCompleteLive,
      percentCompletePicture,
      percentCompleteVideo,
      introduceId,
      trainingStageList: _stageList,
    };

    if (type === 'edit') {
      TaskCenterService.updateTrainingTask({ ...commonParams, id: taskId }).then((res) => {
        message.success('保存成功');
        RCHistory.goBack();
      });
    } else {
      TaskCenterService.createTrainingTask(commonParams).then((res) => {
        message.success('保存成功');
        RCHistory.goBack();
      });
    }
    Bus.trigger('getTrainingTaskPage');
    Bus.trigger('getStoreTaskNum');
  }

  // 保存
  function handleSubmit(issue) {
    setStartCheck(true);
    const { taskName, assignList, timeType, startTime, endTime } = basicInfo;

    if (!taskName) {
      activeStep === 'TRAIN_CONTENT' && setActiveStep('BASIC_INFO');
      return message.warning('请输入培训任务名称');
    }

    if (timeType === 'VALIDITY') {
      if (!startTime) {
        return message.warning('请选择开始时间');
      }
      if (!endTime) {
        return message.warning('请选择结束时间');
      }
      if ((type === 'add' || taskState === 'UN_START') && startTime < new Date().getTime()) {
        return message.warning('开始时间不能早于现在');
      }
      if (!endTime > new Date().getTime()) {
        return message.warning('结束时间不能早于现在');
      }
    }

    if (assignList.length === 0) {
      activeStep === 'TRAIN_CONTENT' && setActiveStep('BASIC_INFO');
      return message.warning('请选择指派学员');
    }
    if (stageList.length === 0) {
      activeStep === 'BASIC_INFO' && setActiveStep('TRAIN_CONTENT');
      return message.warning('请添加阶段');
    }

    const stageNameEmpty = stageList.filter((item) => !item.stageName);
    if (stageNameEmpty.length > 0) {
      activeStep === 'BASIC_INFO' && setActiveStep('TRAIN_CONTENT');
      return message.warning('请输入阶段名称');
    }

    const stageNameArr = stageList.map((item) => item.stageName);
    const stageNameSet = new Set(stageNameArr);
    if (stageNameSet.size !== stageNameArr.length) {
      activeStep === 'BASIC_INFO' && setActiveStep('TRAIN_CONTENT');
      return message.warning('阶段名称不能重复');
    }

    if (percentCompleteLive === '' || percentCompleteVideo === '' || percentCompletePicture === '') {
      activeStep === 'BASIC_INFO' && setActiveStep('TRAIN_CONTENT');
      return message.warning('请输入完成标准');
    }

    if (basicInfo.introduce) {
      Upload.uploadTextToOSS(
        basicInfo.introduce,
        `${randomString()}.txt`,
        (introduceId) => {
          submitRemote(introduceId, issue);
        },
        () => {
          activeStep === 'TRAIN_CONTENT' && setActiveStep('BASIC_INFO');
          message.warning('上传培训目的失败');
        }
      );
    } else {
      submitRemote(null, issue);
    }
  }

  // 判断基本信息是否修改
  function isEqualBasicInfo() {
    return Object.entries(originBasicInfo).toString() === Object.entries(basicInfo).toString();
  }

  // 判断培训内容是否修改
  function isEqualStageList() {
    return JSON.stringify(originStageList) === JSON.stringify(stageList);
  }

  // 判断完成标准是否修改
  function isFinishedStandard() {
    return (
      percentCompleteLive === originPercentCompleteLive &&
      percentCompleteVideo === originPercentCompleteVideo &&
      percentCompletePicture === originPercentCompletePicture
    );
  }

  // 返回、取消
  function handleGoBack() {
    if (!isEqualBasicInfo() || !isEqualStageList() || !isFinishedStandard()) {
      Modal.confirm({
        title: '确认要返回吗?',
        content: '返回后，本次编辑的内容将不被保存。',
        okText: '确认返回',
        cancelText: '留在本页',
        icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
        onOk: () => {
          window.RCHistory.goBack();
        },
      });
    } else {
      window.RCHistory.goBack();
    }
  }

  function handleChangeBasicInfo(field, value) {
    if (field === 'coverUrl') {
      setBasicInfo({
        ...basicInfoRef.current,
        coverUrl: value.fileUrl,
        coverId: value.resourceId,
      });
    } else if (field === 'trainDate') {
      //  固定培训时间，设置起始
      setBasicInfo({
        ...basicInfoRef.current,
        startTime: value && value[0]?.valueOf(),
        endTime: value && value[1]?.valueOf(),
      });
    } else {
      setBasicInfo({
        ...basicInfoRef.current,
        [field]: value,
      });
    }
  }

  function handleChangeStageInfo(field, value) {
    if (field === 'stageList') {
      setStageList(value);
    } else {
      switch (field) {
        case 'percentCompleteLive':
          setPercentCompleteLive(value);
          break;
        case 'percentCompleteVideo':
          setPercentCompleteVideo(value);
          break;
        case 'percentCompletePicture':
          setPercentCompletePicture(value);
          break;
        default:
          break;
      }
    }
  }

  return (
    <div className='page add-train-task'>
      <Breadcrumbs navList={type === 'add' ? '新建培训任务' : '编辑培训任务'} goBack={handleGoBack} />
      <div className='box'>
        <div className='show-tips'>
          <ShowTips message='请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦企学院保有依据国家规定及平台规则进行处理的权利' />
        </div>
        <div className='header-tab'>
          <span className='tab-title' onClick={() => setActiveStep('BASIC_INFO')}>
            <span className={`step-icon ${activeStep === 'BASIC_INFO' ? 'active-icon' : 'default-icon'}`}>1</span>
            <span style={{ position: 'relative' }}>
              <span className={`${activeStep === 'BASIC_INFO' && 'active-text'}`}>基本信息</span>
              {activeStep === 'BASIC_INFO' && <span className='active-line'></span>}
            </span>
          </span>
          <span className='next-arrow'></span>
          <span className='tab-title' onClick={() => setActiveStep('TRAIN_CONTENT')}>
            <span className={`step-icon ${activeStep === 'TRAIN_CONTENT' ? 'active-icon' : 'default-icon'}`}>2</span>
            <span style={{ position: 'relative' }}>
              <span className={`${activeStep === 'TRAIN_CONTENT' && 'active-text'}`}>培训内容</span>
              {activeStep === 'TRAIN_CONTENT' && <span className='active-line'></span>}
            </span>
          </span>
        </div>
        {activeStep === 'BASIC_INFO' && <BasicInfo basicInfo={basicInfo} startCheck={startCheck} onChange={handleChangeBasicInfo} />}
        {activeStep === 'TRAIN_CONTENT' && (
          <TrainContent
            stageList={stageList}
            basicInfo={basicInfo}
            startCheck={startCheck}
            percentCompleteLive={percentCompleteLive}
            percentCompleteVideo={percentCompleteVideo}
            percentCompletePicture={percentCompletePicture}
            onChange={handleChangeStageInfo}
          />
        )}
      </div>
      {renderFooter()}
    </div>
  );
}

export default AddTrainTask;
