package com.yizhi.application.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.album.application.feign.AlbumClient;
import com.yizhi.application.calendarTask.CalendarTaskController;
import com.yizhi.application.vo.CalendarTask;
import com.yizhi.assignment.application.feign.AssignmentStudentClient;
import com.yizhi.certificate.application.feign.CertificateAppClient;
import com.yizhi.comment.application.feign.SubscribeClient;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.exception.BizException;
import com.yizhi.course.application.feign.*;
import com.yizhi.course.application.vo.MyCourseStudyCountVo;
import com.yizhi.exam.application.feign.ExamApiClient;
import com.yizhi.library.application.feign.StudentCaseClient;
import com.yizhi.mall.application.feign.TokenControllerClient;
import com.yizhi.point.application.feign.PointDetailsFeignClients;
import com.yizhi.point.application.feign.PointUserFeignClients;
import com.yizhi.practice.application.feign.MyPracticeStudentClient;
import com.yizhi.research.application.feign.ResearchClient;
import com.yizhi.sign.application.feign.SignRecordApiClient;
import com.yizhi.site.application.feign.api.MyItemConfigApiClients;
import com.yizhi.site.application.feign.api.MyItemConfigDefaultApiClients;
import com.yizhi.site.application.vo.site.MyItemConfigVO;
import com.yizhi.statistics.application.feign.StudentReportClient;
import com.yizhi.system.application.enums.ItemCode;
import com.yizhi.system.application.enums.ItemPcCode;
import com.yizhi.system.application.enums.ItemPcaddUrl;
import com.yizhi.system.application.vo.MyItemVO;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.model.BaseModel;
import com.yizhi.training.application.vo.api.CalendarTaskParamVo;
import com.yizhi.training.application.vo.api.TrainingProjectParamVo;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.BizResponse;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 系统中台控制器
 *
 * @author yinyuyan
 * @create 2018/4/3
 * @since 1.0.0
 */

@Api(tags = "基础服务接口", description = "基础服务接口")
@RestController
@RequestMapping("/api/system")
public class SystemController {

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

    @Autowired
    SignRecordApiClient signRecordApiClient;
    @Autowired
    CourseClient courseClient;
    @Autowired
    PointUserFeignClients pointClient;
    @Autowired
    AssignmentStudentClient assignmentClient;
    @Autowired
    ExamApiClient examClient;
    @Autowired
    CertificateAppClient certificateClient;
    //    @Autowired
//    VoteClient voteClient;
    @Autowired
    MarketingCourseClient marketingCourseClient;
    @Autowired
    TrainingProjectClient trainingProjectClient;
    @Autowired
    LessonClient lessonClient;
    @Autowired
    RecordeClient recordeClient;
    @Autowired
    ResearchClient researchClient;
    @Autowired
    CoursePcClient coursePcClient;
    @Autowired
    PointDetailsFeignClients pointDetailsFeignClients;
    @Autowired
    private MyItemConfigApiClients myItemConfigApiClients;
    @Autowired
    private MyItemConfigDefaultApiClients myItemConfigDefaultApiClients;
    @Autowired
    private CourseStudyHourClient courseStudyHourClient;
    @Autowired
    private StudentCaseClient studentCaseClient;
    @Autowired
    private CalendarTaskController calendarTaskController;
    @Autowired
    private StudentReportClient studentReportClient;
    @Autowired
    private SubscribeClient subscribeClient;
    @Autowired
    private AlbumClient albumClient;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private MyPracticeStudentClient myPracticeStudentClient;
    @Autowired
    private TokenControllerClient tokenControllerClient;

    @ApiOperation(value = "获取我的业务汇总信息", notes = "我的积分总数，我的课程学习总数")
    @GetMapping("/my/business/collect")
    public Response<Map<String, Object>> getMyBusinessCollec() {


        RequestContext rt = ContextHolder.get();
        Map<String, Object> data = new HashMap<>();
        data.put("studyDuration", 0); //课程学习时长
        data.put("pointDetails", 0); // 积分总数
        data.put("studyCourseDuration", 0); // 学习的总课时
        // 我的学习时长统计
        Object studyDuration = null;
        try {
            studyDuration = recordeClient.countStudyDuration(rt.getAccountId(), rt.getSiteId(), null);
            if (Objects.nonNull(studyDuration)) {
                data.put("studyDuration", studyDuration);
            }
        } catch (Exception e) {
            LOG.info(JSON.toJSONString(e));
        }
        // 我的学习总课时
        try {
            Float studyCourseDuration = courseStudyHourClient.hourStatistics(rt.getSiteId()
                    , rt.getAccountId(), null);
            data.put("studyCourseDuration", studyCourseDuration);
        } catch (Exception e) {
            LOG.info(JSON.toJSONString(e));
        }
        // 我的积分统计
        Object pointDetails = null;
        try {
            pointDetails = pointDetailsFeignClients.queryPiont(rt.getAccountId(),
                    rt.getCompanyId(), rt.getSiteId(), null);
            if (Objects.nonNull(pointDetails)) {
                data.put("pointDetails", pointDetails);
            }
        } catch (Exception e) {
            LOG.info(JSON.toJSONString(e));
        }

        Boolean courseDurationShow = false;
        List<Integer> terminalType = new ArrayList<>();
        terminalType.add(3);
        List<MyItemConfigVO> voList = myItemConfigApiClients.queryByAuthoity(terminalType);
        //如果我的配置表没有数据，取默认表里的数据
        if (CollectionUtils.isEmpty(voList)) {
            voList = myItemConfigDefaultApiClients.queryByAuthoity(terminalType);
        }
        for (MyItemConfigVO vo : voList) {
            if (vo.getItemType() == 14) {
                if (vo.getShowable() == 1) {
                    courseDurationShow = true;
                }
            }
        }
        data.put("courseDurationShow", courseDurationShow); // 学习学时是否显示

        return Response.ok(data);
    }

    /**
     * 我的列表
     *
     * @return
     */
    @ApiOperation(value = "我的首页列表", notes = "我的消息首页")
    @PostMapping("/my/item")
    public Response<Map<String, List<MyItemVO>>> list() {
        RequestContext context = ContextHolder.get();
        Map<String, Object> items = new HashMap<>();
        List<Integer> terminalType = Arrays.asList(2, 3);
        List<MyItemConfigVO> voList = myItemConfigApiClients.queryByAuthoity(terminalType);
        //如果我的配置表没有数据，取默认表里的数据
        if (voList == null) {
            voList = myItemConfigDefaultApiClients.queryByAuthoity(terminalType);
        }
        try {
            Map<String, MyItemVO> data1 = new HashMap<>();
            List<MyItemVO> data2 = new ArrayList<>();
            //库中数据获取
            getApiData(voList, context, data2);
            //写死的数据
            getApiStableData(data2, data1, context);
            items.put("data1", data1);
            items.put("data2", data2);
            return Response.ok(items);
        } catch (BizException be) {
            return Response.fail(be.getCode(), be.getCode());
        }

    }

    /**
     * 写死的数据
     */
    private void getApiStableData(List<MyItemVO> data2, Map<String, MyItemVO> data1, RequestContext context) {
        //我的消息
        Integer sum = null;
        try {
        	/*//2024-11-2需求不需要统计数据，先注释
        	sum = messageClient.unreadCount(ContextHolder.get().getAccountId());*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*MyItemVO xx = new MyItemVO(ItemCode.XX.getCode(), ItemCode.XX.getName(), sum == null ? 0 : sum);
        if (!data2.contains(xx)) {
            data2.add(xx);
        }*/
        //课程收藏
        Integer courseCount = 0;
        
        /*//2024-11-2需求不需要统计数据，先注释
        try {
            courseCount = courseClient.getMyFavoriteCount(context.getAccountId(), context.getCompanyId(), context.getSiteId());
            Integer courseCount1 = studentCaseClient.getFavoritesCount(context.getCompanyId(), context.getSiteId(), context.getAccountId());
            if (Objects.nonNull(courseCount)) {
                courseCount += courseCount1;
            } else {
                courseCount = courseCount1;
            }
        } catch (Exception e) {
            LOG.info("异常信息={}", e);
        }*/
        MyItemVO kcsc = new MyItemVO(ItemCode.KCSC.getCode(), ItemCode.KCSC.getName(), courseCount == null ? 0 : courseCount);
        data1.put(ItemCode.KCSC.getCode(), kcsc);
    }

    /**
     * 从库中获取微信端的我的数据
     *
     * @param voList
     */
    private void getApiData(List<MyItemConfigVO> voList, RequestContext context, List<MyItemVO> data2) {
        for (MyItemConfigVO vo : voList) {
            MyItemVO item = new MyItemVO();
            
            /*//2024-11-2需求不需要统计数据，先注释
            switch (vo.getItemType()) {
                case 1://我的培训
                    BaseModel<TrainingProjectParamVo> model = new BaseModel<>();
                    model.setContext(context);
                    Integer projectCount = null;
                    try {
                        projectCount = trainingProjectClient.getMyTrainingProjectCountNum(model);
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    item.setQuantity(projectCount == null ? 0 : projectCount);
                    break;
                case 2://我的课程
                    MyCourseStudyCountVo voTemp = null;
                    try {
                        voTemp = coursePcClient.getMyCourseStudyCount(context.getSiteId(), context.getAccountId());
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    Integer recordeCount = voTemp.getStudyingCountNum();
                    item.setQuantity(recordeCount == null ? 0 : recordeCount);
                    break;
                case 3://我的作业
                    Integer assignmentCount = null;
                    try {
                        assignmentCount = assignmentClient.getAssignmentNumByAccountId(context.getRelationIds(), context.getSiteId(), context.getAccountId());
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    item.setQuantity(assignmentCount == null ? 0 : assignmentCount);
                    break;
                case 4://我的考试
                    Integer examCount = null;
                    try {
                        examCount = examClient.selectCountByAccountId(context.getAccountId());
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    item.setQuantity(examCount == null ? 0 : examCount);
                    break;
                case 5://我的调研
                    Integer research = null;
                    try {
                        research = researchClient.searchUnfinishCount(context);
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    item.setQuantity(research == null ? 0 : research);
                    break;
                case 6://我的积分
                    Integer point = null;
                    try {
                        point = pointClient.queryPiont(context.getAccountId());
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    item.setQuantity(point == null ? 0 : point);
                    break;

                case 9://我的分享
                    Integer marketCount = null;
                    try {
                        marketCount = marketingCourseClient.shareCount();
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    item.setQuantity(marketCount == null ? 0 : marketCount);
                    break;
                case 12://我的证书
                    Integer certificateCount = null;
                    try {
                        certificateCount = certificateClient.getCertificateCount(context.getAccountId(), context.getCompanyId(), context.getSiteId());
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    item.setQuantity(certificateCount == null ? 0 : certificateCount);
                    break;
                case 13://我的案例
                    Integer caseCount = 0;
                    try {
                        caseCount = studentCaseClient.myCaseLibraryTotal();
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    item.setQuantity(caseCount == null ? 0 : caseCount);
                    break;
                case 14://我的学时

                    Float durationCount = 0.0f;
                    try {
                        durationCount = courseStudyHourClient.hourStatistics(context.getSiteId()
                                , context.getAccountId(), null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    item.setQuantityFloat(durationCount == null ? 0.0f : durationCount);
                    break;
                case 15://签到打卡
                    item.setCode(ItemCode.DK.getCode());
                    break;
                case 16://我的任务
                    Integer taskCount = 0;
                    try {
                        CalendarTaskParamVo paramVo = new CalendarTaskParamVo();
                        paramVo.setDate(new Date());
                        Response taskByDateApi = calendarTaskController.getTaskByDateApi(paramVo);
                        Page<CalendarTask> tasks = (Page<CalendarTask>) taskByDateApi.getData();
                        if (tasks != null) {
                            taskCount = tasks.getTotal();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    item.setQuantity(taskCount == null ? 0 : taskCount);
                    break;
                case 17://我的报告
                    Integer count = null;
                    try {
                        count = studentReportClient.getMyReportNum(context);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    item.setQuantity(count == null ? 0 : count);
                    break;
                case 18://我的订阅
                    Integer subCount = null;
                    try {
                        subCount = subscribeClient.getMySubscribeNum(context);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    item.setQuantity(subCount == null ? 0 : subCount);
                    break;
                case 19://我的专辑
                    Integer albumCount = null;
                    try {
                        albumCount = albumClient.getMyAlbumCount(context);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    item.setQuantity(albumCount == null ? 0 : albumCount);
                    break;
                case 20://签到
                    Integer signCount = 0;
                    try {
                        signCount = signRecordApiClient.selectSignRecordCountByAccountId(context.getAccountId());
                    } catch (Exception e) {
                        LOG.info("异常信息={}", e);
                    }
                    item.setQuantity(signCount);
                    break;

                case 22://陪练
                    Integer practiceCount = 0;
                    try {
                        practiceCount = myPracticeStudentClient.getRuningPracticeCount(context).getData();
                    } catch (Exception e) {
                        LOG.info("获取陪练数量--异常信息={}", e);
                    }
                    item.setQuantity(practiceCount);
                    break;
                case 23://我的钱包
                    Integer money = 0;
                    try {
                        // 获取剩余金币数量
                        BizResponse<Integer> response = tokenControllerClient.getTokenAmount();
                        if (null == response || !response.getCode().equals("1000")) {
                            item.setQuantity(money);
                            break;
                        }
                        Integer mallMoneyCount = response.getData();
                        item.setQuantity(mallMoneyCount);
                    } catch (Exception e) {
                        LOG.info("获取我的钱包金币数量--异常信息={}", e);
                    }
                    break;
                default:
                    break;
            }*/
            item.setCode(vo.getWeixinCode());
            item.setName(vo.getName());
            item.setSortNo(vo.getSort());
            item.setLogoImg(vo.getLogoImg());
            data2.add(item);
            LOG.info("---栏目名：" + item.getName() + "---统计数据：" + item.getQuantity());
        }
    }

    @ApiOperation(value = "我的首页列表", notes = "我的消息首页")
    @PostMapping("/pc/my/item")
    public Response<Map<String, List<MyItemVO>>> listPC() {
        List<Integer> terminalType = Arrays.asList(1, 3);
        List<MyItemConfigVO> voList = myItemConfigApiClients.queryByAuthoity(terminalType);
        //如果我的配置表没有数据，取默认表里的数据
        if (voList == null) {
            voList = myItemConfigDefaultApiClients.queryByAuthoity(terminalType);
        }
        try {
            Map<String, Object> items = new HashMap<>();
            Map<String, MyItemVO> data1 = new HashMap<>();
            List<MyItemVO> data2 = new ArrayList<>();

            for (MyItemConfigVO vo : voList) {
                MyItemVO item = new MyItemVO();
                item.setName(vo.getName());
                item.setCode(vo.getPcCode());
                item.setAddUrl(vo.getPcAddUrl());
                item.setQuantity(0);
                item.setSortNo(vo.getSort());
                data2.add(item);
            }
            //我的收藏，管理端不可配，此处写死
            MyItemVO sc = new MyItemVO(ItemPcCode.SC.getCode(), ItemPcCode.SC.getName(), 0, ItemPcaddUrl.SC.getCode());
            if (!data2.contains(sc)) {
                data2.add(sc);
            }
            items.put("data1", data1);
            items.put("data2", data2);
            return Response.ok(items);
        } catch (BizException be) {
            return Response.fail(be.getCode(), be.getCode());
        } catch (Exception e) {
            LOG.error("", e);
            return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(), ReturnCode.SERVICE_UNAVAILABLE.getMsg());
        }
    }
}
