package com.yizhi.application.project.controller;


import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.assignment.application.feign.AssignmentClient;
import com.yizhi.assignment.application.vo.apivo.AssignmentTrainingProject;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.certificate.application.vo.RelateCertificateParam;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.task.AbstractTaskHandler;
import com.yizhi.core.application.task.TaskExecutor;
import com.yizhi.library.application.feign.CaseLibraryClient;
import com.yizhi.library.application.param.ProjectDeleteParam;
import com.yizhi.library.application.param.RelateProjectParam;
import com.yizhi.training.application.feign.TpPlanActivityClient;
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.domain.TpPlanActivityVo;
import com.yizhi.training.application.vo.domain.TpPlanVo;
import com.yizhi.training.application.vo.domain.TrainingProjectVo;
import com.yizhi.training.application.vo.manage.ConditionDeleteVo;
import com.yizhi.training.application.vo.manage.TpPlanActivityConditionUpdateVo;
import com.yizhi.training.application.vo.manage.TpPlanActivitySingleVo;
import com.yizhi.training.application.vo.manage.TpPlanActivitySortVo;
import com.yizhi.util.application.constant.TpActivityType;
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.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 学习计划中的活动 前端控制器
 * </p>
 *
 * @author shengchenglong
 * @since 2018-03-27
 */
@Api(tags = "培训活动接口")
@RestController
@RequestMapping("/manage/tpPlanActivity")
public class TpPlanActivityController {

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

    @Autowired
    private TpPlanActivityClient tpPlanActivityClient;
    @Autowired
    private AssignmentClient assignmentClient;
    @Autowired
    private TrainingProjectClient trainingProjectClient;
    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private CaseLibraryClient caseLibraryClient;
    @Autowired
    private CertificateClient certificateClient;
    @Autowired
    private TpPlanClient tpPlanClient;
    @Value("${pc.host.url}")
    String pcHostUrl;


    @GetMapping("/all/list")
    @ApiOperation(value = "查询培训活动列表", response = TpPlanActivityVo.class)
    public Response<List<TpPlanActivityVo>> allList(
            @ApiParam(value = "所属培训计划的id, 必填", required = true) @RequestParam("tpPlanId") Long tpPlanId,
            @ApiParam(value = "模糊查询的name") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "活动类型： 0课程 1考试 2调研 3直播 4投票 5作业 6证书 7外部链接") @RequestParam(value = "type", required = false) Integer type
    ) {
        try {
            return Response.ok(tpPlanActivityClient.allList(tpPlanId, name, type));
        } 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<TpPlanActivitySortVo> list) {
        try {
            Date date = new Date();
            RequestContext context = ContextHolder.get();

            if (!CollectionUtils.isEmpty(list)) {
                List<TpPlanActivityVo> planActivities = new ArrayList<TpPlanActivityVo>(list.size());

                for (TpPlanActivitySortVo vo : list) {
                    TpPlanActivityVo planActivity = new TpPlanActivityVo();

                    planActivity.setId(vo.getId());
                    planActivity.setSort(vo.getSort());

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

    @PostMapping("/condition/edit")
    @ApiOperation(value = "编辑培训活动开启、完成条件", notes = "返回修改条数")
    public Response<Integer> conditionEdit(
            @ApiParam(value = "培训活动开启、完成条件") @RequestBody TpPlanActivityConditionUpdateVo activityConditionVo) {
        try {
            BaseModel<TpPlanActivityConditionUpdateVo> model = new BaseModel<>();
            model.setDate(new Date());
            model.setContext(ContextHolder.get());
            model.setObj(activityConditionVo);
            return Response.ok(tpPlanActivityClient.conditionEdit(model));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail("", e.getLocalizedMessage());
        }
    }

    @PostMapping("/delete")
    @ApiOperation(value = "在修改培训计划时，若有移除培训活动，使用该接口。包括开启、完成条件", notes = "返回修改条数")
    public Response<Integer> delete(
            @ApiParam(value = "培训活动id集合") @RequestBody ProjectDeleteParam projectDeleteParam) {
        try {
            BaseModel<List<Long>> model = new BaseModel<>();
            model.setDate(new Date());
            model.setContext(ContextHolder.get());
            model.setObj(projectDeleteParam.getIds());
            TpPlanActivityVo tpPlanActivity = null;
            if (!CollectionUtils.isEmpty(projectDeleteParam.getIds())) {
                tpPlanActivity = tpPlanActivityClient.getOne(projectDeleteParam.getIds().get(0));
            }
            Integer result = tpPlanActivityClient.batchDelete(model);
            //如果是证书,需要取消关联状态
            /*if (result > 0) {
                if (null != tpPlanActivity) {
                    certificateClient.cancelRelate(0, tpPlanActivity.getRelationId(), tpPlanActivity.getTrainingProjectId(), tpPlanActivity.getTpPlanId());
                }
            }*/
            return Response.ok(result);
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail("", e.getLocalizedMessage());
        }
    }

    @PostMapping("/save")
    @ApiOperation(value = "修改培训计划时，添加学习活动", notes = "添加的学习活动", response = TpPlanActivityVo.class)
    public Response<Integer> addOne(
            @ApiParam(value = "培训活动单个添加vo") @RequestBody List<TpPlanActivitySingleVo> activitySingleVos) {
        try {
            BaseModel<List<TpPlanActivitySingleVo>> model = new BaseModel<>();
            model.setDate(new Date());
            model.setContext(ContextHolder.get());
            model.setObj(activitySingleVos);
            Integer num = tpPlanActivityClient.addOne(model);

            Long projectId = activitySingleVos.get(0).getProjectId();
            Long tpPlanId = activitySingleVos.get(0).getPlanId();

            // 循环处理作业关联关系
            taskExecutor.asynExecute(new AbstractTaskHandler() {
                @Override
                public void handle() {
                    if (!CollectionUtils.isEmpty(activitySingleVos)) {
                        List<Long> assignmentIds = new ArrayList<>();
                        List<Long> caseLibraryIds = new ArrayList<>();
                        List<Long> certificateIds = new ArrayList<>();
                        for (TpPlanActivitySingleVo vo : activitySingleVos) {
                            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(activitySingleVos.get(0).getProjectId());
                            assignmentTrainingProject.setProjectName(trainingProjectClient.getOne(activitySingleVos.get(0).getProjectId()).getName());
                            assignmentClient.updateTrainingProjectByAssignmentId(assignmentTrainingProject);
                        }
                        //修改培训计划时，添加学习活动
                        if (null != tpPlanId) {

                            //案例活动关联培训项目id
                            if (!CollectionUtils.isEmpty(caseLibraryIds)) {
                                RelateProjectParam relateProjectParam = new RelateProjectParam();
                                relateProjectParam.setProjectId(projectId);
                                relateProjectParam.setCaseLibraryIds(caseLibraryIds);
                                caseLibraryClient.relateProject(relateProjectParam);
                            }
                            //证书关联培训项目id
                            if (!CollectionUtils.isEmpty(certificateIds)) {
                                TrainingProjectVo trainingProject = trainingProjectClient.getOne(projectId);
                                TpPlanVo tpPlan = tpPlanClient.getOne(tpPlanId);


                                RelateCertificateParam relateCertificateParam = new RelateCertificateParam();
                                if (null != trainingProject) {
                                    relateCertificateParam.setBizdName(trainingProject.getName());
                                }
                                if (null != tpPlan) {
                                    relateCertificateParam.setTpPlanName(tpPlan.getName());
                                }
                                relateCertificateParam.setBizdId(projectId);
                                relateCertificateParam.setTpPlanId(tpPlanId);
                                relateCertificateParam.setCertificateIds(certificateIds);
                                //0为培训项目
                                relateCertificateParam.setType(0);
                                certificateClient.relateProject(relateCertificateParam);
                            }
                        }


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

    @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(tpPlanActivityClient.deleteConditions(model));
        } catch (Exception e) {
            LOGGER.error("", e);
            return Response.fail("", e.getLocalizedMessage());
        }
    }


    @GetMapping("/activitiesExport")
    @ApiOperation(value = "导出项目活动清单")
    public Response<String> activitiesExport(@ApiParam("培训id") @RequestParam("tpId") Long tpId) {
        RequestContext context = ContextHolder.get();

        if (tpId == null || tpId == 0) {
            return Response.fail(InternationalEnums.TPPLANACTIVITYCONTROLLER2.getCode());
        }
        TrainingProjectVo one = trainingProjectClient.getOne(tpId);
        if (one == null) {
            return Response.fail(InternationalEnums.TPPLANACTIVITYCONTROLLER3.getCode());
        }
        Long taskId = System.currentTimeMillis();
        String taskName = one.getName() + "项目活动清单" + "_" + taskId.toString();
        Map<String, Object> map = new HashMap<String, Object>();
        String serialNo = "TRAININGACTIVITIES-EXPORT-" + taskId.toString();
        map.put("taskId", taskId);
        map.put("taskName", taskName);
        map.put("serialNo", serialNo);
//        context.setOrgId(1314l);
//        context.setSiteId(1314l);
//        context.setCompanyId(1314l);
//        context.setAccountName("taoge");
//        context.setAccountId(1314l);
        map.put("context", context);
        map.put("trainingProject", one);

        tpPlanActivityClient.activitiesExport(map);
        String fileUril = pcHostUrl+"/api/v1/buckets/upload/objects/download/?preview=true&prefix="+taskName+".xlsx";
        return Response.ok(fileUril);
    }

}

