/*
 * @Author: 吴文洁
 * @Date: 2020-07-17 15:49:11
 * @Last Modified by: chenshu
 * @Last Modified time: 2021-04-06 16:43:23
 * @Description: 大班互动-添加/编辑直播课
 */

import React, { ReactElement, useEffect, useState } from 'react';
import { withRouter } from 'react-router-dom';
import { Button, message, Modal } from 'antd';

import ShowTips from '@/components/ShowTips';
import Breadcrumbs from '@/components/Breadcrumbs';
import Bus from '@/core/tbus';

import AddLiveBasic from './AddLiveBasic';
import AddLiveClassInfoWorkWX from './AddLiveClassInfoWorkWX';
import { randomString } from '@/domains/basic-domain/utils';
import Upload from '@/core/upload';
import PreviewCourseModal from '../modal/PreviewCourseModal';
import CourseService from '@/domains/course-domain/CourseService';
import routeHook from '@/core/routeHook'
import moment from 'moment';
import User from '@/common/js/user';
import _ from 'underscore';
import $ from 'jquery';
import './CreateWorkWXCourse.less';

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


const defaultBasicInfo = {
  courseName: '', // 课程名称
  coverUrl: defaultCover,
  coverId: '',
  categoryId: null,
}


const defaultClassInfo = {
  teacherId: null, //讲师的Id
  courseName: '', //课程名称
  duration: 3600000, //直播时长默认1小时
  remindTime: 0,  //提醒时间
  startTime: new Date().getTime() + 300000,
};

function CreateWorkWXCourse() {
  const [id, setId] = useState(getParameterByName('id'))
  const [type,setType] = useState(getParameterByName('type'))
  const [loading, setLoading] = useState(false)
  const [isEdit, setIsEdit] = useState(true)
  const [courseState, setCourseState] = useState('UN_START')
  const [editorTextLength, setEditorTextLength] = useState(0)
  const [loadintroduce, setLoadintroduce] = useState(false)
  const [basicInfo, setBasicInfo] = useState(defaultBasicInfo)
  const [classInfo, setClassInfo] = useState(defaultClassInfo)
  const [endTime, setEndTime] = useState(0)
  const [introduce, setIntroduce] = useState('')
  const [previewLiveCourseModal, setPreviewLiveCourseModal] = useState()

  useEffect(()=> {
    routeHook.addSaveCase();
    if (type === 'edit') {
      getCourseDetail();
    }
    Bus.bind('editorLimit', (editorTextLength) => {
      setEditorTextLength(editorTextLength)
    });
  },[])

  function getCourseDetail() {
    setLoading(true)
    CourseService.getWorkWXLiveCourseDetail({
      liveCourseId: id,
    }).then((res) => {
      const {
        teacherId,
        teacherName,
        courseName,
        startTime,
        duration,
        courseMediaVOList,
        categoryId,
        categoryName,
        remindTime
      } = res.result;
      let coverId;
      let coverUrl;
      let hasIntro = false;
      courseMediaVOList && courseMediaVOList.map((item) => {
        switch (item.contentType) {
          case 'COVER':
            coverId = item.mediaContent;
            coverUrl = item.mediaUrl;
            break;
          case 'INTRO':
            hasIntro = true;
            getIntroduce('introduce', item.mediaUrl);
            break;
          default:
            break;
        }

        return item;
      });

      const _basicInfo = {
        courseName,
        coverUrl: coverUrl || defaultCover,
        coverId,
        categoryId,
        categoryName,
      };

      const _classInfo = {
        teacherId,
        teacherName,
        duration,
        startTime,
        remindTime,
      };

      // 晚于开课前30分钟
      if (new Date().getTime() > startTime - 1800000) {
        setIsEdit(false)
      }
      setLoadintroduce(!hasIntro)
      setLoading(false)
      setBasicInfo(_basicInfo)
      setClassInfo(_classInfo)
      setCourseState(courseState)
    });
  };

  //获取简介
  function getIntroduce(key, url) {
    $.ajax({
      data: {},
      type: 'GET',
      url,
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
      success: (res) => {
        setLoadintroduce(true)
        setIntroduce(res)
      },
      error: () => {
        message.warning('获取简介失败');
      },
    });
  };

  // 修改基本信息
  function handleChangeBasicInfo(field, value) {
    let binfo = {...basicInfo}
    binfo[field] = value
    setBasicInfo(binfo)
  };

  //课程信息变更回调
  function onClassInfoChange(field, value) {
    let classinfo = {...classInfo}
    switch (field) {
      case 'intro':
        setIntroduce(value)
        break;
      case 'beginTime':
        console.log(value)
        classinfo.startTime = value
        setClassInfo(classinfo)
        break;
      case 'endTime':
        console.log(value)
        setEndTime(value)
      break;
      case 'duration':
        classinfo.duration = value
        setClassInfo(classinfo)
        break;
      case 'teacherId':
        classinfo.teacherId = value
        setClassInfo(classinfo)
        break;
      case 'remindTime':
        classinfo.remindTime = value
        setClassInfo(classinfo)
        break;
      default:
          console.log("NULL")
    }
  }

  // 修改简介
  function handleChangeIntroInfo(field, value) {

  };

  // 完成创建/编辑
  function handleSubmit() {
    //过期判断
    if (User.getExpirationTime() && moment().valueOf() > Number(User.getExpirationTime())) {
      Modal.warning({
        title: '服务已到期',
        content: '当前企业购买的小麦企学院服务已到期，如需继续使用学院功能，请尽快续费购买',
        okText: '我知道了',
      });
      return;
    }
    if (type === 'edit' && isEdit && new Date().getTime() > classInfo.startTime - 1800000) {
      Modal.info({
        title: '提示',
        icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
        content: '晚于开课前30分钟，部分信息不可修改',
        okText: '我知道了',
        onOk: () => {
          getCourseDetail();
        },
      });
      return;
    }
    // this.handleValidate(addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, isEdit, editorTextLength).then((res) => {
      // if (!res) return;
      //上传简介
      Upload.uploadTextToOSS(
        introduce,
        `${randomString()}.txt`,
        (introduceId) => {
          submitRemote({ introduceId, id });
        },
        () => message.warning('上传课程简介失败')
      );
    // });
  };

  function submitRemote({ introduceId, id }) {
    if (type === 'add') {
    } else {
    }


    if (type === 'add') {
      if (endTime !== 0) {
        classInfo.duration = String((endTime - classInfo.startTime)/1000)
      }
      const params = {
        ...classInfo,
        operatorId:User.getUserId(),
        introduceId,
        storeId: User.getStoreId(),
        ...basicInfo
      };
      CourseService.createWorkWXLiveCourse(params).then((res) => {
        if (res.success) {
          message.success('新建成功');
          window.RCHistory.push({
            pathname: `/live-course`,
          });
        }
      });
    } else {
      if (endTime !== 0) {
        classInfo.duration = String((endTime - classInfo.startTime)/1000)
      }
      const params = {
        ...classInfo,
        operatorId:User.getUserId(),
        introduceId,
        storeId: User.getStoreId(),
        ...basicInfo,
        liveCourseId: id
      };
      CourseService.updateWorkWXLiveCourse(params).then((res) => {
        if (res.success) {
          message.success('更新成功');
          window.RCHistory.push({
            pathname: `/live-course`,
          });
        }
      });
    }
  };
/*
  handleValidate = (addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, isEdit, editorTextLength) => {
    return new Promise((resolve) => {
      const { type } = this.state;
      const { courseName, categoryId } = addLiveBasicInfo;
      const { liveDate, timeHorizonStart, timeHorizonEnd, teacherId, calendarTime } = addLiveClassInfo;
      const { liveCourseMediaRequests } = addLiveIntroInfo;
      const currentTime = +new Date();

      if (!courseName) {
        message.warning('请输入课程名称');
        resolve(false);
        return;
      }

      if (!categoryId) {
        message.warning('请选择课程分类');
        resolve(false);
        return;
      }

      if (type === 'add') {
        const { startTime, endTime } = addLiveClassInfo;
        if (calendarTime.length === 0) {
          message.warning('请选择上课日期');
          resolve(false);
          return;
        } else if (startTime === endTime || startTime > endTime) {
          message.warning('结束时间必须晚于开始时间');
          resolve(false);
          return;
        }
        // 若有今日排课 校验当前时间
        const currentDay = moment(currentTime).format('YYYY-MM-DD');
        const itemToday = _.find(calendarTime, (item) => {
          const itemDay = moment(item).format('YYYY-MM-DD');
          return itemDay === currentDay;
        });
        if (itemToday) {
          const itemDay = moment(itemToday).format('YYYY-MM-DD');
          const itemHour = moment(startTime).format('HH:mm');
          if (itemDay === currentDay) {
            if (moment(itemDay + ' ' + itemHour).format('x') < currentTime) {
              message.warning('开始时间不能早于现在');
              resolve(false);
              return;
            }
          }
        }
      } else {
        const _liveDate = moment(liveDate).format('YYYY-MM-DD');
        const _timeHorizonStart = moment(timeHorizonStart).format('HH:mm');
        const _timeHorizonEnd = moment(timeHorizonEnd).format('HH:mm');

        const startTime = moment(_liveDate + ' ' + _timeHorizonStart).format('x');
        const endTime = moment(_liveDate + ' ' + _timeHorizonEnd).format('x');
        if (!startTime || !endTime) {
          message.warning('日期不能为空');
          resolve(false);
          return;
        } else if (!timeHorizonStart) {
          message.warning('开始时间不能为空');
          resolve(false);
          return;
        } else if (!timeHorizonEnd) {
          message.warning('结束时间不能为空');
          resolve(false);
          return;
        } else if (isEdit && startTime < currentTime) {
          message.warning('开始时间不能早于当前时间');
          resolve(false);
          return;
        } else if (isEdit && endTime < currentTime) {
          message.warning('结束时间不能早于当前时间');
          resolve(false);
          return;
        } else if (isEdit && endTime <= startTime) {
          message.warning('结束时间不能早于开始时间');
          resolve(false);
          return;
        }
      }
      if (!teacherId) {
        message.warning('请选择讲师');
        resolve(false);
        return;
      }

      if (editorTextLength > 1000) {
        message.warning('课程简介超过字数限定');
        resolve(false);
        return;
      }
      resolve(true);
    });
  };
  */

  // 显示预览课程弹窗
  function handleShowPreviewModal() {
    // const { addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, type, courseState } = this.state;
    const previewLiveCourseModal = (
      <PreviewCourseModal
        courseBasicInfo={basicInfo}
        courseClassInfo={{...classInfo,endTime}}
        courseIntroInfo={{introduce:introduce,categoryName:basicInfo.courseName}}
        type={type}
        courseState={courseState}
        close={() => {
          setPreviewLiveCourseModal(null)
        }}
      />
    );

    setPreviewLiveCourseModal(previewLiveCourseModal)
  };

  // 取消编辑并返回上一级路由
  function handleGoBack() {
    // 比较state的addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo和默认数据是否相等
    // const { addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo } = this.state;
    if (!_.isEqual(basicInfo, defaultBasicInfo) || !_.isEqual(classInfo, defaultClassInfo)) {
      console.log('ghjklkjh')
      window.RCHistory.push({
        pathname: `/live-course`,
      });
    } else {
      routeHook.cancel()
      window.RCHistory.push({
        pathname: `/live-course`,
      });
    }
  };

  
    // const { id, type, addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, isEdit, loadintroduce } = this.state;
    return (
      <div className='page CreateWorkWXCourse'>
        <Breadcrumbs navList={type === 'add' ? '新建直播课' : '编辑直播课'} goBack={handleGoBack} />
        <div className='box'>
          <div className='show-tips'>
            <ShowTips message='请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦企学院保有依据国家规定及平台规则进行处理的权利' />
          </div>
          <div className='add-live-page__form'>
            <div className='basic-info__wrap'>
              <div className='title'>基本信息</div>
              <AddLiveBasic isEdit={isEdit} pageType={type} data={basicInfo} onChange={handleChangeBasicInfo} />
            </div>

            <div className='class-info__wrap'>
              <div className='title'>上课信息</div>
              {/* <AddLiveClass isEdit={isEdit} pageType={type} data={{ ...addLiveClassInfo, id }} onChange={handleChangeClassInfo} /> */}
              <AddLiveClassInfoWorkWX type={type} data={classInfo} isEdit={isEdit} introduce={introduce} onChange={onClassInfoChange}/>
            </div>

          </div>
        </div>

        <div className='footer shrink-footer'>
          <Button onClick={handleGoBack}>取消</Button>
          <Button onClick={handleShowPreviewModal}>预览</Button>
          <Button type='primary' onClick={_.debounce(() => handleSubmit(), 3000, true)}>
            保存
          </Button>
        </div>
        {previewLiveCourseModal}
      </div>
    );
}

export default withRouter(CreateWorkWXCourse);
