package cn.wisenergy.chnmuseum.party.web.controller;

import cn.wisenergy.chnmuseum.party.auth.SHA256PasswordEncryptionService;
import cn.wisenergy.chnmuseum.party.auth.util.JwtTokenUtil;
import cn.wisenergy.chnmuseum.party.common.enums.LanguageEnum;
import cn.wisenergy.chnmuseum.party.common.util.DateUtil;
import cn.wisenergy.chnmuseum.party.common.util.TimeUtils;
import cn.wisenergy.chnmuseum.party.common.validator.groups.Add;
import cn.wisenergy.chnmuseum.party.common.vo.AudioVo;
import cn.wisenergy.chnmuseum.party.common.vo.GenericPageParam;
import cn.wisenergy.chnmuseum.party.common.vo.VideoVo;
import cn.wisenergy.chnmuseum.party.model.*;
import cn.wisenergy.chnmuseum.party.service.*;
import cn.wisenergy.chnmuseum.party.service.impl.*;
import cn.wisenergy.chnmuseum.party.web.controller.base.BaseController;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController()
@RequestMapping("/cmRestApi")
@Api(tags = {"中国移动API"})
public class ChinaMobileRestApiController extends BaseController {

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

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private EmployeeServiceImpl employeeService;

    @Resource
    private TUserServiceImpl userService;

    @Resource
    private RunLogServiceImpl runLogService;

    @Resource
    private SysLogController sysLogController;

    @Resource
    private TAreaServiceImpl areaService;

    @Resource
    private AssetServiceImpl assetService;

    @Resource
    private TBoxOperationServiceImpl boxOperationService;

    @Resource
    private ExhibitionBoardService exhibitionBoardService;

    @Resource
    private TBoardStatisticService tBoardStatisticService;

    @Resource
    private LearningProjectService learningProjectService;

    @Resource
    private LearningContentService learningContentService;

    @Resource
    private ExhibitionBoardCatService exhibitionBoardCatService;

    @Resource
    private CopyrightOwnerService copyrightOwnerService;

    @Resource
    private LearningContentBoardService learningContentBoardService;

    @Resource
    private TAppVersionService appVersionService;

    @Resource
    private TAppDirPicService appDirPicService;

    @Resource
    private TAppRunPicService appRunPicService;

    private static final String SHIRO_JWT_TOKEN = "shiro:jwt:token:";
    //用户登录次数计数  redisKey 前缀
    private static final String SHIRO_LOGIN_COUNT = "shiro_login_count_";
    //用户登录是否被锁定    一小时 redisKey 前缀
    private static final String SHIRO_IS_LOCK = "shiro_is_lock_";

//    /**
//     * 管理员ajax登录请求 后端用户登录
//     *
//     * @param username
//     * @param password
//     * @return
//     */
//    @RequestMapping(value = "/user/webLogin", method = RequestMethod.POST)
//    public ResponseEntity<JSONObject> login(@RequestParam(value = "username") String username,
//                                            @RequestParam(value = "password") String password,
//                                            @RequestParam(value = "boxNo") String boxNo) {
//        JSONObject resultMap = new JSONObject(true);
//        Employee employee;
//        if (StringUtils.isNoneBlank(username)) {
//            //访问一次,计数一次
//            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
//            if ("LOCK".equals(opsForValue.get(SHIRO_IS_LOCK + username))) {
//                resultMap.put("status", 400);
//                resultMap.put("message", "由于密码输入错误次数大于5次,12小时内帐号已禁止登录!请您联系相关管理人员,联系电话:13924551212,邮箱:325346534@zh.com。");
//                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
//            }
//            employee = employeeService.selectByUsername(username);
//            if (employee == null) {
//                resultMap.put("status", 500);
//                resultMap.put("message", "用户名或密码不正确!");
//                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
//            }
//            try {
//                byte[] salt = employee.getPasswordSalt();
//                if (!new String(SHA256PasswordEncryptionService.createPasswordHash(password, salt)).equals(new String(employee.getPasswordHash()))) {
//                    opsForValue.increment(SHIRO_LOGIN_COUNT + username, 1);
//                    //计数大于5时,设置用户被锁定一小时
//                    String s = opsForValue.get(SHIRO_LOGIN_COUNT + username);
//                    if (StringUtils.isNotBlank(s)) {
//                        if (Integer.parseInt(s) >= 5) {
//                            opsForValue.set(SHIRO_IS_LOCK + username, "LOCK");
//                            stringRedisTemplate.expire(SHIRO_IS_LOCK + username, 12, TimeUnit.HOURS);
//                        }
//                    }
//                    throw new IncorrectCredentialsException("用户名或密码不正确!");
//                }
//                String token = JwtTokenUtil.sign(username, employee.getId());
//                // 将token信息存入Redis
//                stringRedisTemplate.opsForValue().set(SHIRO_JWT_TOKEN + token, employee.getId(), 240, TimeUnit.MINUTES);
//
//                JSONObject jsonObject = new JSONObject(true);
//                jsonObject.put("token", token);
//                jsonObject.put("userId", employee.getId());
//                jsonObject.put("userName", employee.getUsername());
//                jsonObject.put("expire", TimeUtils.format(LocalDateTime.now().plusMinutes(240), TimeUtils.FORMAT_ONE));
//                jsonObject.put("orgCode", "");
//                jsonObject.put("orgName", "");
//
//                resultMap.put("resultCode", 200);
//                resultMap.put("message", "成功");
//                resultMap.put("data", jsonObject);
//                return ResponseEntity.status(HttpStatus.OK).body(resultMap);
//            } catch (Exception e) {
//                resultMap.put("status", 500);
//                resultMap.put("message", e.getMessage());
//            }
//        }
//        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
//    }
//
//    @ApiOperation(value = "获取单个成员信息")
//    @GetMapping(value = "/user/getUserInfo")
//    public ResponseEntity<JSONObject> getById(String userId, @RequestHeader("token") String token) {
//        try {
//            Employee employee = employeeService.selectByEmpId(userId);
//
//            if (null == employee) {
//                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
//            }
//
//            JSONObject jsonObject = new JSONObject(true);
//            jsonObject.put("token", token);
//            jsonObject.put("userId", employee.getId());
//            jsonObject.put("userName", employee.getUsername());
//            long expire = stringRedisTemplate.getExpire(SHIRO_JWT_TOKEN + token) == null ? 0L : stringRedisTemplate.getExpire(SHIRO_JWT_TOKEN + token);
//            jsonObject.put("expire", TimeUtils.format(LocalDateTime.now().plusMinutes(expire), TimeUtils.FORMAT_ONE));
////          BankBranchInfo bankBranch = this.employeeService.getById(Id);
////          if (bankBranch != null) {
////               employee.setBankBranchName(bankBranch.getName());
////          }
//            jsonObject.put("orgCode", "");
//            jsonObject.put("orgName", "");
//
//            JSONObject resultMap = new JSONObject(true);
//            resultMap.put("resultCode", 200);
//            resultMap.put("message", "成功");
//            resultMap.put("data", jsonObject);
//            return ResponseEntity.ok(resultMap);
//        } catch (Exception e) {
//            logger.error("查询成员信息错误!", e);
//        }
//        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
//    }


    /**
     * 管理员ajax登录请求 后端用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/user/webLogin", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> login(@RequestParam(value = "username") String username,
                                            @RequestParam(value = "password") String password,
                                            @RequestParam(value = "mac") String mac) {
        JSONObject resultMap = new JSONObject(true);
        TUser user;
        if (StringUtils.isNoneBlank(username)) {

            try {
                //访问一次,计数一次
                ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
                if ("LOCK".equals(opsForValue.get(SHIRO_IS_LOCK + username))) {
                    resultMap.put("status", 400);
                    resultMap.put("message", "由于密码输入错误次数大于5次,12小时内帐号已禁止登录!请您联系相关管理人员,联系电话:13924551212,邮箱:325346534@zh.com。");
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
                }
                user = userService.selectByUsername(username);
                if (user == null) {
                    resultMap.put("status", 500);
                    resultMap.put("message", "用户名或密码不正确!");
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
                }
                TBoxOperation operation = boxOperationService.getOne(new UpdateWrapper<TBoxOperation>().eq("organ_id", user.getOrgId()));
                if (operation == null || "".equals(operation.getMac())) {
                    resultMap.put("status", 500);
                    resultMap.put("message", "用户未激活!");
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
                }
                if (!mac.equals(operation.getMac())) {
                    resultMap.put("status", 500);
                    resultMap.put("message", "mac地址不正确!");
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
                }
                if ("2".equals(user.getStatus())) {
                    throw new DisabledAccountException("此帐号已禁用,请联系管理员!");
                }

                if (user.getPermanent() != null && !user.getPermanent()) {
                    if (user.getEffectiveDate().isAfter(LocalDate.now()) || user.getExiredDate().isBefore(LocalDate.now())) {
                        throw new DisabledAccountException("此帐号已失效,请联系管理员!");
                    }
                }

                byte[] salt = user.getPasswordSalt();
                if (!new String(SHA256PasswordEncryptionService.createPasswordHash(password, salt)).equals(new String(user.getPasswordHash()))) {
                    opsForValue.increment(SHIRO_LOGIN_COUNT + username, 1);
                    //计数大于5时,设置用户被锁定一小时
                    String s = opsForValue.get(SHIRO_LOGIN_COUNT + username);
                    if (StringUtils.isNotBlank(s)) {
                        if (Integer.parseInt(s) >= 5) {
                            opsForValue.set(SHIRO_IS_LOCK + username, "LOCK");
                            stringRedisTemplate.expire(SHIRO_IS_LOCK + username, 12, TimeUnit.HOURS);
                        }
                    }
                    throw new IncorrectCredentialsException("用户名或密码不正确!");
                }
                String token = JwtTokenUtil.sign(username, user.getId());
                // 将token信息存入Redis
                stringRedisTemplate.opsForValue().set(SHIRO_JWT_TOKEN + token, user.getId(), 240, TimeUnit.MINUTES);

                JSONObject jsonObject = new JSONObject(true);
                jsonObject.put("token", token);
                jsonObject.put("userId", user.getId());
                jsonObject.put("userName", user.getUserName());
                jsonObject.put("expire", TimeUtils.format(LocalDateTime.now().plusMinutes(240), TimeUtils.FORMAT_ONE));
                jsonObject.put("orgCode", user.getOrgId());
                jsonObject.put("orgName", user.getOrgName());

                resultMap.put("resultCode", 200);
                resultMap.put("message", "登录成功");
                resultMap.put("data", jsonObject);
                return ResponseEntity.status(HttpStatus.OK).body(resultMap);
            } catch (Exception e) {
                resultMap.put("resultCode", 500);
                resultMap.put("message", e.getMessage());
            }
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
    }

    @ApiOperation(value = "获取单个成员信息")
    @GetMapping(value = "/user/getUserInfo")
    public ResponseEntity<JSONObject> getById(String userId) {
        JSONObject resultMap = new JSONObject(true);
        try {
            TUser user = userService.getById(userId);

            if (null == user) {
                resultMap.put("resultCode", 500);
                resultMap.put("message", "用户不存在");
                resultMap.put("data", "");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            JSONObject jsonObject = new JSONObject(true);
            jsonObject.put("userId", user.getId());
            jsonObject.put("userName", user.getUserName());
//            long expire = stringRedisTemplate.getExpire(SHIRO_JWT_TOKEN + token) == null ? 0L : stringRedisTemplate.getExpire(SHIRO_JWT_TOKEN + token);
            //jsonObject.put("expire", TimeUtils.format(LocalDateTime.now().plusMinutes(expire), TimeUtils.FORMAT_ONE));
            jsonObject.put("effectiveDate", user.getEffectiveDate());
            jsonObject.put("expireDate", user.getExiredDate());
            jsonObject.put("orgCode", user.getOrgId());
            jsonObject.put("orgName", user.getOrgName());

            resultMap.put("resultCode", 200);
            resultMap.put("message", "成功");
            resultMap.put("data", jsonObject);
            return ResponseEntity.ok(resultMap);
        } catch (Exception e) {
            resultMap.put("resultCode", 500);
            resultMap.put("message", "获取单个成员信息失败!");
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
    }

    @RequestMapping(value = "/user/logout", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> logout() {
        String token = request.getHeader("Authorization");
        JSONObject resultMap = new JSONObject(true);
        try {
            if (StringUtils.isNotBlank(token)) {
//                SecurityUtils.getSubject().logout();
                this.stringRedisTemplate.delete(SHIRO_JWT_TOKEN + token);
            }
            resultMap.put("resultCode", 200);
            resultMap.put("message", "成功");
            resultMap.put("data", "");
            return ResponseEntity.status(HttpStatus.OK).body(resultMap);
        } catch (Exception e) {
            resultMap.put("resultCode", 500);
            resultMap.put("message", "注销错误!");
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
    }

    /**
     * 插入机顶盒日志表
     */
    @ApiOperation(value = "插入机顶盒日志表", notes = "插入机顶盒日志表")
    @PostMapping(value = "/insertRunLog")
    public ResponseEntity<JSONObject> insertRunLog(RunLog runLog) {
        JSONObject resultMap = new JSONObject();

        try {
            boolean b = runLogService.insertRunLog(runLog);
            resultMap.put("resultCode", 200);
            resultMap.put("message", "成功");
            resultMap.put("data", "");
            return ResponseEntity.status(HttpStatus.OK).body(resultMap);
        } catch (Exception e) {
            resultMap.put("resultCode", 500);
            resultMap.put("message", "失败");
            resultMap.put("data", "");
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
    }

    /**
     * 查询语言列表
     */
    @ApiOperation(value = "查询语言列表", notes = "查询语言列表")
    @PostMapping(value = "/language/info")
    public ResponseEntity<JSONObject> languageInfo() {
        JSONObject resultMap = new JSONObject();

        try {
            List<Map<String, String>> list = areaService.languageInfo();
            resultMap.put("resultCode", 200);
            resultMap.put("message", "成功");
            resultMap.put("data", list);
            return ResponseEntity.status(HttpStatus.OK).body(resultMap);
        } catch (Exception e) {
            resultMap.put("resultCode", 500);
            resultMap.put("message", "失败");
            resultMap.put("data", "");
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultMap);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "learningContentId", value = "学习内容ID", paramType = "query", dataType = "String")
    })
    @PostMapping("/exhibitionBoard/getPage")
    @RequiresPermissions("exhibition:board:page")
    @ApiOperation(value = "展板列表查询", notes = "展板列表查询")
    public Map<String, Object> getExhibitionBoardPageList(@RequestParam(value = "learningContentId", required = false) String learningContentId) {
        final IPage<ExhibitionBoard> page = this.learningContentBoardService.getBoardPageByLearningContentId(getPage(), learningContentId, null);
        for (ExhibitionBoard exhibitionBoard : page.getRecords()) {
            if (exhibitionBoard.getAssetCopyrightOwnerId() != null) {
                String name = this.copyrightOwnerService.getById(exhibitionBoard.getAssetCopyrightOwnerId()).getName();
                exhibitionBoard.setBoardCopyrightOwnerName(name);
            }
            if (exhibitionBoard.getExhibitionBoardCatId() != null) {
                String name = this.exhibitionBoardCatService.getById(exhibitionBoard.getExhibitionBoardCatId()).getName();
                exhibitionBoard.setExhibitionBoardCatName(name);
            }
            final String assetId = exhibitionBoard.getAssetId();
            final Asset asset = this.assetService.getById(assetId);
            final String videoUrl = asset.getVideoUrl();
            final List<VideoVo> videoVoList = JSONObject.parseObject(videoUrl, new TypeReference<List<VideoVo>>() {
            }, Feature.OrderedField);
            exhibitionBoard.setVideoUrlList(videoVoList.stream().map(VideoVo::getFileUrl).collect(Collectors.toList()));
        }
        return getResult(page);
    }

    @ApiOperation(value = "展板详情页面查询", notes = "展板详情页面查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "boardId", value = "展板ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "language", value = "语言", dataType = "String", paramType = "query")
    })
    @GetMapping("/exhibitionBoard/getBoardInfo")
    public Map<String, Object> getById(@RequestParam(value = "boardId") String id, @RequestParam(value = "language", required = false) LanguageEnum language) {
        ExhibitionBoard exhibitionBoard = exhibitionBoardService.getById(id);
        String exhibitionBoardCatId = exhibitionBoard.getExhibitionBoardCatId();
        if (exhibitionBoardCatId != null) {
            exhibitionBoard.setExhibitionBoardCatName(this.exhibitionBoardCatService.getById(exhibitionBoardCatId).getName());
        }
        String boardCopyrightOwnerId = exhibitionBoard.getBoardCopyrightOwnerId();
        if (boardCopyrightOwnerId != null) {
            exhibitionBoard.setBoardCopyrightOwnerName(this.copyrightOwnerService.getById(boardCopyrightOwnerId).getName());
        }

        final String guideAudioUrl = exhibitionBoard.getGuideAudioUrl();
        final List<AudioVo> audioVoList = JSONObject.parseObject(guideAudioUrl, new TypeReference<List<AudioVo>>() {
        }, Feature.OrderedField);
        exhibitionBoard.setAudioUrlList(audioVoList.stream().map(AudioVo::getFileUrl).collect(Collectors.toList()));

        final String refMaterialUrl = exhibitionBoard.getRefMaterialUrl();
        final List<AudioVo> refMaterialVoList = JSONObject.parseObject(refMaterialUrl, new TypeReference<List<AudioVo>>() {
        }, Feature.OrderedField);
        exhibitionBoard.setMaterialUrlList(refMaterialVoList.stream().map(AudioVo::getFileUrl).collect(Collectors.toList()));

        String assetId = exhibitionBoard.getAssetId();
        if (assetId != null) {
            final Asset asset = this.assetService.getById(assetId);
            exhibitionBoard.setAssetName(this.assetService.getById(assetId).getName());
            final String assetCopyrightOwnerId = asset.getAssetCopyrightOwnerId();
            final String assetCopyrightOwnerName = this.copyrightOwnerService.getById(assetCopyrightOwnerId).getName();
            exhibitionBoard.setAssetCopyrightOwnerName(assetCopyrightOwnerName);

            final String videoUrl = asset.getVideoUrl();
            final List<VideoVo> videoVoList = JSONObject.parseObject(videoUrl, new TypeReference<List<VideoVo>>() {
            }, Feature.OrderedField);
            exhibitionBoard.setVideoUrlList(videoVoList.stream().map(VideoVo::getFileUrl).collect(Collectors.toList()));
        }
        return getResult(exhibitionBoard);
    }

    @PostMapping("/equitment/playLog")
    @RequiresPermissions("t:board:statistic:statisticBoardInfo")
    @ApiOperation(value = "播放记录信息反馈", notes = "播放记录信息反馈")
    public Map<String, Object> boardStatisticInfo(@Validated(value = {Add.class}) TBoardStatistic tBoardStatistic) {
        // 展板信息统计
        try {
            Object result = tBoardStatisticService.boardStatisticInfo(tBoardStatistic, false);
            // 返回操作结果
            if (result != null && (boolean) result) {
                return getSuccessResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 保存失败
        return getFailResult();
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "nameOrCode", value = "名称或编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startDate", value = "创建时间-开始", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "创建时间-结束", paramType = "query", dataType = "String")
    })
    @PostMapping("/learningContent/getPage")
    @RequiresPermissions("learning:content:page")
    @ApiOperation(value = "查询学习内容", notes = "查询学习内容")
    public Map<String, Object> getLearningContentPageList(GenericPageParam genericPageParam) {
        LambdaQueryWrapper<LearningContent> queryWrapper = new LambdaQueryWrapper<>();
        // 对名称或编码模糊查询
        if (StringUtils.isNotBlank(genericPageParam.getNameOrCode())) {
            queryWrapper.like(LearningContent::getName, genericPageParam.getNameOrCode());
        }
        // 根据创建时间区间检索
        if (genericPageParam.getStartDate() != null && genericPageParam.getEndDate() != null) {
            queryWrapper.ge(LearningContent::getCreateTime, genericPageParam.getStartDate().atTime(0, 0, 0))
                    .le(LearningContent::getCreateTime, genericPageParam.getEndDate().atTime(23, 59, 59));
        }
        // 设置排序规则
        queryWrapper.orderByDesc(LearningContent::getCreateTime);
        // 设置查询内容
        queryWrapper.select(
                LearningContent::getId,
                LearningContent::getName,
                LearningContent::getAuditStatus,
                LearningContent::getCreateTime,
                LearningContent::getUpdateTime);
        Page<LearningContent> page = this.learningContentService.page(getPage(), queryWrapper);
        for (LearningContent learningContent : page.getRecords()) {
            LambdaQueryWrapper<LearningContentBoard> lambdaQueryWrapper = Wrappers.<LearningContentBoard>lambdaQuery().eq(LearningContentBoard::getLearningContentId, learningContent.getId());
            int exhibitionBoardCount = this.learningContentBoardService.count(lambdaQueryWrapper);
            learningContent.setExhibitionBoardCount(exhibitionBoardCount);
        }
        return getResult(page);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "nameOrCode", value = "名称或编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startDate", value = "创建时间-开始", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "创建时间-结束", paramType = "query", dataType = "String")
    })
    @PostMapping("/learningProject/getPage")
    @RequiresPermissions("learning:project:page")
    @ApiOperation(value = "查询项目", notes = "查询项目")
    public Map<String, Object> getLearningProjectPageList(GenericPageParam genericPageParam) {
        LambdaQueryWrapper<LearningProject> queryWrapper = new LambdaQueryWrapper<>();
        // 对名称或编码模糊查询
        if (StringUtils.isNotBlank(genericPageParam.getNameOrCode())) {
            queryWrapper.like(LearningProject::getName, genericPageParam.getNameOrCode());
        }
        // 根据创建时间区间检索
        if (genericPageParam.getStartDate() != null && genericPageParam.getEndDate() != null) {
            queryWrapper.ge(LearningProject::getCreateTime, genericPageParam.getStartDate().atTime(0, 0, 0))
                    .le(LearningProject::getCreateTime, genericPageParam.getEndDate().atTime(23, 59, 59));
        }
        // 设置排序规则
        queryWrapper.orderByDesc(LearningProject::getCreateTime);
        // 设置查询内容
        queryWrapper.select(
                LearningProject::getId,
                LearningProject::getName,
                LearningProject::getRemarks,
                LearningProject::getCreateTime,
                LearningProject::getUpdateTime);
        Page<LearningProject> page = this.learningProjectService.page(getPage(), queryWrapper);
        for (LearningProject learningProject : page.getRecords()) {
            LambdaQueryWrapper<LearningContent> lambdaQueryWrapper = Wrappers.<LearningContent>lambdaQuery()
                    .eq(LearningContent::getLearningProjectId, learningProject.getId())
                    .eq(LearningContent::getIsPublished, true);
            lambdaQueryWrapper.select(LearningContent::getName);
            List<LearningContent> learningContentList = this.learningContentService.list(lambdaQueryWrapper);
            String learningContentNames = learningContentList.stream().map(LearningContent::getName).collect(Collectors.joining("、"));
            learningProject.setLearningContentNames(learningContentNames);
        }
        return getResult(page);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "boardId", value = "名称或编码", paramType = "query", dataType = "String")
    })
    @PostMapping("/exhibitionBoard/getRefMaterial")
    @RequiresPermissions("learning:project:page")
    @ApiOperation(value = "展板参考资料查询", notes = "展板参考资料查询")
    public Map<String, Object> getBoardRefMaterial(@RequestParam(value = "boardId", required = false) String boardId) {
        final ExhibitionBoard exhibitionBoard = this.exhibitionBoardService.getById(boardId);
        final String refMaterialUrl = exhibitionBoard.getRefMaterialUrl();
        final List<AudioVo> audioVoList = JSONObject.parseObject(refMaterialUrl, new TypeReference<List<AudioVo>>() {
        }, Feature.OrderedField);
        return getResult(audioVoList);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "learningContentId", value = "学习内容ID", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "nameOrCode", value = "名称或编码", paramType = "query", dataType = "String")
    })
    @PostMapping("/exhibitionBoard/search")
    @RequiresPermissions("learning:content:board:page")
    @ApiOperation(value = "模糊搜索查询", notes = "模糊搜索查询")
    public Map<String, Object> getLearningContentBoardPageList(GenericPageParam genericPageParam, @RequestParam(value = "learningContentId", required = false) String learningContentId) {
        IPage<ExhibitionBoard> page = this.learningContentBoardService.getBoardPageByLearningContentId(getPage(), learningContentId, genericPageParam.getNameOrCode());
        return getResult(page);
    }

    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "_index", value = "分页起始偏移量", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "_size", value = "返回条数", paramType = "query", dataType = "Integer")
    })
    @PostMapping("/asset/search")
    @RequiresPermissions("learning:content:board:page")
    @ApiOperation(value = "获取当前用户可查看的视频信息", notes = "获取当前用户可查看的视频信息")
    public Map<String, Object> getAssetPageByOrganId() {
        final TUser tUser = getcurUser();
        final String orgId = tUser.getOrgId();
        IPage<Asset> page = this.learningContentBoardService.getAssetPageByOrganId(getPage(), orgId);
        return getResult(page);
    }

    @ApiOperation(value = "app最新版本查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "versionNo", value = "app版本号", dataType = "String", paramType = "query")
    })
    @GetMapping(value = "/version/check")
    @RequiresPermissions("app:version:check")
    public Map<String, Object> versionCheck(String versionNo) {
        TAppVersion current = new TAppVersion();//当前版本
        // 查询最新版本号信息
        QueryWrapper<TAppVersion> qw = new QueryWrapper<>();
        qw.eq("is_current", 1);
        qw.select().orderByDesc("update_time");
        List<TAppVersion> currentList = appVersionService.list(qw);
        if (currentList == null || currentList.size() == 0) {
            return getFailResult("未设置当前版本信息");
        } else {
            current = currentList.get(0);
        }
        Map map = new HashMap();
        map.put("isLatest",versionNo.equals(current.getAppVersion()));
        map.put("versionNo",current.getAppVersion());
        map.put("versionUrl",current.getApkUrl());
        map.put("updateLog",current.getUpdateLog());
        map.put("updateTime", current.getUpdateTime());
        return getResult(map);
    }


    @ApiOperation(value = "app界面图片查询")
    @GetMapping(value = "/app/picSelect")
    @RequiresPermissions("app:pic:select")
    public Map<String, Object> appPicSelect() {
        TAppDirPic currentDir = null;// 当前目录页面
        TAppRunPic currentRun = null;// 当前运行画面
        // 查询当前目录界面信息
        QueryWrapper<TAppDirPic> qw = new QueryWrapper<>();
        qw.eq("is_current", 1);
        qw.select().orderByDesc("create_time");
        List<TAppDirPic> currentDirList = appDirPicService.list(qw);
        if (currentDirList != null && currentDirList.size() > 0) {
            currentDir = currentDirList.get(0);
        }
        QueryWrapper<TAppRunPic> qw1 = new QueryWrapper<>();
        qw1.eq("is_current", 1);
        qw1.select().orderByDesc("create_time");
        List<TAppRunPic> currentRunList = appRunPicService.list(qw1);
        if (currentRunList != null && currentRunList.size() > 0) {
            currentRun = currentRunList.get(0);
        }

        Map map = new HashMap();
        map.put("dirImgUrl",currentDir != null? currentDir.getAppDirPic() : "未设置目录图片");
        map.put("runImgUrl",currentRun != null ? currentRun.getAppRunPic() : "未设置运行图片");
        return getResult(map);
    }
}