package com.yizhi.application.course.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.tools.PageTools;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.event.EventWrapper;
import com.yizhi.core.application.publish.CloudEventPublisher;
import com.yizhi.core.application.task.AbstractTaskHandler;
import com.yizhi.core.application.task.TaskExecutor;
import com.yizhi.course.application.feign.*;
import com.yizhi.course.application.vo.*;
import com.yizhi.course.application.vo.domain.ChapterEntityVo;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.course.application.vo.domain.MaterialEntityVo;
import com.yizhi.course.application.vo.domain.RecordeEntityVo;
import com.yizhi.point.application.feign.PointRedisFeignClients;
import com.yizhi.point.application.vo.PointParamVO;
import com.yizhi.util.application.constant.QueueConstant;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.event.TrainingProjectEvent;
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.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(tags = "学员端端-课程完成记录", description = "课程完成记录接口")
@RestController
@RequestMapping("/api/recorde")
public class RecordeStuController {

    private final Logger LOG = LoggerFactory.getLogger(RecordeStuController.class);

    @Autowired
    RecordeClient recordeClient;

    @Autowired
    PointRedisFeignClients pointRedisFeignClients;
/*
    @Autowired
    AmqpTemplate amqpTemplate;*/
    @Autowired
    CourseClient courseClient;
    @Autowired
    MaterialClient materialClient;
    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private CloudEventPublisher cloudEventPublisher;
    @Autowired
    private CourseStudyClient courseStudyClient;
    @Autowired
    private CoursePcClient coursePcClient;



    @ApiOperation(value = "我的学习记录", response = RecordeListVo.class)
    @GetMapping("/list")
    public Response<List<RecordeListVo>> getMyCourseRecordeList(
            @ApiParam(name = "courseId", value = "课程id") @RequestParam(name = "courseId") Long courseId
    ) {
        RequestContext requestContext = ContextHolder.get();
        return Response.ok(recordeClient.getMyRecorde(courseId, requestContext.getAccountId()));
    }

    @ApiOperation(value = "我的已学习的课程", response = MyCourseRecordeVo.class)
    @GetMapping("/my/list")
    public Response<MyCourseRecordeVo> getMyCourseRecordeList(
            @ApiParam(name = "name", value = "搜索", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(name = "type", value = "课程是否完成 0 为进行中 1 为已完成 ,不传则查询所有", required = false) @RequestParam(name = "type", required = false, defaultValue = "2") Integer type,
            @ApiParam(name = "pageNo") @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize") @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize,
            @ApiParam(name = "startDate" ,value="开始时间", required=false) @RequestParam(name = "startDate", required=false) Long startDate,
            @ApiParam(name = "endDate",value="结束时间", required=false) @RequestParam(name = "endDate", required=false) Long endDate
    ) {
        /*RequestContext requestContext = ContextHolder.get();
        Page<MyCourseRecordeVo> list = recordeClient.getMyCourseRecordeList(name, requestContext.getAccountId(), type, pageNo, pageSize);

        Map<String, Integer> page = new HashMap<String, Integer>();
        page.put("pageNo", pageNo);
        page.put("pageSize", pageSize);
        page.put("pageTotal", list.getTotal());
        return Response.ok(list.getRecords(), page);*/
        RequestContext rt = ContextHolder.get();
        LOG.info("开始时间{},结束时间{}",startDate,endDate);
        Page<MyCourseRecordeVo> data = coursePcClient.getMyCourseStudyList(
                rt.getSiteId(),rt.getAccountId(),name,type,pageNo,pageSize,startDate,endDate);

        return Response.ok(PageTools.split(data));
    }


    @ApiOperation(value = "课程章节完成记录")
    @PostMapping("/completed")
    public Response recordeCompleted(@RequestBody RecordeEntityVo recorde) {

        RequestContext requestContext = ContextHolder.get();
        recorde.setAccountId(requestContext.getAccountId());
        recorde.setCompanyId(requestContext.getCompanyId());
        recorde.setSiteId(requestContext.getSiteId());
        recorde.setCreateTime(new Date());
        Integer duration = recorde.getDuration();
        recorde.setDuration(0);
        if(Objects.nonNull(duration)){
            recorde.setDuration(duration);
        }
        recorde.setStartTime(new Date());
        recorde.setEndTime(new Date());
        recorde.setOrgId(requestContext.getOrgId());
        recorde.setValid(1);
        recorde.setExitstates(1);
        String sessionId = recorde.getSessionId();
        if(StringUtils.isEmpty(sessionId)){
            recorde.setSessionId("AUTO-"+UUID.randomUUID().toString());
        }
        Integer overed = recorde.getOvered();
        if(Objects.isNull(overed)){
            recorde.setOvered(0);
        }
        // 保存完成状态
        Boolean ret = recordeClient.completedSave(recorde);
        if(Boolean.FALSE.equals(ret)){
            return Response.fail();
        }
        return Response.ok();
    }

    private void getPoint(Long chapterId, String accountName, 
    		Long accountId, Long companyId, Long siteId, Long orgId) {
        try {
            ChapterEntityVo chapter = courseClient.chapterGet(chapterId);
            if (!StringUtils.isEmpty(chapter)) {
                MaterialEntityVo material = materialClient.view(chapter.getMaterialId());
                if (!StringUtils.isEmpty(material)) {

                    PointParamVO pointParamVO = new PointParamVO();
                    //事件名称
                    pointParamVO.setEventName("pointCourse");
                    //事件类型
                    pointParamVO.setActivityType("课程章节完成发放积分");
                    //学习活动来源
                    pointParamVO.setActivitySource("课程");
                    //学习活动名
                    StringBuilder activityName = new StringBuilder();

                    CourseEntityVo course = courseClient.view(chapter.getCourseId());
                    if (!StringUtils.isEmpty(course)) {
                        activityName.append(course.getName());
                        activityName.append(":");
                    }
                    activityName.append(chapter.getName());
                    pointParamVO.setActivityName(activityName.toString());
                    //发放条件
                    pointParamVO.setReleaseCondition("课程章节完成发放");
                    //发放规则
                    pointParamVO.setReleaseRules("按照章节获取取积分");
                    //积分创建时间
                    pointParamVO.setCreatePointTime(new Date());
                    //积分来源ID，（业务ID主键）
                    pointParamVO.setSourceId(chapter.getId());
                    //积分数量，  正数 加积分，  负数减积分
                    pointParamVO.setOperatingPoint(chapter.getScore());
                    //学员ID
                    pointParamVO.setAccountId(accountId);
                    //学员名称
                    pointParamVO.setAccountName(accountName);
                    pointParamVO.setSiteId(siteId);
                    pointParamVO.setCompanyId(companyId);
                    pointParamVO.setOrgId(orgId);
                    //调用积分接口添加积分
                    String sitePointId = pointRedisFeignClients.addPointRedis(pointParamVO);
                    if (null != sitePointId) {
                        //发送积分获取消息
                        //amqpTemplate.convertAndSend("course", sitePointId);
                    }
                }

            }
        } catch (Exception e) {
            LOG.error("章节" + chapterId + "积分消息发送失败！");
        }

    }

    /**
     * 给项目发送课程完成消息
     */
    private void toProject(RecordeVO recorde, Long siteId) {
        taskExecutor.asynExecute(new AbstractTaskHandler() {
            @Override
            public void handle() {
                try {
                    String key = recorde.getCourseId() + "_" + recorde.getAccountId();
                    LOG.info("key: " + key);
                    Set<String> set = new HashSet<>();
                    set.add(key);
                    Boolean flag = courseClient.isCourseFinished(set, true).get(key);
                    flag = flag == null ? false : flag;
                    LOG.info("flag: " + flag);

                    cloudEventPublisher.publish(QueueConstant.TRAINING_PROJECT_EVENT_QUEUE, new EventWrapper<TrainingProjectEvent>(recorde.getCourseId(),
                            TrainingProjectEvent.getInstanceCourse(recorde.getCourseId(), recorde.getAccountId(), new Date(),
                                    recorde.getDuration().longValue(), flag, siteId)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
