package com.fs.company.controller.live;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.http.HttpUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.CompanyUser;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.fs.framework.service.TokenService;
import com.fs.live.domain.Live;
import com.fs.live.domain.LiveCompanyCode;
import com.fs.live.service.ILiveCompanyCodeService;
import com.fs.live.service.ILiveService;
import com.fs.live.vo.LiveListVo;
import com.fs.system.oss.OSSFactory;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 直播Controller
 *
 * @author fs
 * @date 2025-01-17
 */
@RestController
@RequestMapping("/live/live")
public class LiveController extends BaseController
{
    @Autowired
    private ILiveService liveService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ILiveCompanyCodeService liveCompanyCodeService;

    /**
     * 查询未结束直播间
     */
    @PreAuthorize("@ss.hasPermi('live:live:list')")
    @GetMapping("/listToLiveNoEnd")
    public TableDataInfo listToLiveNoEnd(Live live)
    {
        startPage();
        List<Live> list = liveService.listToLiveNoEnd(live);
        return getDataTable(list);
    }

    /**
     * 查询直播列表
     */
    @PreAuthorize("@ss.hasPermi('live:live:list')")
    @GetMapping("/list")
    public TableDataInfo list(Live live)
    {
        // 设置企业ID和企业用户ID
        setCompanyId(live);

        startPage();
        List<Live> list = liveService.selectLiveList(live);
        return getDataTable(list);
    }

    /**
     * 查询直播列表
     */
    @PreAuthorize("@ss.hasPermi('live:live:selectLiveToStudent')")
    @PostMapping("/selectLiveToStudent")
    public TableDataInfo selectLiveToStudent(@RequestBody Map<String,String> param)
    {
        startPage();
        String liveName = param.get("liveName");
        String status = param.get("status");
        String startTime = param.get("startTime");
        String finishTime = param.get("finishTime");
        List<Live> list = liveService.selectLiveToStudent(liveName,status,startTime,finishTime);
        return getDataTable(list);
    }

    /**
     * 导出直播列表
     */
    @PreAuthorize("@ss.hasPermi('live:live:export')")
    @Log(title = "直播", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Live live)
    {
        // 设置企业ID和企业用户ID
        setCompanyId(live);


        List<Live> list = liveService.selectLiveList(live);
        ExcelUtil<Live> util = new ExcelUtil<Live>(Live.class);
        return util.exportExcel(list, "直播数据");
    }

    /**
     * 获取直播详细信息
     */
    @PreAuthorize("@ss.hasPermi('live:live:query')")
    @GetMapping(value = "/{liveId}")
    public AjaxResult getInfo(@PathVariable("liveId") Long liveId)
    {
        CompanyUser user = SecurityUtils.getLoginUser().getUser();
        return AjaxResult.success(liveService.selectLiveByLiveIdAndCompanyIdAndCompanyUserId(liveId, user.getCompanyId(), user.getUserId()));
    }



    /**
     * 新增直播
     */
    @PreAuthorize("@ss.hasPermi('live:live:add')")
    @Log(title = "直播", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Live live)
    {
        // 设置企业ID和企业用户ID
        setCompanyId(live);
        return toAjax(liveService.insertLive(live));
    }

    /**
     * 结束直播
     */
    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    @GetMapping("/finishLive")
    public R finishLive(Live live) {
        CompanyUser user = SecurityUtils.getLoginUser().getUser();
        live.setCompanyUserId(user.getUserId());
        live.setCompanyId(user.getCompanyId());
        return liveService.finishLive(live);
    }

    /**
     * 复制直播
     */
    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    @GetMapping("/copyLive")
    public R copyLive(Live live) {
        CompanyUser user = SecurityUtils.getLoginUser().getUser();
        live.setCompanyUserId(user.getUserId());
        live.setCompanyId(user.getCompanyId());
        return liveService.copyLive(live);
    }

    /**
     * 开启直播
     */
    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    @GetMapping("/startLive")
    public R startLive(Live live) {
        CompanyUser user = SecurityUtils.getLoginUser().getUser();
        live.setCompanyUserId(user.getUserId());
        live.setCompanyId(user.getCompanyId());
        return liveService.startLive(live);
    }

    /**
     * 修改直播
     */
    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    @Log(title = "直播", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Live live)
    {
        return toAjax(liveService.updateLive(live));
    }

    /**
     * 删除直播
     */
    @PreAuthorize("@ss.hasPermi('live:live:remove')")
    @Log(title = "直播", businessType = BusinessType.DELETE)
	@DeleteMapping("/{liveIds}")
    public AjaxResult remove(@PathVariable Long[] liveIds)
    {
        return toAjax(liveService.deleteLiveByLiveIds(liveIds));
    }

    @PreAuthorize("@ss.hasPermi('live:live:query')")
    @GetMapping("/living/{liveId}")
    public R getRoom(@PathVariable String liveId) {
        return liveService.getLiveRoom(liveId);
    }

    @PreAuthorize("@ss.hasPermi('live:live:query')")
    @PostMapping("/checkLive")
    public R checkLiving(@RequestBody Map<String, String> payload) {
        return liveService.checkLiving(payload);
    }

    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    @PostMapping("/closeLiving")
    public R closeLiving(@RequestBody Map<String, String> payload) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        payload.put("userId", loginUser.getUser().getUserId().toString());
        return liveService.closeLiving(payload);
    }

    @PreAuthorize("@ss.hasPermi('live:live:insert')")
    @PostMapping("/create")
    public R createRoom(@RequestBody Map<String, Object> payload) {
        if (!payload.containsKey("liveId")) {
            return R.error("直播间id缺失");
        }
        Long liveId = Long.valueOf(payload.get("liveId").toString());
        return liveService.createLiveRoom(liveId);
    }

    /**
     * 校验上传的身份证信息
     */
    @PreAuthorize("@ss.hasPermi('live:live:insert')")
    @PostMapping("/verifyIdInfo")
    public R verifyIdInfo(@RequestBody Map<String, String> payload) {
        return liveService.verifyIdInfo(payload);
    }

    /**
     * 开始循环播放视频
     */
    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    @PostMapping("/startLoopPlay")
    public R startLoopPlay(@RequestBody Live live) {
        return liveService.startLoopPlay(live);
    }

    /**
     * 停止循环播放
     */
    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    @PostMapping("/stopLoopPlay")
    public R stopLoopPlay(@RequestBody Live live) {
        return liveService.stopLoopPlay(live);
    }

    /**
     * 批量上下架视频
     */
    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    @PostMapping("/handleShelfOrUn")
    public R handleShelfOrUn(@RequestBody LiveListVo listVo) {
        setListCompanyId(listVo);
        return liveService.handleShelfOrUn(listVo);
    }

    /**
     * 批量删除视频
     */
    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    @PostMapping("/handleDeleteSelected")
    public R handleDeleteSelected(@RequestBody LiveListVo listVo) {
        setListCompanyId(listVo);
        return liveService.handleDeleteSelected(listVo);
    }



    /**
     * 设置企业ID和企业用户ID
     * @param live 直播间
     */
    private void setCompanyId(Live live) {
        CompanyUser user = SecurityUtils.getLoginUser().getUser();
        live.setCompanyId(user.getCompanyId());
        live.setCompanyUserId(user.getUserId());
    }

    /**
     * 设置企业ID和企业用户ID
     * @param live 直播间
     */
    private void setListCompanyId(LiveListVo live) {
        CompanyUser user = SecurityUtils.getLoginUser().getUser();
        live.setCompanyId(user.getCompanyId());
        live.setCompanyUserId(user.getUserId());
    }

    @ApiOperation("查询微信urlScheme")
    @GetMapping("/getAppletScheme")
    public R getAppletScheme(@RequestParam(value = "cardId") Long cardId) {
        try {
            String appId = "123";
            String secret = "123";
            String rspStr = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&" + "appid=" + appId + "&secret=" + secret);
            JSONObject obj = JSONObject.parseObject(rspStr);
            String access_token = obj.getString("access_token");
            JSONObject jsonObject = new JSONObject();
            JSONObject jump_wxaObj = new JSONObject();
            jump_wxaObj.put("path", "/pages_company/card");
            jump_wxaObj.put("query", "id=" + cardId);
            jsonObject.put("jump_wxa", jump_wxaObj);
            jsonObject.put("is_expire", false);
            String paramStr = jsonObject.toJSONString();
            String postStr = HttpUtils.sendPost("https://api.weixin.qq.com/wxa/generatescheme?access_token=" + access_token, paramStr);
            obj = JSONObject.parseObject(postStr);
            //response.addHeader("Access-Control-Allow-Origin", "*");
            return R.ok().put("result", obj);
        } catch (Exception e) {
            return R.error("操作失败");
        }
    }

    @ApiOperation("生成微信小程序码")
    @GetMapping("/getWxaCodeUnLimit")
    @PreAuthorize("@ss.hasPermi('live:live:edit')")
    public R getWxaCodeUnLimit(@RequestParam(value = "liveId") Long liveId) {
        String url="https://api.weixin.qq.com/cgi-bin/stable_token";
        HashMap<String, String> map = new HashMap<>();
        map.put("grant_type","client_credential");
        // 百域承品
        map.put("appid","wx44beed5640bcb1ba");
        map.put("secret","1bfcfa420f741801575a74d94752d014");
        String accessToken = HttpUtils.endApi(url, null, map);
        // 创建Gson对象
        Gson gson = new Gson();
        // 将JSON字符串解析为Java对象
        Map<String, String> accessTokenMap  = gson.fromJson(accessToken, new TypeToken<Map<String, Object>>(){}.getType());
        String codeUrl="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessTokenMap.get("access_token");
        HashMap<String, String> jsonMap = new HashMap<>();
        jsonMap.put("page","pages_course/living");
        CompanyUser user = SecurityUtils.getLoginUser().getUser();
        String scene = "a="+ liveId+"&b="+user.getCompanyId()+"&c="+user.getUserId();
        jsonMap.put("scene",scene);
        //正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        jsonMap.put("env_version","release");
        byte[] bytes = HttpUtils.getWechatQrcodeByHttpURL(codeUrl, jsonMap);
        if(bytes.length == 0) return R.error("生成二维码失败");
        if (bytes.length > 0 && bytes.length < 500) {
            String errorCode = new String(bytes, StandardCharsets.UTF_8);
            logger.error(errorCode);
            return R.error("生成二维码失败");
        }
        // 保存
        String saveUrl = OSSFactory.build().uploadSuffix(bytes, ".png");
        Date nowDate = DateUtils.getNowDate();
        LiveCompanyCode exist = liveCompanyCodeService.selectByLiveIdAndUser(liveId, user.getCompanyId(), user.getUserId());
        if (exist == null) {
            exist = new LiveCompanyCode();
            exist.setUpdateTime(nowDate);
            exist.setLiveCodeUrl(saveUrl);
            exist.setLiveId(liveId);
            exist.setCompanyId(user.getCompanyId());
            exist.setCompanyUserId(user.getUserId());
            exist.setCreateTime(nowDate);
            liveCompanyCodeService.insertLiveCompanyCode(exist);
        } else {
            exist.setUpdateTime(nowDate);
            exist.setLiveCodeUrl(saveUrl);
            liveCompanyCodeService.updateLiveCompanyCode(exist);
        }

        return R.ok().put("data", exist);
    }
}
