/*
 * @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: 3600, //直播时长默认1小时
  remindTime: 900,  //提醒时间
  // startTime: new Date().getTime() + 300000,
  startTime: 0
};

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 [getInfo, setGetInfo] = useState(false)
  const [previewLiveCourseModal, setPreviewLiveCourseModal] = useState()

  useEffect(()=> {
    routeHook.addSaveCase();
    if (type === 'edit') {
      getCourseDetail();
    }else{
      setGetInfo(true)
    }
    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;
      });
      if (!hasIntro) {
        setGetInfo(true)
      }

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

      const _classInfo = {
        teacherId,
        teacherName,
        duration,
        startTime,
        endTime: startTime+Number(duration)*1000,
        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)
        setGetInfo(true)
      },
      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 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;
    }
    handleValidate().then((res) => {
      if (!res) return;
      //上传简介
      Upload.uploadTextToOSS(
        introduce,
        `${randomString()}.txt`,
        (introduceId) => {
          submitRemote({ introduceId, id });
        },
        () => message.warning('上传课程简介失败')
      );
    });
  };

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

    console.log('取消')

    routeHook.cancel()
    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('新建成功');
          Bus.trigger('freshCourseList')
          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) {
          Bus.trigger('freshCourseList')
          message.success('更新成功');
          window.RCHistory.push({
            pathname: `/live-course`,
          });
        }
      });
    }
  };

  function handleValidate() {
    return new Promise((resolve) => {
      if (_.isEmpty(basicInfo.courseName)) {
        message.warning("课程名称不能为空")
        resolve(false)
        return
      }
      if (_.isEmpty(basicInfo.categoryId)) {
        message.warning("课程分类未选择")
        resolve(false)
        return
      }
      if (!classInfo.startTime) {
        message.warning("未设置开始时间")
        resolve(false)
        return
      }
      if (_.isEmpty(classInfo.teacherId)) {
        message.warning("课程分类未选择")
        resolve(false)
        return
      }
      if (introduce.length > 1000) {
        message.warning("直播简介超过1000个字")
        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) || introduce.length > 0) {
      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'>基本信息<span style={{marginLeft:"24px",color:"#2966FF",fontSize:"14px"}}>温馨提示：在直播间可控制回放录制功能。</span></div>
              <AddLiveBasic isEdit={isEdit} pageType={type} data={basicInfo} onChange={handleChangeBasicInfo} courseNameLimit={20}/>
            </div>

            <div className='class-info__wrap'>
              <div className='title'>上课信息</div>
              {/* <AddLiveClass isEdit={isEdit} pageType={type} data={{ ...addLiveClassInfo, id }} onChange={handleChangeClassInfo} /> */}
              {
                getInfo && <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);
