/*
 * @Author: yuananting
 * @Date: 2021-07-29 13:57:03
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-09 17:39:56
 * @Description: 任务中心-培训任务-新建页面
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useEffect, useState } from 'react';
import { Button, message, Modal, Space } 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';

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

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

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

const DEFAULT_FINISH_STANDARD = {
  percentCompleteLive: 80,
  percentCompleteVideo: 80, // 线上课完成百分比
  percentCompletePicture: 80, // 图文课完成百分比
};

function AddTrainTask() {
  const type = getParameterByName('type');
  const [activeStep, setActiveStep] = useState('BASIC_INFO');
  const [basicInfo, setBasicInfo] = useState(DEFAULT_BASIC_INFO);
  const [stageList, setStageList] = useState(DEFAULT_STAGE_LIST);
  const [finishStandard, setFinishStandard] = useState(DEFAULT_FINISH_STANDARD); // 完成百分比
  const [startCheck, setStartCheck] = useState(false); // 是否启动校验

  // useEffect(() => {

  // }, [basicInfo]);
  console.log('basicInfo=====>', basicInfo);

  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>
            {/* disabled={submitDisabled} */}
          </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>
            {/* disabled={submitDisabled} */}
          </div>
        </Otherwise>
      </Choose>
    );
  }

  function submitRemote(introduceId, issue) {
    const { endTime, helpStoreUserIds, learnType, startTime, taskName, timeType, coverId, coverUrl } = basicInfo;

    const { percentCompleteLive, percentCompletePicture, percentCompleteVideo } = finishStandard;

    const commonParams = {
      assignList: [
        // 指派对象
        {
          assignId: '',
          assignName: '',
          assignType: '',
        },
      ],

      createId: User.getUserId(),
      endTime,
      helpStoreUserIds, // 协同者集合
      issueState: issue, // 是否发布
      learnType, // 学习模式
      scheduleMediaRequests: [
        {
          contentType: 'COVER',
          mediaContent: coverId,
          mediaType: 'PICTURE',
          mediaUrl: coverUrl,
        },
      ],
      startTime,
      storeId: User.getStoreId(),
      taskName,
      timeType,
      percentCompleteLive,
      percentCompletePicture,
      percentCompleteVideo,
      introduceId,
    };

    console.log('commonParams:', commonParams);
  }

  function handleSubmit(issue) {
    setStartCheck(true);
    if (stageList.length === 0) {
      return message.warning('请添加阶段');
    }

    Upload.uploadTextToOSS(
      basicInfo.introduce,
      `${randomString()}.txt`,
      (introduceId) => {
        submitRemote(introduceId, issue);
      },
      () => message.warning('上传培训目的失败')
    );
  }

  function handleGoBack() {
    window.RCHistory.goBack();
  }

  function handleChangeBasicInfo(field, value) {
    console.log('handleChangeBasicInfo====>', basicInfo, field, value);
    if (field === 'coverUrl') {
      setBasicInfo({
        ...basicInfo,
        coverUrl: value.fileUrl,
        coverId: value.resourceId,
      });
    } else if (field === 'trainDate') {
      //  固定培训时间，设置起始
      setBasicInfo({
        ...basicInfo,
        startTime: value && value[0]?.valueOf(),
        endTime: value && value[1]?.valueOf(),
      });
    } else if (field === 'timeType' && value === 'FOREVER') {
      setBasicInfo({
        ...basicInfo,
        [field]: value,
        startTime: null,
        endTime: null,
      });
    } else {
      let a = {
        ...basicInfo,
        [field]: value,
      };
      console.log('a====>', a);
      setBasicInfo(a);
    }
  }

  function handleChangeStageInfo(field, value) {
    if (field === 'stageList') {
      setStageList(value);
    } else {
      setFinishStandard({
        ...finishStandard,
        [field]: value,
      });
    }
  }

  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} finishStandard={finishStandard} onChange={handleChangeStageInfo} />
        )}
      </div>
      {renderFooter()}
    </div>
  );
}

export default AddTrainTask;
