/*
 * @Author: zhangleyuan
 * @Date: 2021-02-20 16:13:39
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-05-10 10:15:58
 * @Description: 描述一下
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useEffect, useState } from "react";
import { Button, message, Modal} from 'antd';
import ShowTips from "@/components/ShowTips";
import Breadcrumbs from "@/components/Breadcrumbs";
import BasicInfo from './components/BasicInfo';
import TrainingTask from './components/TrainingTask';
import ExpiredCourseList from './components/ExpiredCourseList';
import PlanService from '@/domains/plan-domain/planService'
import User from '@/common/js/user';
import _ from "underscore";
import './AddPlan.less'
const defaultCover = 'https://image.xiaomaiketang.com/xm/YNfi45JwFA.png';
const defaultBasicData = {
    planName:"",
    coverUrl: defaultCover,
    coverId:null,
    enableState:"YES",
    selectOperatorList:[],
    instro:'',
    operateType:'All_Operate',
    percentCompleteLive:80,
    percentCompleteVideo:80,
    percentCompletePicture:100
}
const defaultTaskList = [];

function AddPlan() {
    const id = getParameterByName("id");
    const type = getParameterByName("type");
    const [basicData,setBasicData] = useState(defaultBasicData);
    const [taskList,setTaskList] = useState(defaultTaskList);
    const [expiredCourseList,setExpiredCourseList] = useState([]);
    const [hasGetDetail,setHasGetDetail]= useState(false);
    const [submitDisabled,setSubmitDisabled] = useState(false);
    useEffect(()=>{
        if(type==='edit'){
            getPlanDetail();  
            getPlanCustomerState();
        }
    },id)
    function getPlanCustomerState(){
        PlanService.getTrainingCourseAutoCancel({
            planId: id
        }).then((res) => {
            const expiredCourseList = res.result;
            setExpiredCourseList(expiredCourseList)
        })
    }
    function getPlanDetail (){
        PlanService.getTrainingPlanDetail({
            planId: id
        }).then((res) => {
            const {
                planName,
                enableState,
                operateType,
                operateIds,
                percentCompleteLive,
                percentCompleteVideo,
                percentCompletePicture,
                courseMediaVOS,
                trainingTaskList
            } = res.result;
            let coverId;
            let coverUrl;
            let instro;
            courseMediaVOS.map((item) => {
                switch (item.contentType){
                    case "COVER":
                        coverId = item.mediaContent;
                        coverUrl = item.mediaUrl;
                    break;
                    case "INTRO":
                        instro = item.mediaContent;
                    break;  
                    default:
                    break;
                }
                return item;
            })
            let _selectOperatorList = [];
            if(operateIds){
                _selectOperatorList = operateIds.map((item,index)=>{
                    let _item = {};
                    _item.id = item;
                    return _item
                })
            }
            setTaskList(trainingTaskList);
            setBasicData({
                planName,
                coverUrl:coverUrl || defaultCover,
                coverId,
                enableState,
                selectOperatorList:_selectOperatorList,
                instro,
                operateType,
                percentCompleteLive,
                percentCompleteVideo,
                percentCompletePicture
            })
            setHasGetDetail(true);
        })
    }
    function handleChangeBasicInfo(field, value,option){
        setBasicData( {
            ...basicData,
            [field]: value,
        })
    }

    function handleChangeTaskInfo(value){
        setTaskList(value)
    }

    function submitInfo(){
        const {planName,enableState,selectOperatorList,instro,operateType,percentCompleteLive,percentCompleteVideo,percentCompletePicture,coverId,coverUrl} = basicData;
        let input  = /^[\s]*$/;
        if(!planName || input.test(planName)){
            message.warning('请输入的培训计划名称');
           return;
        }
        if(operateType==='Assign_Operate' && selectOperatorList.length===0){
            message.warning('请选择指定运营师');
            return;
        }
        if(!percentCompleteLive && percentCompleteLive !==0 ){
            message.warning('请输入完成标准');
           return;
        }
        if(!percentCompleteVideo && percentCompleteVideo !==0 ){
            message.warning('请输入完成标准');
           return;
        }
        if(!percentCompletePicture && percentCompletePicture !==0 ){
            message.warning('请输入完成标准');
           return;
        }
        if(taskList.length === 0){
            message.warning('请输入培训计划内容');
            return;
        }
        for(let i=0;i<taskList.length;i++){
            if(input.test(taskList[i].taskName)){
                message.warning('培训任务名称不能为空');
                return false; 
            }
            if(taskList[i].courseList.length === 0){
                Modal.confirm({
                    title: '保存失败',
                    content: '每个任务下至少关联一个课程',
                    okText: '确定',
                    cancelText: '取消',
                    icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
                })
                return false; 
            }
        }
        let scheduleMediaRequests = [];
        let coverObj ={
            contentType:'COVER',
            mediaContent:coverId,
            mediaType:'PICTURE',
            mediaUrl: coverUrl,
        }
        if(coverId){
            scheduleMediaRequests = [...scheduleMediaRequests,coverObj];
        }
        let instroObj = {
            contentType:"INTRO",
            mediaType: 'TEXT',
            mediaContent:instro,
        }
        if(instro){
            scheduleMediaRequests = [...scheduleMediaRequests,instroObj];
        }

        const params = {
            createId:User.getStoreUserId(),
            enableState,
            operateIds:_.pluck(selectOperatorList,'id'),
            operateType,
            percentCompleteLive,
            percentCompleteVideo,
            percentCompletePicture,
            planName,
            scheduleMediaRequests,
            storeId:User.getStoreId(),
            trainingTaskList:handleSubmitTaskData(taskList)
        } 
        if (type === 'add') {
            PlanService.createTrainingPlan(params).then((res) => {
                if (res.success){
                    message.success("新建成功");
                    setSubmitDisabled(true);
                    window.RCHistory.goBack();
                }  
            });
        }else{
            const _params = {
                ...params,
                id
            }
            PlanService.updateTrainingPlan(_params).then((res) => {
                if (res.success){
                    message.success("更新成功");
                    window.RCHistory.goBack();
                }  
            }); 
        }
    }
    function handleSubmitTaskData(taskData){
        return  taskData.map((item,index)=>{
            let _item = {};
            _item.taskId = item.taskId;
            _item.taskName =item.taskName;
            _item.courseList = item.courseList.map((childItem,index)=>{
                let _childItem = {}
                _childItem.courseId = childItem.courseId;
                _childItem.courseName = childItem.courseName;
                _childItem.courseType = childItem.courseType;
                return _childItem;
            });
            return  _item;
        })
    }
  // 取消编辑并返回上一级路由
  function handleGoBack (){
    if (!_.isEqual(basicData, defaultBasicData) || !_.isEqual(taskList, defaultTaskList)
    ) {
      Modal.confirm({
        title: '确定要返回吗？',
        content: '返回后，本次编辑的内容将不被保存',
        okText: '确认返回',
        cancelText: '留在本页',
        icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
        onOk: () =>  {
          window.RCHistory.goBack();
        }
      })
    } else {
      window.RCHistory.goBack();
    }
  }
  
  
  return (
    <div className="page add-plan-page">   
        <Breadcrumbs
            navList={type == "add" ? "新建培训计划" : "编辑培训计划"}
            goBack={handleGoBack}
        />
        <div className="box">
            <div className="show-tips">
                <ShowTips message="请遵守国家相关规定，切勿上传低俗色情、暴力恐怖、谣言诈骗、侵权盗版等相关内容，小麦企学院保有依据国家规定及平台规则进行处理的权利" />
            </div>
            <div className="add-plan-page__form">
                <div className="basic-info__wrap">
                    <div className="title">基本信息</div>
                    <BasicInfo 
                      data={basicData}
                      onChange={handleChangeBasicInfo}
                    />
                </div>
                <div className="basic-info__wrap">
                    <div className="title">培训任务</div>
                    { (type==='edit' && hasGetDetail) &&
                        <TrainingTask data={taskList} onChange={handleChangeTaskInfo} />
                    }
                    { type==='add' &&
                        <TrainingTask data={taskList} onChange={handleChangeTaskInfo} />
                    }
                </div>
                { (type==='edit' && expiredCourseList.length > 0) &&
                    <div className="expired-info__wrap">
                        <div className="title">失效课程</div>
                        <ExpiredCourseList expiredCourseList={expiredCourseList}/>
                    </div>
                }
            </div> 
        </div>
        <div className="footer">
            <Button onClick={handleGoBack}>取消</Button>
            <Button type="primary" onClick={submitInfo} disabled={submitDisabled}>保存</Button>
        </div>
    </div>    
  )

}
export default AddPlan;