package com.yizhi.application.course.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.itextpdf.text.Chapter;
import com.yizhi.application.accountUtil.AuthorizeQueryAccount;
import com.yizhi.application.course.util.MaterialTransferService;
import com.yizhi.core.application.enums.InternationalEnums;
import com.yizhi.certificate.application.feign.CertificateClient;
import com.yizhi.certificate.application.vo.RelateCertificateParam;
import com.yizhi.certificate.application.vo.domain.CertificateVo;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.core.application.vo.AuthorizeChapterVO;
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.lecturer.application.enums.DeleteFlag;
import com.yizhi.site.application.enums.PortalEnum;
import com.yizhi.site.application.feign.PortalManageFeignClients;
import com.yizhi.site.application.feign.PortalManagePCFeignClients;
import com.yizhi.site.application.vo.domain.ProtalPlateVo;
import com.yizhi.studylog.application.feign.StudyLogClient;
import com.yizhi.system.application.vo.AccountVO;
import com.yizhi.system.application.vo.OrgVO;
import com.yizhi.training.application.feign.TpPlanActivityClient;
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 io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author wenjunlong
 * @since 2018-03-19
 */
@Api(tags = "管理端-课程", description = "课程接口")
@RestController
@RequestMapping("/manage/course")
public class CourseController {

    @Autowired
    CourseClient courseClient;

    @Autowired
    MaterialClient materialClient;

    @Autowired
    TpPlanActivityClient trainingProjectClient;

    @Autowired
    TestInfoClient testInfoClient;

    @Autowired
    AccreditClient accreditClient;

    @Autowired
    MaterialTransferService materialTransferService;

    @Autowired
    PortalManageFeignClients portalManageFeignClients;

    @Autowired
    PortalManagePCFeignClients portalManagePCFeignClients;

    @Autowired
    private AuthorizeQueryAccount queryAccount;

    @Autowired
    private StudyLogClient studyLogClient;

    @Autowired
    private CourseStudyClient courseStudyClient;

    @Autowired
    private CertificateClient certificateClient;


    private static final Logger logger = LoggerFactory.getLogger(CourseController.class);

    @ApiOperation(value = "统计课程的默认学时以及查询是否开启显示配置", response = CourseTotalDurationInfoVO.class)
    @GetMapping("/totalDuration/dispaly/info/get")
    public Response<CourseTotalDurationInfoVO> getCourseDurationInfo(@RequestParam("courseId") Long courseId) {
        return Response.ok(courseClient.getCourseDurationInfo(courseId, ContextHolder.get().getSiteId()));
    }

    @GetMapping("/list")
    @ApiOperation(value = "课程分页查询()", notes = "返回分页结果集", response = CourseEntityVo.class)
    public Response<Page<CourseEntityVo>> list(@RequestParam(required = false, value = "type", defaultValue = "0") Integer type,
                                               @ApiParam(name = "courseType", value = "课程类型", required = false) @RequestParam(required = false, value = "courseType") Integer courseType,
                                               @ApiParam(name = "name", value = "课程名称或作者", required = false) @RequestParam(name = "name", required = false) String name,
                                               @ApiParam(name = "terminalType", value = "首页配置(除去已经配置课程)，terminalType 为1 移动端;2 PC端", required = false) @RequestParam(name = "terminalType", required = false) Integer terminalType,
                                               @ApiParam(name = "classifyId", value = "分类id ", required = false) @RequestParam(name = "classifyId", required = false) Long classifyId,
                                               @ApiParam(name = "shelves", value = "0 未上架 1 已上架 2 草稿", required = false) @RequestParam(name = "shelves", required = false) Integer shelves,
                                               @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @ApiParam(name = "pageSize", value = "每页条数,默认20条", required = true) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize) {

        List<Long> ids = null;
        if (terminalType != null) {
            if (terminalType == PortalEnum.ONE.ordinal()) {
                ids = portalManageFeignClients.selectHomeConfigList("移动端", 3);
            } else if (terminalType == PortalEnum.TWO.ordinal()) {
                ids = portalManageFeignClients.selectHomeConfigList("PC", 3);
            }
        }


        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        map.put("name", name);
        map.put("shelves", shelves);
        map.put("classifyId", classifyId);
        map.put("type", type);
        map.put("courseType", courseType);
        RequestContext requestContext = ContextHolder.get();
        /*
         * if (StringUtils.isEmpty(requestContext)) { map.put("companyId", 0l);
         * map.put("siteId", 0l); } else { if (requestContext.isAdmin()) {
         * map.put("companyId", requestContext.getCompanyId()); map.put("siteId",
         * requestContext.getSiteId()); } else { map.put("companyId",
         * requestContext.getCompanyId()); map.put("siteId",
         * requestContext.getSiteId()); map.put("orgId", requestContext.getOrgIds()); }
         *
         * }
         */

        map.put("companyId", requestContext.getCompanyId());
        map.put("siteId", requestContext.getSiteId());
        map.put("orgIds", requestContext.getOrgIds());
        map.put("courseIds", ids);
        Page<CourseEntityVo> page = courseClient.list(map);
        return Response.ok(page);
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增课程第一步", notes = "点击下一步保存")
    public BizResponse<CourseVo> save(@ApiParam(name = "courseVo", value = "需要传入name，code，"
            + "       classifyId，authorUnit，description，tags", required = true) @RequestBody CourseVo courseVo
//            @ApiParam(name = "name", value = "课程名称", required = true) @RequestParam(name = "name") String name,
//            @ApiParam(name = "code", value = "课程编码", required = true) @RequestParam(name = "code") String code,
//            @ApiParam(name = "classifyId", value = "分类id", required = true) @RequestParam(name = "classifyId") Long classifyId,
//            @ApiParam(name = "authorUnit", value = "制作单位", required = true) @RequestParam(name = "authorUnit") String authorUnit,
//            @ApiParam(name = "description", value = "课程简介", required = true) @RequestParam(name = "description") String description,
//            @ApiParam(name = "tags", value = "自定义关键词", required = true) @RequestParam(name = "tags") String tags

    ) {
        RequestContext requestContext = ContextHolder.get();
        courseVo.setCompanyId(requestContext.getCompanyId());
        courseVo.setSiteId(requestContext.getSiteId());
        courseVo.setOrgId(requestContext.getOrgId());
        courseVo.setCreateById(requestContext.getAccountId());
        courseVo.setCreateByName(requestContext.getAccountName());
        return courseClient.saveV2(courseVo);

    }

    @PostMapping("/up")
    @ApiOperation(value = "上架", notes = "上架操作")
    public Response<String> up(@ApiParam(name = "course", value = "只需要传入id") @RequestBody CourseEntityVo course
//            @ApiParam(name = "id", value = "课程主键", required = true) @RequestParam(name = "id") Long id
    ) {
        Integer result = courseClient.up(course);
//        Boolean f = courseClient.up(id); 0 上架成功  1 课程没有章节内容 2 没有课程 3 业务处理失败

        if (result == 0) {
            return Response.ok("上架成功");
        } else if (result == 1) {
            return Response.fail(InternationalEnums.COURSECONTROLLER2.getCode());
        } else if (result == 2) {
            return Response.fail(InternationalEnums.COURSECONTROLLER3.getCode());
        } else {
            return Response.fail("上架成功");
        }
    }

    @PostMapping("/down") // 课程下架
    @ApiOperation(value = "下架", notes = "下架操作")
    public Response<String> down(@ApiParam(name = "course", value = "只需要传入id") @RequestBody CourseEntityVo course
//            @ApiParam(name = "id", value = "课程主键", required = true) @RequestParam(name = "id") Long id
    ) {
        List<Long> list = new ArrayList<>();
        list.add(course.getId());
        // 判度心跳是否包含未处理的课程信息
        int countNum = studyLogClient.getStudyLogByCourseId(course.getId());
        if (countNum > 0) {
            return Response.fail(InternationalEnums.COURSECONTROLLER5.getCode());
        }
        ProtalPlateVo protalPlate = new ProtalPlateVo();
        protalPlate.setLinkContent(course.getId());
        protalPlate.setState(DeleteFlag.YES.ordinal());
        ProtalPlateVo plate = portalManagePCFeignClients.getPlate(protalPlate);
        if (plate != null) {
            return Response.fail(InternationalEnums.COURSECONTROLLER6.getCode());
        }

        Set<String> tpNames = trainingProjectClient.checkBizIsExistInTpNames(list);
        logger.info("下架课程ids={}, 返回的课程名={}", JSON.toJSONString(list), JSON.toJSONString(tpNames));
        if (CollectionUtils.isEmpty(tpNames) || tpNames.size() == 0) {
            Boolean f = courseClient.down(course);
            if (f) {
                return Response.ok("下架成功");
            } else {
                return Response.fail(InternationalEnums.OFFLINECOURSECONTROLLER5.getCode());
            }
        } else {
            StringBuilder sb = new StringBuilder();
            for (String s : tpNames) {
                sb.append(s);
                sb.append(",");
            }
            return Response.fail("{{" + InternationalEnums.OFFLINECOURSECONTROLLER6.getCode() + "}}" + sb.toString() + "{{" + InternationalEnums.OFFLINECOURSECONTROLLER8.getCode() + "}}");
        }
    }

    @GetMapping("/code/vail")
    @ApiOperation(value = "课程code唯一性验证", notes = "课程code唯一性验证")
    public Response<String> vail(
            @ApiParam(name = "id", value = "课程主键,课程做更新时传入", required = false) @RequestParam(name = "id", required = false) Long id,
            @ApiParam(name = "code", value = "课程code", required = true) @RequestParam(name = "code") String code) {
        RequestContext requestContext = ContextHolder.get();
        if (courseClient.vailCode(id, code, requestContext.getSiteId())) {
            return Response.ok("课程编码可以使用");
        }
        return Response.fail("", InternationalEnums.COURSECONTROLLER7.getCode());
    }

    @PostMapping("/chapter/save")
    @ApiOperation(value = "课程保存2 章节保存", notes = "课程保存2 章节保存（如果是测验source=9）")
    public Response<String> chapterSave(@ApiParam(name = "chapter", value = "章节接受参数") @RequestBody ChapterEntityVo chapter) {
        logger.info("新增章节数据={}", JSON.toJSONString(chapter));
        RequestContext requestContext = ContextHolder.get();
        Integer source = chapter.getSource();
        source = Objects.isNull(source) ? 0 : source;
        if (source.intValue() != 9 && chapter.getMaterialId() != null) {
            MaterialEntityVo material = materialClient.view(chapter.getMaterialId());
            if (!StringUtils.isEmpty(material)) {
                chapter.setMaterialName(material.getName());
                chapter.setMaterialType(material.getType());
                chapter.setMaterialCode(material.getCode());
            }

        }

        Integer materialTypeObj = chapter.getMaterialType();
        int materialType = materialTypeObj == null ? 0 : materialTypeObj.intValue();
        // 对总结性测验进行检查，只能增加一个总结性测验
        if (8 == materialType) {
            int countNum = courseClient.countChapterTest(chapter.getCourseId(), 8);
            if (countNum > 0) {
                return Response.fail(InternationalEnums.COURSECONTROLLER8.getCode());
            }
        }
        chapter.setCreateById(requestContext.getAccountId());
        chapter.setCreateTime(new Date());
        ChapterEntityVo c = courseClient.chapterSave(chapter);
        // 如果添加测验，更新测验的状态为使用中
        if (source.intValue() == 9) {
            testInfoClient.updateStatus(chapter.getMaterialId(), null, 1);
        }
        /*
         * TestInfoVO testInfoVO = new TestInfoVO();
         * testInfoVO.setId(chapter.getMaterialId()); testInfoVO.setStatus(1);
         * testInfoClient.testInfoSave(testInfoVO);
         */
        if (c != null) {
            AuthorizeChapterVO chapterVO = new AuthorizeChapterVO();
            BeanUtils.copyProperties(c, chapterVO);
            courseClient.authorizeChapterSave(chapterVO);
            return Response.ok();
        } else {
            return Response.fail();
        }
    }

    /**
     * 课程管理。章节列表
     *
     * @param courseId
     * @return
     */
    @GetMapping("/chapter/list")
    @ApiOperation(value = "课程保存2 章节列表查询", notes = "课程保存2 章节列表查询", response = Chapter.class)
    public Response chapterList(
            @ApiParam(name = "courseId", value = "课程主键id", required = true) @RequestParam(name = "courseId") Long courseId) {
        List<ChapterEntityVo> chapters = courseClient.chapterList(courseId);
        return Response.ok(chapters);
    }

    /**
     * 修改章或者节的时候，根据章或节id查询章节信息
     *
     * @param chapterId
     * @return
     */
    @GetMapping("/chapter/get")
    @ApiOperation(value = "课程保存2  章节单个信息查询", notes = "课程保存2  章节单个信息查询")
    public Response chapterGet(
            @ApiParam(name = "chapterId", value = "章节主键id", required = true) @RequestParam(name = "chapterId") Long chapterId) {
        ChapterEntityVo chapter = courseClient.chapterGet(chapterId);
        return Response.ok(chapter);
    }

    @PostMapping("/chapter/update")
    @ApiOperation(value = "课程保存2 章节修改", notes = "课程保存2 章节修改（如果是测验source=9）")
    public Response<String> chapterUpdate(
            @ApiParam(name = "chapter", value = "章节接受参数对象") @RequestBody ChapterEntityVo chapterVo) {

        logger.info("更新对象={}", JSON.toJSONString(chapterVo));
        ChapterEntityVo chapter = courseClient.chapterGet(chapterVo.getId());
        logger.info("更新旧对象={}", JSON.toJSONString(chapter));
        if (!StringUtils.isEmpty(chapterVo.getName())) {
            chapter.setName(chapterVo.getName());
        }
        if (!StringUtils.isEmpty(chapterVo.getRemark())) {
            chapter.setRemark(chapterVo.getRemark());
        }
        if (!StringUtils.isEmpty(chapterVo.getScore())) {
            chapter.setScore(chapterVo.getScore());
        }

        Integer sourceNew = chapterVo.getSource();
        sourceNew = sourceNew == null ? 0 : sourceNew;

        // 如果添加测验，更新测验的状态为使用中
        Integer sourceOld = chapter.getSource();
        sourceOld = sourceOld == null ? 0 : sourceOld;
        logger.info("更新对象的sourceOld={}，sourceNew={}", sourceOld, sourceNew);
        if (!sourceOld.equals(sourceNew)) {
            if (sourceOld.intValue() != 9 && sourceNew.intValue() == 9) {
                testInfoClient.updateStatus(chapterVo.getMaterialId(), null, 2);
            }
            if (sourceOld.intValue() == 9 && sourceNew.intValue() != 9) {
                testInfoClient.updateStatus(chapter.getMaterialId(), chapterVo.getId(), 2);
            }
        }

        if (sourceNew.intValue() == 9 && sourceOld.equals(sourceNew)) {
            testInfoClient.updateStatus(chapter.getMaterialId(), chapterVo.getMaterialId(), 4);
        }

        if (sourceNew.intValue() != 9 && chapterVo.getMaterialId() != null) {
            MaterialEntityVo material = materialClient.view(chapterVo.getMaterialId());
            if (!StringUtils.isEmpty(material)) {
                chapter.setMaterialId(material.getId());
                chapter.setMaterialName(material.getName());
                chapter.setMaterialType(material.getType());
                chapter.setMaterialCode(material.getCode());
            }
        } else {
            chapter.setMaterialId(chapterVo.getMaterialId());
            chapter.setMaterialName(chapterVo.getMaterialName());
            chapter.setMaterialType(chapterVo.getMaterialType());
            chapter.setMaterialCode(chapterVo.getMaterialCode());

        }
        chapter.setSource(sourceNew);
        RequestContext requestContext = ContextHolder.get();
        chapter.setUpdateById(requestContext.getAccountId());
        chapter.setUpdateTime(new Date());
        Boolean f = courseClient.chapterUpdate(chapter);

        if (f) {
            // 被授权课程的章节的修改
            AuthorizeChapterVO chapterVO = new AuthorizeChapterVO();
            BeanUtils.copyProperties(chapter, chapterVO);
            courseClient.authorizeChapterUpdate(chapterVO);
            return Response.ok();
        } else {
            return Response.fail();
        }
    }

    @PostMapping("/chapter/delete")
    @ApiOperation(value = "章节删除", notes = "章节删除")
    public Response chapterDelete(@ApiParam(name = "chapter", value = "只需传入id") @RequestBody ChapterEntityVo chapter
//            @ApiParam(name = "chapterId", value = "章节主键id") @RequestParam(name = "chapterId") Long chapterId
    ) {
        ChapterEntityVo chapterDO = courseClient.chapterGet(chapter.getId());
        Boolean f = courseClient.chapterDelete(chapter);
        if (f) {
            // 被授权课程列表的删除
            AuthorizeChapterVO chapterVO = new AuthorizeChapterVO();
            BeanUtils.copyProperties(chapterDO, chapterVO);
            courseClient.authorizeChapterDelete(chapterVO);
            return Response.ok();
        } else {
            return Response.fail();
        }
    }

    @PostMapping("/chapter/sort")
    @ApiOperation(value = "课程保存2  章节排序", notes = "课程保存2  章节排序")
    public Response chapterSort(@RequestBody List<String> ids) {
        Boolean f = courseClient.chapterSort(ids);
        if (f) {
            courseClient.authorizeChapterSort(ids);
            return Response.ok();
        } else {
            return Response.fail();
        }
    }

    @PostMapping("/update")
    @ApiOperation(value = "课程保存3   课程规则保存 也可用修改", notes = "课程保存3   课程规则保存 也可用修改")
    public BizResponse update(@ApiParam(name = "courseVo", value = "课程接受参数对象") @RequestBody CourseVo courseVo) {
        RequestContext requestContext = ContextHolder.get();

        courseVo.setUpdateById(requestContext.getAccountId());
        courseVo.setUpdateByName(requestContext.getAccountName());
        courseVo.setUpdateTime(new Date());
        courseVo.setSiteId(requestContext.getSiteId());
        courseVo.setCompanyId(requestContext.getCompanyId());
        courseVo.setOrgId(requestContext.getOrgId());
        Date taskEndDate = courseVo.getTaskEndDate();
        Date taskStartDate = courseVo.getTaskStartDate();
        if (null != courseVo.getEnableTask() && courseVo.getEnableTask().equals(1) && (taskEndDate == null || taskStartDate == null)) {
            return BizResponse.fail(InternationalEnums.COURSECONTROLLER13.getCode());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            //mysql timestamp 最大值是2038-01-01
            if (null != courseVo.getEnableTask() && courseVo.getEnableTask().equals(1)
                    && ( taskEndDate.getTime() > sdf.parse("2038-01-01").getTime() || taskStartDate.getTime() > sdf.parse("2038-01-01").getTime() )) {
                return BizResponse.fail(InternationalEnums.COURSECONTROLLER14.getCode());
            }
        } catch (ParseException e) {
            logger.error("生成固定日期出错：{}",e);
            return BizResponse.fail(InternationalEnums.COURSECONTROLLER14.getCode());
        }
        BizResponse<Boolean> result = courseClient.updateV2(courseVo);
        if (null == result || !BizResponse.ok().getCode().equals(result.getCode()) || !result.getData()){
            return result;
        }
        // 添加关联的证书id
        Boolean grantCertificate = courseVo.getGrantCertificate();
        if (grantCertificate != null) {
            List<CourseCertificateVo> courseCertificateVos = courseVo.getCertificates();
            List<Long> certificateIds = null;
            if (courseCertificateVos != null) {
                certificateIds = courseCertificateVos.stream().map(CourseCertificateVo::getId).collect(Collectors.toList());
            }
            RelateCertificateParam param = new RelateCertificateParam();
            param.setCertificateIds(certificateIds);
            param.setBizdId(courseVo.getId());
            CourseVo courseVoDB = courseClient.getOne(courseVo.getId());
            param.setBizdName(courseVoDB.getName());
            param.setType(1);
           // certificateClient.relateProject(param);
        }
        return BizResponse.ok();
    }

    @GetMapping("/get")
    @ApiOperation(value = "课程查看", notes = "课程查看", response = CourseDetailsVo.class)
    public Response get(@ApiParam(name = "id", value = "课程接受参数对象") @RequestParam(name = "id") Long id) {
        RequestContext requestContext = ContextHolder.get();
        CourseDetailsVo courseAllVo = courseClient.manageGet(id, requestContext.getAccountId());
        CourseVo vo = courseAllVo.getCourseVo();
        if (vo == null) {
            return Response.fail("课程信息不存在");
        } else if (!requestContext.getSiteId().equals(vo.getSiteId())) {
            return Response.fail("课程站点和范围的站点不一致");
        }
        String certificates = vo.getCertificateStr();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(certificates)) {
            String[] dataStr = certificates.split(",");
            List<Long> ids = new ArrayList<>();
            for (String str : dataStr) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(str)) {
                    ids.add(Long.valueOf(str));
                }
            }
            Map<Long, CertificateVo> data = certificateClient.getCertificateMap(ids);
            if (!CollectionUtils.isEmpty(data)) {
                List<CourseCertificateVo> certificatesData = new ArrayList<>();
                for (Long idItem : ids) {
                    if (data.containsKey(idItem)) {
                        CourseCertificateVo voItem = new CourseCertificateVo();
                        voItem.setId(idItem);
                        voItem.setName(data.get(idItem).getTitle());
                        certificatesData.add(voItem);
                    }
                }
                vo.setCertificates(certificatesData);
            }
        }

        return Response.ok(courseAllVo);
    }

    @GetMapping("/import")
    @ApiOperation(value = "课程导入", notes = "课程导入")
    public Response eImport(
            @ApiParam(name = "fileurl", value = "excel文件上传到aliyunOSS库的文件url", required = true) @RequestParam(name = "fileurl") String fileurl,
            @ApiParam(name = "fileName", value = "文件名称，需要带后缀", required = true) @RequestParam(name = "fileName") String fileName) {
        return Response.ok("未定");
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除", notes = "删除")
    public Response<String> delete(
            @ApiParam(name = "courseDeleteVo", value = "ids 课程主键  可传入多个 用逗号, 分割") @RequestBody CourseDeleteVo courseDeleteVo) {
        List<String> courseIds = new ArrayList<>();
        String[] courseIdArr = courseDeleteVo.getIds().split(",");
        StringBuffer stringBuffer = new StringBuffer();
        for (String courseId : courseIdArr) {

            if (accreditClient.getAccreditByCourseId(Long.valueOf(courseId)) > 0) {
                String name = courseClient.view(Long.valueOf(courseId)).getCode();
                if (courseIdArr.length == courseIds.size()) {
                    stringBuffer.append(name);
                } else {
                    stringBuffer.append(name).append(",");
                }
                courseIds.add(courseId);
            }

        }
        if (courseIds.size() > 0) {
            return Response.fail("{{" + InternationalEnums.COURSECONTROLLER11.getCode() + "}}" + stringBuffer.toString() + "{{" + InternationalEnums.COURSECONTROLLER12.getCode() + "}}");
        }

        try {

            Boolean f = courseClient.delete(courseDeleteVo);
            if (f) {
                return Response.ok("删除成功！");
            } else {
                return Response.fail(InternationalEnums.OFFLINECOURSECONTROLLER1.getCode());
            }
        } catch (Exception e) {
            return Response.fail(ReturnCode.DELETE_FAIL.getCode(), ReturnCode.DELETE_FAIL.getMsg());
        }

    }

    @ApiOperation(value = "课程用户范围选择保存", notes = "用户范围选择保存")
    @PostMapping("/coursrAccount/save")
    public Response saveCoursrAccount(@RequestBody List<CourseAccountVO> courseAccounts) {
        RequestContext requestContext = ContextHolder.get();
        for (CourseAccountVO courseAccount : courseAccounts) {
            courseAccount.setSiteId(requestContext.getSiteId());
        }
        Boolean f = courseClient.saveCoursrAccount(courseAccounts);
        if (f) {
            return Response.ok();
        }
        return Response.fail(ReturnCode.SAVE_FAIL.getCode(), ReturnCode.SAVE_FAIL.getMsg());
    }

    @ApiOperation(value = "课程用户范围选择查询", notes = "用户范围选择查询")
    @GetMapping("/coursrAccount/list")
    public Response getCourseAccountList(@RequestParam(name = "courseId") Long courseId) {
        List<CourseAccountVO> ranges = courseClient.getCourseAccountList(courseId);
        if (!CollectionUtils.isEmpty(ranges)) {
            List<Long> accountIds = new ArrayList<>(ranges.size());
            List<Long> orgIds = new ArrayList<>(ranges.size());
            ranges.forEach(a -> {
                if (a.getType().equals(1)) {
                    orgIds.add(a.getRelationId());
                } else {
                    accountIds.add(a.getRelationId());
                }
            });
            Map<Long, com.yizhi.system.application.vo.AccountVO> accountMap = queryAccount.queryAccountByIds(accountIds);
            Map<Long, OrgVO> orgMap = queryAccount.queryOrgByIds(orgIds);
            ranges.forEach(a -> {
                if (null != accountMap) {
                    AccountVO accountVO = accountMap.get(a.getRelationId());
                    if (null != accountVO && a.getType().equals(2)) {
                        a.setWorkNum(accountVO.getWorkNum());
                        a.setFullName(accountVO.getFullName());
                        a.setName(accountVO.getName());
                    }
                }
                if (null != orgMap) {
                    OrgVO orgVO = orgMap.get(a.getRelationId());
                    if (null != orgVO && a.getType().equals(1)) {
                        a.setName(orgVO.getName());
                    }
                }
            });
        }
        return Response.ok(ranges);
    }

    /**
     * 获取课程img
     *
     * @param id 课程id
     * @return
     */
    @ApiOperation(value = "获取课程img", notes = "根据课程id获取课程封面图片")
    @GetMapping("/image")
    public Response<String> getCourseImg(@RequestParam(value = "id") Long id) {
        CourseEntityVo course = courseClient.view(id);
        return Response.ok(course.getImage());
    }

    /**
     * 获取课程对象
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询课程只包含课程信息", notes = "根据id获取课程")
    @GetMapping("/view")
    public Response<CourseVo> getCourseView(@RequestParam(value = "id") Long id) {
        CourseEntityVo course = courseClient.view(id);
        CourseVo courseVo = new CourseVo();
        RequestContext requestContext = ContextHolder.get();
        courseVo.setCompanyId(requestContext.getCompanyId());
        courseVo.setSiteId(requestContext.getSiteId());
        courseVo.setOrgId(requestContext.getOrgId());
        courseVo.setCreateById(requestContext.getAccountId());
        courseVo.setCreateByName(requestContext.getAccountName());
        courseVo.setId(course.getId());
        courseVo.setImage(course.getImage());
        courseVo.setAudioComplete(course.getAudioComplete());
        courseVo.setAuthorUnit(course.getAuthorUnit());
        courseVo.setClassifyId(course.getClassifyId());
        courseVo.setClassifyName(course.getClassifyName());
        courseVo.setCreateTime(course.getCreateTime().toString());
        courseVo.setCode(course.getCode());
        courseVo.setDescription(course.getDescription());
        courseVo.setDownEnable(course.getDownEnable());
        courseVo.setFastForwardEnable(course.getFastForwardEnable());
        courseVo.setJumpEnable(course.getJumpEnable());
        courseVo.setCommentEnable(course.getCommentEnable());
        courseVo.setPortRule(course.getPortRule());
        courseVo.setScope(course.getScope());
        courseVo.setShelves(course.getShelves());
        courseVo.setDocComplete(course.getDocComplete());
        courseVo.setUpdateTime(course.getUpdateTime());
        courseVo.setName(course.getName());
        courseVo.setAutoEnable(course.getAutoEnable());
        courseVo.setGradeEnable(course.getGradeEnable());
        return Response.ok(courseVo);
    }

    /**
     * 根据课程id 获取课程评分和(课程学习人数)课程浏览人次
     *
     * @param courseId
     * @return
     */
//    @ApiOperation(value = "获取学习人数(浏览人次)，评分", notes = "根据id获取课程")
//    @GetMapping("/getManageCourseList")
//    public Response<HomePageCoursePageVo> getManageCourseList(@RequestParam("courseId") Long courseId){
//        RequestContext requestContext = ContextHolder.get();
//        Long companyId = requestContext.getCompanyId();
//        Long siteId = requestContext.getSiteId();
//        HomePageCoursePageVo manageListCourseVos = (HomePageCoursePageVo) courseClient.getManageCourseList(courseId);
//        return Response.ok(manageListCourseVos);
//    }
    @ApiOperation(value = "获取学习人数(浏览人次)，评分", notes = "根据id获取课程")
    @GetMapping("/getManageCourseList")
    public Response<HomePageCoursePageVo> getManageCourseList(@RequestParam("courseId") Long courseId) {
        RequestContext requestContext = ContextHolder.get();
        Long companyId = requestContext.getCompanyId();
        Long siteId = requestContext.getSiteId();

        HomePageCoursePageVo manageListCourseVos = courseClient.getManageCourseList(courseId, siteId, companyId);
        return Response.ok(manageListCourseVos);
    }

    @GetMapping("/authorizelist")
    @ApiOperation(value = "课程分页查询", notes = "返回分页结果集", response = CourseEntityVo.class)
    public Response<Page<AuthCourseVO>> authorizeList(
            @ApiParam(name = "name", value = "课程名称或作者", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(name = "classifyId", value = "分类id ", required = false) @RequestParam(name = "classifyId", required = false) Long classifyId,
            @ApiParam(name = "authorizeSiteId", value = "被授权站点id", required = true) @RequestParam(name = "authorizeSiteId", required = false) Long authorizeSiteId,
            @ApiParam(name = "shelves", value = "0 未上架 1 已上架 2 草稿", required = false) @RequestParam(name = "shelves", required = false) Integer shelves,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条", required = true) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        map.put("name", name);
        // 包含上架上下架的课程
        map.put("shelves", 3);
        map.put("classifyId", classifyId);
        map.put("authorizeSiteId", authorizeSiteId);

        RequestContext requestContext = ContextHolder.get();

        map.put("companyId", requestContext.getCompanyId());
        map.put("siteId", requestContext.getSiteId());
        map.put("orgIds", requestContext.getOrgIds());
        Page<AuthCourseVO> page = courseClient.getAuthorizeCourseList(map);
        return Response.ok(page);
    }

    @PostMapping("/backupMaterial")
    @ApiOperation(value = "素材迁移")
    public Response<String> backupMaterial(@RequestBody List<String> codeList,
                                           @ApiParam(name = "afterSiteId", value = "转移后站点id", required = true) @RequestParam(name = "afterSiteId", required = true) Long afterSiteId,
                                           @ApiParam(name = "beforeSiteId", value = "转移前站点id", required = true) @RequestParam(name = "beforeSiteId", required = true) Long beforeSiteId,
                                           @ApiParam(name = "companyId", value = "转移后公司id", required = true) @RequestParam(name = "companyId", required = true) Long companyId) {

        courseClient.updateMaterialData(codeList, afterSiteId, beforeSiteId, companyId);
        return Response.ok("转移成功！");

    }

    @PostMapping("/transferMaterial")
    @ApiOperation(value = "素材迁移2")
    public Response<String> transferMaterial(@RequestBody List<String> codeList,
                                             @ApiParam(name = "afterSiteId", value = "转移后站点id", required = true) @RequestParam(name = "afterSiteId", required = true) Long afterSiteId,
                                             @ApiParam(name = "beforeSiteId", value = "转移前站点id", required = true) @RequestParam(name = "beforeSiteId", required = true) Long beforeSiteId,
                                             @ApiParam(name = "companyId", value = "转移后公司id", required = true) @RequestParam(name = "companyId", required = true) Long companyId) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("afterSiteId", afterSiteId);
        stringObjectHashMap.put("beforeSiteId", beforeSiteId);
        stringObjectHashMap.put("companyId", companyId);
        stringObjectHashMap.put("codeList", codeList);

        materialTransferService.execute(stringObjectHashMap, true);
        return Response.ok("转移成功！");

    }

    @GetMapping("/list/export")
    @ApiOperation(value = "课程清单导出")
    public Response<String> listExport(@RequestParam(required = false, value = "type", defaultValue = "0") Integer type,
                                       @ApiParam(name = "name", value = "课程名称或作者", required = false) @RequestParam(name = "name", required = false) String name,
                                       @ApiParam(name = "classifyId", value = "分类id ", required = false) @RequestParam(name = "classifyId", required = false) Long classifyId,
                                       @ApiParam(name = "courseType", value = "课程类型", required = false) @RequestParam(required = false, value = "courseType") Integer courseType,
                                       @ApiParam(name = "shelves", value = "0 未上架 1 已上架 2 草稿", required = false) @RequestParam(name = "shelves", required = false) Integer shelves) {

        return Response.ok(courseClient.listExport(type, name, classifyId, shelves, courseType).get("result").toString());
    }

    @GetMapping("/mq/record/open")
    public Response<Boolean> mqRecordOpen(@RequestParam("key") String key) {

        return Response.ok(courseStudyClient.openRedis(key));
    }
}
