package com.vctgo.system.controller;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.vctgo.common.core.constant.CacheConstants;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.SysPlatformUser;
import com.vctgo.system.api.domain.dto.VoteExpertWorkingPlatformDto;
import com.vctgo.system.api.domain.vo.VoteExpertSubmissionVo;
import com.vctgo.system.api.domain.vo.VoteExpertWorkingPlatformVo;
import com.vctgo.system.api.model.LoginUser;
import com.vctgo.system.service.ISysPlatformUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.vctgo.common.log.annotation.Log;
import com.vctgo.common.log.enums.BusinessType;
import com.vctgo.common.security.annotation.RequiresPermissions;
import com.vctgo.system.domain.SysPlatformExpert;
import com.vctgo.system.service.ISysPlatformExpertService;
import com.vctgo.common.core.web.controller.BaseController;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.core.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;

/**
 * 专家附属信息Controller
 *
 * @author caesar
 * @date 2024-03-27
 */
@Api(tags = "专家附属信息")
@RestController
@RequestMapping("/plat/expert")
public class SysPlatformExpertController extends BaseController {

    @Autowired
    private ISysPlatformExpertService sysPlatformExpertService;

    @Autowired
    private ISysPlatformUserService sysPlatformUserService;

    @Autowired
    private ISysPlatformUserService userService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询专家附属信息分页列表
     */
    @RequiresPermissions("system:platform:expert:page")
    @GetMapping("/page")
    public AjaxResult page(SysPlatformExpert sysPlatformExpert) {
        IPage<SysPlatformExpert> pageList = sysPlatformExpertService.selectSysPlatformExpertPage(sysPlatformExpert);
        return AjaxResult.success(pageList);
    }

    /**
     * 导出专家附属信息列表
     */
    @RequiresPermissions("system:platform:expert:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPlatformExpert sysPlatformExpert) {
        List<SysPlatformExpert> list = sysPlatformExpertService.selectSysPlatformExpertList(sysPlatformExpert);
        ExcelUtil<SysPlatformExpert> util = new ExcelUtil<SysPlatformExpert>(SysPlatformExpert.class);
        util.exportExcel(response, list, "专家附属信息数据");
    }

    /**
     * 获取专家附属信息详细信息
     */
    @RequiresPermissions("system:platform:expert:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success((sysPlatformExpertService.selectSysPlatformExpertById(id)));
    }

    /**
     * 新增专家附属信息
     */
    @Transactional
    @RequiresPermissions("system:platform:expert:add")
    @PostMapping
    public AjaxResult add(@RequestBody SysPlatformExpert sysPlatformExpert) {
        return toAjax(sysPlatformExpertService.insertSysPlatformExpert(sysPlatformExpert));
    }

    /**
     * 修改专家附属信息
     */
    @Transactional
    @RequiresPermissions("system:platform:expert:edit")
    @PutMapping
    public AjaxResult edit(@RequestBody SysPlatformExpert sysPlatformExpert) {
        return toAjax(sysPlatformExpertService.updateSysPlatformExpert(sysPlatformExpert));
    }

    /**
     * 逻辑删除专家附属信息
     */
    @Transactional
    @RequiresPermissions("system:platform:expert:abandon")
    @PutMapping("/abandon/{ids}")
    public AjaxResult abandon(@PathVariable Long[] ids, Long userId) {
        return AjaxResult.success(sysPlatformExpertService.logicalDeleteSysPlatformExpertByIds(ids, userId));
    }

    /**
     * 删除专家附属信息
     */
    @RequiresPermissions("system:platform:expert:remove")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysPlatformExpertService.deleteSysPlatformExpertByIds(ids));
    }

    /**
     * 添加账号
     */
    @Transactional
    @RequiresPermissions("system:platform:expert:resetPwd")
    @PutMapping("/addAccount")
    public AjaxResult addAccount(@RequestBody SysPlatformExpert sysPlatformExpert) {
        //专家信息
        sysPlatformExpertService.updateSysPlatformExpert(sysPlatformExpert);

        // 设置角色
        sysPlatformUserService.deleteUserRoleByUserId(sysPlatformExpert.getUserId());
        sysPlatformUserService.insertUserRole(sysPlatformExpert.getUserId(), sysPlatformExpert.getRoleIds());

        // 设置密码
        String randomPassword = SecurityUtils.randomPassword(6);//随机密码6位
        SysPlatformUser user = new SysPlatformUser();
        user.setUserId(sysPlatformExpert.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(randomPassword));
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateById(SecurityUtils.getUserId());
        userService.resetPwd(user);

        return AjaxResult.success(randomPassword);
    }

    /**
     * 修改状态
     */
    @Transactional
    @RequiresPermissions("system:platform:expert:resetPwd")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysPlatformExpert sysPlatformExpert) {
        //专家信息
        sysPlatformExpertService.updateSysPlatformExpert(sysPlatformExpert);

        // 设置角色
        sysPlatformUserService.deleteUserRoleByUserId(sysPlatformExpert.getUserId());
        sysPlatformUserService.insertUserRole(sysPlatformExpert.getUserId(), sysPlatformExpert.getRoleIds());

        // 强制该用户退出登录
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser)
                    && Objects.nonNull(onlineUser.getUserid())
                    && onlineUser.getUserid().longValue() == sysPlatformExpert.getUserId().longValue()) {
                redisService.deleteObject(key);
            }
        }

        return AjaxResult.success();
    }

    /**
     * 重置密码
     */
    @Transactional
    @RequiresPermissions("system:platform:expert:resetPwd")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysPlatformUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());

        // 设置密码
        String randomPassword = SecurityUtils.randomPassword(6);//随机密码6位
        user.setPassword(SecurityUtils.encryptPassword(randomPassword));
        user.setUpdateBy(SecurityUtils.getUsername());
        userService.resetPwd(user);

        // 强制该用户退出登录
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser)
                    && Objects.nonNull(onlineUser.getUserid())
                    && onlineUser.getUserid().longValue() == user.getUserId().longValue()) {
                redisService.deleteObject(key);
            }
        }

        return AjaxResult.success(randomPassword);
    }

    /**
     * 专家平台分页
     */
    @GetMapping("/expertPage")
    public AjaxResult expertPage(VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto) {
        IPage<VoteExpertWorkingPlatformVo> page = sysPlatformExpertService.expertPage(voteExpertWorkingPlatformDto);
        return AjaxResult.success(page);
    }


    /**
     * 专家作品分页
     */
    @GetMapping("/submissionList")
    public AjaxResult submissionList(VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto) {
        IPage<VoteExpertSubmissionVo> page = sysPlatformExpertService.submissionList(voteExpertWorkingPlatformDto);
        return AjaxResult.success(page);
    }

    /**
     * 专家评分作品数
     */
    @GetMapping("/count")
    public AjaxResult count(VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto) {
        return AjaxResult.success(sysPlatformExpertService.submissionCount(voteExpertWorkingPlatformDto));
    }


    @GetMapping("/item/{ruleId}")
    public AjaxResult item(@PathVariable("ruleId") Long ruleId) {
        return AjaxResult.success(sysPlatformExpertService.item(ruleId));
    }

    @GetMapping("/eventDetails/{eventId}")
    public AjaxResult eventDetails(@PathVariable("eventId") Long eventId) {
        return AjaxResult.success(sysPlatformExpertService.eventDetails(eventId));
    }

    /**
     * 作品详情
     */
    @GetMapping("/submissionDetails")
    public AjaxResult submissionDetails (VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto){
        return AjaxResult.success(sysPlatformExpertService.submissionDetails(voteExpertWorkingPlatformDto));
    }

    /**
     * 提交评分
     */
    @PostMapping("/commitGrade")
    public AjaxResult commitGrade(@RequestBody VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto){
        return AjaxResult.success(sysPlatformExpertService.commitGrade(voteExpertWorkingPlatformDto));
    }



}
