package com.yizhi.application.project.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.yizhi.assignment.application.feign.AssignmentClient;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.core.application.task.TaskExecutor;
import com.yizhi.library.application.feign.CaseLibraryClient;
import com.yizhi.training.application.feign.TpPlanClient;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.model.BaseModel;
import com.yizhi.training.application.vo.api.IdVo;
import com.yizhi.training.application.vo.manage.ConditionDeleteVo;
import com.yizhi.training.application.vo.manage.TpPlanSortVo;
import com.yizhi.training.application.vo.manage.TpPlanUpdateVo;
import com.yizhi.training.application.vo.manage.TpPlanVo;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 培训项目 - 学习计划 前端控制器
 * </p>
 *
 * @author shengchenglong
 * @since 2018-03-27
 */
@Api(tags = "培训计划接口")
@RestController
@RequestMapping("/manage/tpPlan")
public class TpPlanController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TpPlanController.class);

    @Autowired
    private TpPlanClient tpPlanClient;

//    @Autowired
//    private SystemMessageClient systemMessageClient;

    @Autowired
    private TrainingProjectClient trainingProjectClient;

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private AssignmentClient assignmentClient;

    @Autowired
    private CaseLibraryClient caseLibraryClient;

    @Autowired
    private CertificateClient certificateClient;


    /**
     * 查询培训项目下的所有培训计划
     *
     * @param trainingProjectId
     * @return
     */
    @GetMapping("/all/list")
    @ApiOperation(value = "培训计划列表", response = TpPlanVo.class)
    public Response<List<TpPlanVo>> listAll(
            @ApiParam(value = "培训项目id", required = true) @RequestParam("trainingProjectId") Long trainingProjectId) {
        try {
            return Response.ok(tpPlanClient.listAll(trainingProjectId));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail("", e.getLocalizedMessage());
        }
    }

    @PostMapping("/sort/update")
    @ApiOperation(value = "培训计划排序修改", notes = "返回修改条数")
    public Response<Integer> updateSort(
            @ApiParam(value = "修改排序的培训计划排序vo", required = true) @RequestBody List<TpPlanSortVo> list) {
        try {
            Date date = new Date();
            RequestContext context = ContextHolder.get();

            if (!CollectionUtils.isEmpty(list)) {
                List<com.yizhi.training.application.vo.domain.TpPlanVo> plans = new ArrayList<>(list.size());

                for (TpPlanSortVo vo : list) {
                    com.yizhi.training.application.vo.domain.TpPlanVo plan = new com.yizhi.training.application.vo.domain.TpPlanVo();
                    plan.setId(vo.getId());
                    plan.setSort(vo.getSort());

                    plan.setUpdateById(context.getAccountId());
                    plan.setUpdateByName(context.getAccountName());
                    plan.setUpdateTime(date);
                    plans.add(plan);
                }
                return Response.ok(tpPlanClient.updateSort(plans));
            }
            return Response.fail(InternationalEnums.TPPLANACTIVITYCONTROLLER1.getCode());
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail("", e.getLocalizedMessage());
        }
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增培训计划（包括计划中的活动和条件等）")
    public Response<com.yizhi.training.application.vo.domain.TpPlanVo> save(
            @ApiParam(value = "培训计划vo", required = true) @RequestBody TpPlanVo tpPlanVo) {
        try {
            SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            
            if(StringUtils.isEmpty(tpPlanVo.getName()) || tpPlanVo.getStartTime() == null || tpPlanVo.getEndTime() == null){
            	com.yizhi.training.application.vo.domain.TrainingProjectVo trainingProjectVo = trainingProjectClient.getOne(tpPlanVo.getTrainingProjectId());
            	if (CollectionUtils.isEmpty(tpPlanVo.getActivities())) {
            		tpPlanVo.setName(tpPlanVo.getName());
            	} else {
            		tpPlanVo.setName(tpPlanVo.getActivities().get(0).getName());
            	}
            	
            	tpPlanVo.setStartTime(trainingProjectVo.getStartTime());
            	tpPlanVo.setEndTime(trainingProjectVo.getEndTime());
            }
            
            BaseModel<TpPlanVo> model = new BaseModel<>();
            model.setObj(tpPlanVo);
            model.setContext(ContextHolder.get());
            model.setDate(new Date());
            com.yizhi.training.application.vo.domain.TpPlanVo tpPlan = tpPlanClient.save(model);

            // if (tpPlan != null && StringUtils.isEmpty(tpPlan.getSubMsg())) {
            //     com.yizhi.training.application.vo.domain.TrainingProjectVo project = trainingProjectClient.getOne(tpPlanVo.getTrainingProjectId());
            //     List<TpPlanActivityVo> activities = tpPlanVo.getActivities();
            //     if (!CollectionUtils.isEmpty(activities)) {
            //         // 循环处理作业关联关系
            //         //加上案例活动关联
            //         taskExecutor.asynExecute(new AbstractTaskHandler() {
            //             @Override
            //             public void handle() {
            //                 List<Long> assignmentIds = new ArrayList<>();
            //                 List<Long> caseLibraryIds = new ArrayList<>();
            //                 List<Long> certificateIds = new ArrayList<>();
            //                 for (TpPlanActivityVo vo : activities) {
            //                     if (vo.getType().equals(TpActivityType.TYPE_ASSIGNMENT)) {
            //                         assignmentIds.add(vo.getRelationId());
            //                     } else if (vo.getType().equals(TpActivityType.TYPE_CASE_ACTIVITY)) {
            //                         caseLibraryIds.add(vo.getRelationId());
            //                     } else if (vo.getType().equals(TpActivityType.TYPE_CERTIFICATE)) {
            //                         certificateIds.add(vo.getRelationId());
            //                     }
            //                 }
            //                 if (!CollectionUtils.isEmpty(assignmentIds)) {
            //                     AssignmentTrainingProject assignmentTrainingProject = new AssignmentTrainingProject();
            //                     assignmentTrainingProject.setListAssignmentIds(assignmentIds);
            //                     assignmentTrainingProject.setProjectId(project.getId());
            //                     assignmentTrainingProject.setProjectName(project.getName());
            //                     assignmentClient.updateTrainingProjectByAssignmentId(assignmentTrainingProject);
            //                 }
            //                 //关联案例库
            //                 if (!CollectionUtils.isEmpty(caseLibraryIds)) {
            //                     RelateProjectParam relateProjectParam = new RelateProjectParam();
            //                     relateProjectParam.setCaseLibraryIds(caseLibraryIds);
            //                     relateProjectParam.setProjectId(project.getId());
            //                     caseLibraryClient.relateProject(relateProjectParam);
            //                 }
            //                 //关联证书
            //                 if (!CollectionUtils.isEmpty(certificateIds)) {
            //                     RelateCertificateParam relateCertificateParam = new RelateCertificateParam();
            //                     relateCertificateParam.setTpPlanId(tpPlan.getId());
            //                     relateCertificateParam.setTpPlanName(tpPlan.getName());
            //                     relateCertificateParam.setBizdId(project.getId());
            //                     relateCertificateParam.setBizdName(project.getName());
            //                     relateCertificateParam.setType(0);
            //                     relateCertificateParam.setCertificateIds(certificateIds);
            //                     certificateClient.relateProject(relateCertificateParam);
            //                 }
            //             }
            //         });
            //     }
            // } else {
            //     return Response.fail(tpPlan.getSubMsg());
            // }
            return Response.ok(tpPlan);
        } catch (Exception e) {
            LOGGER.error("", e);
            String msg = e.getMessage();
            msg = msg.substring(msg.indexOf(":") + 1);
            Map<String, String> map = (Map<String, String>) JSON.parse(msg);
            return Response.fail("4001", map.get("message"));
        }
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改培训计划（包括计划的条件）", response = com.yizhi.training.application.vo.domain.TpPlanVo.class)
    public Response<com.yizhi.training.application.vo.domain.TpPlanVo> update(
            @ApiParam(value = "培训计划修改vo", required = true) @RequestBody TpPlanUpdateVo tpPlanUpdateVo) {
        try {
            BaseModel<TpPlanUpdateVo> model = new BaseModel<>();
            model.setObj(tpPlanUpdateVo);
            model.setContext(ContextHolder.get());
            model.setDate(new Date());
            com.yizhi.training.application.vo.domain.TpPlanVo tpPlanVo = tpPlanClient.update(model);
            if (ObjectUtil.isNotNull(tpPlanVo)&&tpPlanVo.getSubMsg()==null) {
                return Response.ok(tpPlanClient.update(model));
            }else {
                return Response.fail(tpPlanVo.getSubMsg());
            }
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail();
        }
    }

    @PostMapping("/condition/delete")
    @ApiOperation(value = "删除前置 或 后置条件")
    public Response<Integer> deleteConditions(
            @ApiParam(value = "待删除的条件id集合", required = true) @RequestBody ConditionDeleteVo conditionDeleteVo) {
        try {
            BaseModel<ConditionDeleteVo> model = new BaseModel<>();
            model.setContext(ContextHolder.get());
            model.setDate(new Date());
            model.setObj(conditionDeleteVo);

            return Response.ok(tpPlanClient.deleteConditions(model));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail("", e.getLocalizedMessage());
        }
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除学习计划")
    public Response delete(
            @ApiParam(value = "学习计划id集合", required = true) @RequestBody List<Long> ids) {
        try {
            BaseModel<List<Long>> model = new BaseModel<>();
            model.setContext(ContextHolder.get());
            model.setDate(new Date());
            model.setObj(ids);

            //add by hutao
            int i = tpPlanClient.batchDelete(model);
            if (i == -1) {
                //该计划已被其他计划作为前置计划所依赖，不能删除！！！
                return Response.fail("", InternationalEnums.TPPLANCONTROLLER1.getCode());
            }
            /*if (i > 0) {
                certificateClient.cancelRelate(0, null, null, ids.get(0));
            }*/


            return Response.ok(i);
            //
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail("", e.getLocalizedMessage());
        }

    }

    @ApiOperation(value = "查看培训计划的内容（包括提醒、前置计划、完成条件）", response = com.yizhi.training.application.vo.domain.TpPlanVo.class)
    @GetMapping("detail/view")
    public Response<com.yizhi.training.application.vo.domain.TpPlanVo> viewDetail(@RequestParam("planId") Long planId) {

        try {
            return Response.ok(tpPlanClient.viewDetail(planId));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail("", e.getLocalizedMessage());
        }
    }

    @ApiOperation(value = "根据计划id清空计划活动（包括条件等）")
    @PostMapping("/truncate/activity")
    public Response<Integer> truncateActivity(@RequestBody IdVo vo) {
        try {
            if (null == vo.getId()) {
                return Response.fail("4001", InternationalEnums.TPPLANCONTROLLER2.getCode());
            } else {
                BaseModel<Long> model = new BaseModel<>();
                model.setDate(new Date());
                model.setContext(ContextHolder.get());
                model.setObj(vo.getId());
                return Response.ok(tpPlanClient.truncateActivity(model));
            }
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail("", e.getLocalizedMessage());
        }
    }

    /**
     * 提醒关键字替换
     *
     * @param value
     */
    private String replaceContent(String value, String name, String trainingProjectName, String startTime) {
        if (!StringUtils.isEmpty(value)) {
            value = value.replace("{项目名称}", trainingProjectName);
            value = value.replace("{学习计划名称}", name);
            value = value.replace("{开始时间}", startTime);
        }
        return value;
    }

    @GetMapping("/move")
    @ApiOperation(value = "培训计划上下移")
    public Response update(@ApiParam("type；1-上移  2-下移 必填") @RequestParam("type") Integer type,
                           @ApiParam("计划id必填") @RequestParam("id") Long id) {
        com.yizhi.training.application.vo.domain.TpPlanVo vo = tpPlanClient.getOne(id);
        String result = "";
        if (vo == null) {
            result = InternationalEnums.TPPLANCONTROLLER7.getCode();
            return Response.fail(result);
        }
        Integer move = tpPlanClient.move(type, id);
        switch (move) {
            case 1:
                result = InternationalEnums.TPPLANCONTROLLER3.getCode();
                return Response.ok(result);
            case -1:
                result = InternationalEnums.TPPLANCONTROLLER4.getCode();
                break;
            case -2:
                result = InternationalEnums.TPPLANCONTROLLER5.getCode();
                break;
            case 0:
                result = InternationalEnums.TPPLANCONTROLLER6.getCode();
                break;
        }
        return Response.fail(result);
    }

}

