package com.ruoyi.web.controller.front;


import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.PhoneUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.vod.VodPlayAuthDto;
import com.ruoyi.common.vod.VodUtils;
import com.ruoyi.common.vod.VodZlsjsUtils;
import com.ruoyi.dz.domain.DzCards;
import com.ruoyi.dz.service.IDzCardsService;
import com.ruoyi.enums.SmsTypeEnum;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.ShortMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("front/comm")
@Api(tags = "前台-公共")
@Slf4j
public class CommController {
    private final ISysDictTypeService dictTypeService;
    private final ShortMessageService shortMessageService;
    private final RedisCache redisCache;
    private final ISysUserService userService;
    private final ISysConfigService configService;
    private final IDzCardsService cardsService;
    private final VodUtils vodUtils;
    private final VodZlsjsUtils vodZlsjsUtils;

    public CommController(ISysDictTypeService dictTypeService, ShortMessageService shortMessageService, RedisCache redisCache, ISysUserService userService, ISysConfigService configService, IDzCardsService cardsService, VodUtils vodUtils, VodZlsjsUtils vodZlsjsUtils) {
        this.dictTypeService = dictTypeService;
        this.shortMessageService = shortMessageService;
        this.redisCache = redisCache;
        this.userService = userService;
        this.configService = configService;
        this.cardsService = cardsService;
        this.vodUtils = vodUtils;
        this.vodZlsjsUtils = vodZlsjsUtils;
    }

    @GetMapping(value = "dict/{dictTypes}")
    @Anonymous
    @ApiOperation("字典列表")
    public AjaxResult dictType(@PathVariable String[] dictTypes)
    {
        Map<String, List<JSONObject>> dictTypeMap = new HashMap<>();
        for(String dictType : dictTypes) {
            List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
            if (StringUtils.isNull(data))
            {
                dictTypeMap.put(dictType, Collections.emptyList());
            } else {
                dictTypeMap.put(dictType, data.stream().map(t -> {
                    JSONObject o = new JSONObject();
                    o.put("dictCode", t.getDictCode());
                    o.put("dictValue", t.getDictValue());
                    o.put("dictLabel", t.getDictLabel());
                    return o;
                }).collect(Collectors.toList()));
            }
        }
        return AjaxResult.success(dictTypeMap);
    }

    @GetMapping(value = "config")
    @Anonymous
    @ApiOperation("前端参数列表")
    public AjaxResult config()
    {
        List<SysConfig> configList = Lists.newArrayList();
        String frontConfKeys = configService.selectConfigByKey(UserConstants.FRONT_CONFIGS);
        SysConfig cond = new SysConfig();
        for(String key : frontConfKeys.split(",")) {
            cond.setConfigKey(key);
            List<SysConfig> data = configService.selectConfigList(cond);
            if (CollectionUtils.isEmpty(data))
            {
                SysConfig conf = new SysConfig();
                conf.setConfigKey(key);
                configList.add(conf);
            } else {
                configList.add(data.get(0));
            }
        }
        return AjaxResult.success(configList);
    }

    @ApiOperation("验证卡密码")
    @PostMapping(value = "validateCard")
    public AjaxResult validateCard(String cardNo, String password) {
        DzCards card = cardsService.selectDzCardsByCardNo(cardNo);
        boolean isSuccess = null != card && card.getPassword().equals(password);
        if (!isSuccess) {
            return AjaxResult.error("验证失败");
        }
        return AjaxResult.success("验证成功");
    }

    @ApiOperation("发送验证码(验重,验证码,不登陆)")
    @PostMapping(value = "sendSmsNoToken")
    @Anonymous
    public AjaxResult sendSmsNoToken(String mobile, SmsTypeEnum smsType, String uuid, String code){
        if(!PhoneUtils.isPhoneNumber(mobile)){
            return AjaxResult.error("手机号错误");
        }
        if (!checkCaptcha(uuid, code)) {
            return AjaxResult.error("验证码错误");
        }
        SysUser sysUser = userService.selectUserByMobile(mobile);
        if (StringUtils.isNotNull(sysUser)) {
            return AjaxResult.error("手机号已存在");
        }
        if(shortMessageService.isBlacklist(mobile)){
            return AjaxResult.error("发送频繁，请稍候再试");
        }
        return shortMessageService.sendVerifyCode(smsType, mobile);
    }


    @ApiOperation("发送验证码(不验重,验证码,不登陆)")
    @PostMapping(value = "sendSmsNoValidationNoToken")
    @Anonymous
    public AjaxResult sendSmsNoValidationNoToken(String mobile, SmsTypeEnum smsType, String uuid, String code){
        if(!PhoneUtils.isPhoneNumber(mobile)){
            return AjaxResult.error("手机号错误");
        }
        if (!checkCaptcha(uuid, code)) {
            return AjaxResult.error("验证码错误");
        }
        if(shortMessageService.isBlacklist(mobile)){
            return AjaxResult.error("发送频繁，请稍候再试");
        }
        return shortMessageService.sendVerifyCode(smsType, mobile);
    }

    @ApiOperation("发送验证码(不验重,需登陆,无验证码)")
    @PostMapping(value = "sendSms")
    public AjaxResult sendSms(String mobile, SmsTypeEnum smsType){
        return shortMessageService.sendVerifyCode(smsType, mobile);
    }

    @ApiOperation("验证码校验")
    @PostMapping(value = "validateSms")
    @Anonymous
    public AjaxResult validate(String mobile, String code){
        boolean isSuccess = shortMessageService.checkCode(mobile, code);
        if(!isSuccess){
            return AjaxResult.error("验证失败");
        }
        return AjaxResult.success("验证成功");
    }

    private Boolean checkCaptcha(String uuid, String code) {
        if (configService.isSmsCaptchaEnabled()) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (null == code || !code.equalsIgnoreCase(captcha)) {
                return false;
            }
        }
        return true;
    }

    @GetMapping("/vod/getVideoPlayAuth")
    @ApiOperation("获取视频点播授权")
    public AjaxResult getVideoPlayAuth(String videoId) throws Exception {
        VodPlayAuthDto dto = new VodPlayAuthDto();
        try {
            dto = vodUtils.getVideoPlayAuth(videoId);
        }catch (Exception e){
            log.error(e.toString());
        }
        return AjaxResult.success(dto);
    }

    @GetMapping("/vod/getVideoPlayInfo")
    @ApiOperation("获取视频播放信息")
    public AjaxResult getVideoPlayInfo(String videoId) throws Exception {
        GetPlayInfoResponse response = new GetPlayInfoResponse();
        //智隆叁加叁的vod为 “zlsjs,” 开头
        Boolean isZlsjs=true;
        try {
            if(videoId.startsWith(Constants.ZLSJS_PREFIX)|| Convert.toStrArray(videoId).length==2){
                videoId = Convert.toStrArray(videoId)[1];
                response = vodZlsjsUtils.getPlayInfo(videoId);
            }else {
                isZlsjs=false;
                response = vodUtils.getPlayInfo(videoId);
            }
        }catch (Exception e){
            if(isZlsjs){
                response = vodUtils.getPlayInfo(videoId);
            }else {
                response = vodZlsjsUtils.getPlayInfo(videoId);
            }
        }

        if(StringUtils.isNotNull(response)&& !org.springframework.util.CollectionUtils.isEmpty(response.getPlayInfoList())){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("videoId",videoId);
            jsonObject.put("palyUrl",response.getPlayInfoList().get(0).getPlayURL());
            jsonObject.put("duration",response.getPlayInfoList().get(0).getDuration());
            jsonObject.put("coverUrl",StringUtils.EMPTY);
            if(StringUtils.isNotNull(response.getVideoBase())){
                jsonObject.put("coverUrl",response.getVideoBase().getCoverURL());
                jsonObject.put("title",response.getVideoBase().getTitle());
                jsonObject.put("videoId",response.getVideoBase().getVideoId());
            }

            return AjaxResult.success(jsonObject);
        }
        return AjaxResult.error("未找到有效的url");
    }
}
