/*
 * @Author: zhangleyuan
 * @Date: 2021-02-20 16:13:39
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-03-09 16:54:56
 * @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,
   
}
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([]);
    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,
                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 = [];
            _selectOperatorList = operateIds.map((item,index)=>{
                let _item = {};
                _item.id = item;
                return _item
            })
            setBasicData({
                planName,
                coverUrl:coverUrl || defaultCover,
                coverId,
                enableState,
                selectOperatorList:_selectOperatorList,
                instro,
                operateType,
                percentCompleteLive,
                percentCompleteVideo
            })
            setTaskList(trainingTaskList)
        })
    }
    function handleChangeBasicInfo(field, value){
        setBasicData( {
            ...basicData,
            [field]: value,
        })
    }

    function handleChangeTaskInfo(value){
        setTaskList(value)
    }

    function submitInfo(){
        const {planName,enableState,selectOperatorList,instro,operateType,percentCompleteLive,percentCompleteVideo,coverId,coverUrl} = basicData;
        if(!planName){
            message.warning('请输入的培训计划名称');
           return;
        }
        if(taskList.length === 0){
            message.warning('请输入培训计划内容');
            return;
        }
        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,
            planName,
            scheduleMediaRequests,
            storeId:User.getStoreId(),
            trainingTaskList:handleSubmitTaskData(taskList)
        } 
        if (type === 'add') {
            PlanService.createTrainingPlan(params).then((res) => {
                if (res.success){
                    message.success("新建成功");
                    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' && taskList.length>0) &&
                        <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>取消</Button>
            <Button type="primary" onClick={submitInfo}>保存</Button>
        </div>
    </div>    
  )

}
export default AddPlan;