/*
 * @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, useRef, 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()
  const [exItems, setExItems] = useState([])
  const [enableSubmit, setEnableSubmit] = useState(true)

  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;
      });
      

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

      const _classInfo = {
        teacherId,
        teacherName,
        duration,
        startTime,
        endTime: startTime+Number(duration)*1000,
        remindTime,
      };
      setEndTime(startTime+Number(duration)*1000)

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

  //获取简介
  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}
    console.log(field,value)
    switch (field) {
      case 'intro':
        setIntroduce(value)
        console.log(value.length)
        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.teacherId
        classinfo.teacherName = value.teacherName
        setClassInfo(classinfo)
        break;
      case 'remindTime':
        classinfo.remindTime = value
        setClassInfo(classinfo)
        break;
      default:
          console.log("NULL")
    }
  }

  // 完成创建/编辑
  function handleSubmit() {
    setExItems([])
    //过期判断
    if (User.getExpirationTime() && moment().valueOf() > Number(User.getExpirationTime())) {
      Modal.warning({
        title: '服务已到期',
        content: `当前企业购买的${window.brandName}服务已到期，如需继续使用学院功能，请尽快续费购买`,
        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 }) {
    setEnableSubmit(false)

    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) => {
        setEnableSubmit(true)
        if (res.success) {
          message.success('新建成功');
          Bus.trigger('freshCourseList')
          window.RCHistory.push({
            pathname: `/live-course`,
          });
        }
      })
      .catch((err)=> {
        setEnableSubmit(true)
      });
    } 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) => {
        setEnableSubmit(true)
        if (res.success) {
          Bus.trigger('freshCourseList')
          message.success('更新成功');
          window.RCHistory.push({
            pathname: `/live-course`,
          });
        }
      })
      .catch((err)=> {
        setEnableSubmit(true)
      });
    }
  };

  function handleValidate() {
    return new Promise((resolve) => {
      let _exitem = []
      if (_.isEmpty(basicInfo.courseName)) {
        _exitem.push("courseName")
      }
      if (_.isEmpty(basicInfo.categoryId)) {
        _exitem.push("categoryId")
      }
      if (!classInfo.startTime) {
        _exitem.push("startTime")
      }
      if (classInfo.startTime < new Date().getTime()) {
        _exitem.push("startTime")
      }
      if (endTime !== 0 && (endTime < classInfo.startTime)) {
        _exitem.push("endTime")
      }
      if (_.isEmpty(classInfo.teacherId)) {
        _exitem.push("teacherId")
      }
      if (editorTextLength > 1000) {
        _exitem.push("intro")
      }
      setExItems(_exitem)



      if (_.isEmpty(basicInfo.courseName)) {
        message.warning("课程名称不能为空")
        let item = document.getElementById("courseName")
        if (item) {
          item.scrollIntoView(true)
        }
        resolve(false)
        return
      }
      if (_.isEmpty(basicInfo.categoryId)) {
        message.warning("课程分类未选择")
        let item = document.getElementById("categoryId")
        if (item) {
          item.scrollIntoView(true)
        }
        resolve(false)
        return
      }
      if (!classInfo.startTime) {
        message.warning("未设置开始时间")
        let item = document.getElementById("startTime")
        if (item) {
          item.scrollIntoView(true)
        }
        resolve(false)
        return
      }
      if (classInfo.startTime < new Date().getTime()) {
        message.warning("开始时间不能早于现在")
        let item = document.getElementById("startTime")
        if (item) {
          item.scrollIntoView(true)
        }
        resolve(false)
        return
      }
      if (endTime !== 0 && (endTime < classInfo.startTime)) {
        message.warning("结束时间不能早于开始时间")
        let item = document.getElementById("endTime")
        if (item) {
          item.scrollIntoView(true)
        }
        resolve(false)
        return
      }
      if (_.isEmpty(classInfo.teacherId)) {
        message.warning("未设置讲师")
        let item = document.getElementById("teacherId")
        if (item) {
          item.scrollIntoView(true)
        }
        resolve(false)
        return
      }
      if (editorTextLength > 1000) {
        message.warning("直播简介超过1000个字")
        let item = document.getElementById("intro")
        if (item) {
          item.scrollIntoView(true)
        }
        resolve(false)
        return
      }
      resolve(true)
    });
  };


  // 显示预览课程弹窗
  function handleShowPreviewModal() {
    // const { addLiveBasicInfo, addLiveClassInfo, addLiveIntroInfo, type, courseState } = this.state;
    const previewLiveCourseModal = (
      <PreviewCourseModal 
        bizType="qiwei"
        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={`请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，${window.brandName}保有依据国家规定及平台规则进行处理的权利`} />
          </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} exItems={exItems}/>
            </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} exItems={exItems}/>
              }
              
            </div>

          </div>
        </div>

        <div className='footer shrink-footer'>
          <Button onClick={handleGoBack}>取消</Button>
          <Button onClick={handleShowPreviewModal}>预览</Button>
          <Button type='primary' onClick={_.debounce(() => handleSubmit(), 3000, true)} disabled={!enableSubmit}>
            {enableSubmit?"保存":"正在提交"}
          </Button>
        </div>
        {previewLiveCourseModal}
      </div>
    );
}

export default withRouter(CreateWorkWXCourse);
