package com.miaxis.pc.controller.vip;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miaxis.common.constant.Constants;
import java.util.List;
import java.util.Arrays;
import java.util.Random;

import com.miaxis.common.core.domain.entity.SysRole;
import com.miaxis.common.core.domain.entity.SysUser;
import com.miaxis.common.core.domain.vo.AgentVO;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.SecurityUtils;
import com.miaxis.system.service.ISysRoleService;
import com.miaxis.system.service.ISysUserService;
import com.miaxis.vip.dto.QueryVipCodeListDTO;
import io.swagger.annotations.*;
import com.miaxis.common.core.domain.Response;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.ModelAttribute;
import com.miaxis.common.annotation.Log;
import com.miaxis.common.core.controller.BaseController;
import com.miaxis.common.enums.BusinessTypeEnum;
import com.miaxis.vip.domain.VipCode;
import com.miaxis.vip.service.IVipCodeService;
import com.miaxis.common.utils.poi.ExcelUtil;
import com.miaxis.common.core.page.ResponsePageInfo;

/**
 * 【激活码】Controller
 *
 * @author miaxis
 * @date 2021-08-18
 */
@RestController
@RequestMapping("/vip/code")
@Api(tags={"【pc-激活码】"})
public class VipCodeController extends BaseController{
    @Autowired
    private IVipCodeService vipCodeService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 查询激活码列表
     */
    @PreAuthorize("@ss.hasPermi('vip:code:list')")
    @GetMapping("/list")
    @ApiOperation("查询激活码列表")
        @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "当前页码" ,dataType = "int", paramType = "query", required = false),
            @ApiImplicitParam(name = "pageSize",value = "每页数据量" , dataType = "int", paramType = "query", required = false),
    })
    public ResponsePageInfo<VipCode> list(QueryVipCodeListDTO dto){
        startPage();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        dto.setAgentId(user.getUserId()==1l? dto.getAgentId(): user.getUserId());
        List<VipCode> list = vipCodeService.selectVipCodeList(dto);
        return toResponsePageInfo(list);
    }


    /**
     * 查询代理商列表
     */
    @PreAuthorize("@ss.hasPermi('vip:code:list')")
    @GetMapping("/agentList")
    @ApiOperation("查询代理商列表")
    public Response<List<AgentVO>> agentList(String agentName){
        SysRole sysRole = new SysRole();
        sysRole.setRoleKey("agent");
        List<SysRole> sysRoles = roleService.selectRoleList(sysRole);
        Long roleId = sysRoles.get(0).getRoleId();
        List<AgentVO> sysUsersList =  userService.getAgentList(roleId,agentName);
        return Response.success(sysUsersList);
    }

    /**
     * 导出激活码列表
     */
    @PreAuthorize("@ss.hasPermi('vip:code:export')")
    @Log(title = "激活码", businessType = BusinessTypeEnum.EXPORT)
    @GetMapping("/export")
    @ApiOperation("导出激活码列表Excel")
    public Response<String> export(@ModelAttribute QueryVipCodeListDTO queryVipCodeListDTO){
        List<VipCode> list = vipCodeService.selectVipCodeList(queryVipCodeListDTO);
        ExcelUtil<VipCode> util = new ExcelUtil<VipCode>(VipCode.class);
        return util.exportExcel(list, "code");
    }

    /**
     * 获取激活码详细信息
     */
    @PreAuthorize("@ss.hasPermi('vip:code:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取激活码详细信息")
    public Response<VipCode> getInfo(
            @ApiParam(name = "id", value = "激活码参数", required = true)
            @PathVariable("id") Long id
    ){
        return Response.success(vipCodeService.getById(id));
    }

    /**
     * 新增激活码
     */
    @PreAuthorize("@ss.hasPermi('vip:code:add')")
    @Log(title = "激活码", businessType = BusinessTypeEnum.INSERT)
    @PostMapping
    @ApiOperation("新增激活码")
    public Response<String> add(){
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.getAgentType() == null) {
            throw new CustomException("用户还未成为会员");
        }
        if ( "1".equals(sysUser.getAgentType()) && sysUser.getAgentRemainingNumber() <= 0){
            throw new CustomException("剩余券码已不足");
        }
        if ( "2".equals(sysUser.getAgentType()) && sysUser.getAgentExpireTime().getTime()< System.currentTimeMillis()){
            throw new CustomException("代理权限已过期");
        }
        VipCode vipCode = new VipCode();
        String rVipCode = null ;
        do {
            rVipCode  = randomVipcode();
        }while (isRepeat(rVipCode));
        vipCode.setVipCode(rVipCode);
        vipCode.setAgentId(SecurityUtils.getLoginUser().getUser().getUserId());
        vipCodeService.save(vipCode);
        if ( "1".equals(sysUser.getAgentType()) ){
            userService.updateAgentRemainingNumber(sysUser.getUserId());
        }
        return Response.success(rVipCode);
    }

    private boolean isRepeat(String rVipCode) {
        QueryWrapper<VipCode> wrapper = new QueryWrapper<VipCode>();
        wrapper.eq("vip_code",rVipCode);
        VipCode one = vipCodeService.getOne(wrapper);
        return one!= null;

    }

    private String randomVipcode() {
        String result = "";
        Random random = new Random();
        for(int i =0 ;i <11 ;i ++){
            result+=random.nextInt(10);
        }
        return  result;


    }

    /**
     * 修改激活码
     */
    @PreAuthorize("@ss.hasPermi('vip:code:edit')")
    @Log(title = "激活码", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    @ApiOperation("修改激活码")
    public Response<Integer> edit(@RequestBody VipCode vipCode){
        return toResponse(vipCodeService.updateById(vipCode) ? 1 : 0);
    }

    /**
     * 删除激活码
     */
    @PreAuthorize("@ss.hasPermi('vip:code:remove')")
    @Log(title = "激活码", businessType = BusinessTypeEnum.DELETE)
	@DeleteMapping("/{ids}")
    @ApiOperation("删除激活码")
    public  Response<Integer> remove(
            @ApiParam(name = "ids", value = "激活码ids参数", required = true)
            @PathVariable Long[] ids
    ){
        return toResponse(vipCodeService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


}
