package com.td.Dawa.sys.sysGame.controller;

import com.td.Dawa.annotation.Decrypt;
import com.td.Dawa.annotation.Encrypt;
import com.td.Dawa.common.controller.CommonController;
import com.td.Dawa.common.pojo.PageInfo;
import com.td.Dawa.common.pojo.Result;
import com.td.Dawa.config.enums.GameEnum;
import com.td.Dawa.config.enums.ResultEnum;
import com.td.Dawa.game.comcharacters.service.ComCharactersService;
import com.td.Dawa.game.comcharacters.vo.ComCharactersClientVo;
import com.td.Dawa.game.comcharacters.vo.ComCharactersVo;
import com.td.Dawa.game.complayerbackpack.pojo.ComPlayerBackpack;
import com.td.Dawa.game.complayerbackpack.service.ComPlayerBackpackService;
import com.td.Dawa.game.complayerbackpack.vo.ComPlayerBackpackVo;
import com.td.Dawa.game.complayersattri.service.ComPlayersAttriService;
import com.td.Dawa.game.complayersattri.vo.ComPlayersAttriVo;
import com.td.Dawa.game.comusers.pojo.ComUsers;
import com.td.Dawa.game.comusers.service.ComUsersService;
import com.td.Dawa.game.comusers.vo.ComUsersVo;
import com.td.Dawa.game.excelcharacterattri.pojo.ExcelCharacterAttri;
import com.td.Dawa.game.excelcharacterattri.service.ExcelCharacterAttriService;
import com.td.Dawa.game.excelcharacterattri.vo.ExcelCharacterAttriVo;
import com.td.Dawa.game.excelcharactercreate.service.ExcelCharacterCreateService;
import com.td.Dawa.game.excelprop.pojo.ExcelProp;
import com.td.Dawa.game.excelprop.service.ExcelPropService;
import com.td.Dawa.game.excelprop.vo.ExcelPropClientVo;
import com.td.Dawa.game.excelprop.vo.ExcelPropVo;
import com.td.Dawa.game.excelworkpro.vo.ExcelWorkProVo;
import com.td.Dawa.util.CopyUtil;
import com.td.Dawa.util.JwtTokenUtil;
import com.td.Dawa.util.RedisData;
import com.td.Dawa.util.RedisLock;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sys/sysComUsers/")
public class sysGameUsersController extends CommonController<ComUsersVo, ComUsers, String> {
    @Autowired
    private ComUsersService comUsersService;

    @Autowired
    private ComPlayersAttriService comPlayersAttriService;

    @Autowired
    private ComPlayerBackpackService comPlayerBackpackService;

    @Autowired
    private ComCharactersService comCharactersService;

    @Autowired
    private ExcelCharacterAttriService excelCharacterAttriService;

    @Autowired
    private ExcelPropService excelPropService;

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${spring.profiles.active}")
    private String active;

    @GetMapping("user")
    public ModelAndView user() {
        return new ModelAndView("sys/aComUser/user");
    }

    @PostMapping("findGameUserByAddress")
    @Decrypt
    @Encrypt
    public Result<PageInfo<ComUsersVo>> findGameUserByAddress(ComUsersVo comUsersVo) {
        ComUsersVo comUsersVo1 = new ComUsersVo();
        ArrayList<ComUsersVo> comUsersVoList = new ArrayList<>();
        if (comUsersVo.getAddress() != null) {
            comUsersVo1 = comUsersService.findByAddress(comUsersVo.getAddress());
            comUsersVoList.add(comUsersVo1);
        }
        PageInfo<ComUsersVo> pageInfo = new PageInfo<>();
        pageInfo.setPage(1);//页码
        pageInfo.setPageSize(2);//页面大小
        pageInfo.setRows(comUsersVoList);//分页结果
        pageInfo.setRecords(comUsersVoList.size());//总记录数
        pageInfo.setTotal(1);//总页数
        return Result.of(pageInfo);
    }


    //属性表
    @GetMapping("userAttribute")
    public ModelAndView userAttribute() {
        return new ModelAndView("sys/aComUser/userAttri");
    }

    @PostMapping("findAllUserAttribute")
    @Decrypt
    @Encrypt
    public Result<PageInfo<ComPlayersAttriVo>> findAllUserAttribute(ComUsersVo comUsersVo) {

        if (comUsersVo.getAddress() != null) {
            //查询用户id
            ComUsersVo _comUsersVo = comUsersService.findByAddress(comUsersVo.getAddress());
            if (!_comUsersVo.equals(null)) {
                //如果存在用户数据，继续查询背包
                ComPlayersAttriVo vo = new ComPlayersAttriVo();
                vo.setUserId(_comUsersVo.getUserId());
                vo.setPage(comUsersVo.getPage());
                vo.setRows(comUsersVo.getRows());
                vo.setSidx(comUsersVo.getSidx());
                vo.setSord(comUsersVo.getSord());
                return comPlayersAttriService.page(vo);
            }
        }
        //没数据随便返回一个空的
        ArrayList<ComPlayersAttriVo> vo = new ArrayList<>();
        PageInfo<ComPlayersAttriVo> pageInfo = new PageInfo<>();
        pageInfo.setPage(1);//页码
        pageInfo.setPageSize(1);//页面大小
        pageInfo.setRows(vo);//分页结果
        pageInfo.setRecords(vo.size());//总记录数
        pageInfo.setTotal(1);//总页数
        return Result.of(pageInfo);
    }

    @PostMapping("saveUserAttribute")
    @Decrypt
    @Encrypt
    public Result saveUserAttribute(ComPlayersAttriVo vo) {
        Result result = comPlayersAttriService.save(vo);
        return result;
    }


    //瓦达接口相关

    /**
     * 根据地址获取用户信息
     *
     * @param address
     * @return
     */
    @PostMapping("findUserIdByAddress")
    @Decrypt
    @Encrypt
    public Result<?> findUserIdByAddress(@RequestParam("address") String address) {
        //查询用户id
        ComUsersVo _comUsersVo = comUsersService.findByAddress(address);
        if (_comUsersVo == null) {
            return Result.of(null, false, ResultEnum.USER_NOT_ADDRESS);
        }
        return Result.of(_comUsersVo);
    }

    //用户背包
    @GetMapping("userPlayerBackpack")
    public ModelAndView userPlayerBackpack() {
        //初始化背包页面时候，加载物品配置，以便添加信息
        List<ExcelProp> excelPropList = excelPropService.getListFromCache(GameEnum.REDIS_KEY_EXCEL_PROP.getMessage());

        return new ModelAndView("sys/aComUser/userPlayerBackpack","propList",CopyUtil.copyList(excelPropList,ExcelPropVo.class));
    }


    @PostMapping("findPlayerBackpack")
    @Decrypt
    @Encrypt
    public Result<?> findPlayerBackpack(ComUsersVo comUsersVo) {
        if (comUsersVo.getAddress() != null) {
            //查询用户id
            ComUsersVo _comUsersVo = comUsersService.findByAddress(comUsersVo.getAddress());
            if (!_comUsersVo.equals(null)) {
                //如果存在用户数据，继续查询背包
                ComPlayerBackpackVo vo = new ComPlayerBackpackVo();
                vo.setUserId(_comUsersVo.getUserId());
                vo.setPage(comUsersVo.getPage());
                vo.setRows(comUsersVo.getRows());
                vo.setSidx(comUsersVo.getSidx());
                vo.setSord(comUsersVo.getSord());
                return comPlayerBackpackService.page(vo);
            }
        }
        return Result.of(new PageInfo<>());
    }

    /**
     * 新增背包数据
     *
     * @param vo
     * @return
     */
    @PostMapping("savePlayerBackpack")
    @Decrypt
    @Encrypt
    public Result<?> savePlayerBackpack(ComPlayerBackpackVo vo) {
        long time = System.currentTimeMillis() + RedisData.getBackpackTimeout();
        String _redisKey = "SYS_BACKPACK_SAVE_" + vo.getUserId();
        try {
            // 防止重复操作
            if (!redisLock.lock(_redisKey, String.valueOf(time))) {
                return Result.of(null, false, "保存繁忙，稍后再试！");
            }
            //新增情况查询是否存在物品
            if (!StringUtils.hasText(vo.getId()) && comPlayerBackpackService.findByUserIdAndItemId(vo.getUserId(), vo.getItemId()) != null) {
                return Result.of(null, false, "已存在物品");
            }
            Result result = comPlayerBackpackService.save(vo);
            redisLock.unlock(_redisKey, String.valueOf(time));
            return result;
        } catch (Exception e) {
            return Result.of(null, false, "保存异常，稍后再试！");
        }
    }

    /**
     * 直接根据id添加物品
     *
     * @param userId
     * @param id
     * @return
     */
    @PostMapping("addProp")
    @Encrypt
    public Result<?> addProp(@RequestParam(value = "userId") String userId,
                                                       @RequestParam(value = "id") Integer id) {
        long time = System.currentTimeMillis() + RedisData.getCharacterTimeout();
        String _redisKey = "SYS_PROP_ADD_" + userId;
        try {
            // 防止重复操作
            if (!redisLock.lock(_redisKey, String.valueOf(time))) {
                return Result.of(null, false, "保存繁忙，稍后再试！");
            }
            //拿出一个角色对应的配置数据来生成角色
            ExcelPropVo excelPropVo = excelPropService.getVo(id);
            if (excelPropVo == null) {
                return Result.of(null, false, "没有对应物品！");
            }
            //根据roleId 对应的数据，生成玩家数据,属性
            ComPlayerBackpack comPlayerBackpack = comPlayerBackpackService.saveByUserIdAndProp(userId, CopyUtil.copy(excelPropVo,ExcelPropClientVo.class));
            return Result.of(comPlayerBackpack);
        } catch (Exception e) {
            return Result.of(null, false, "操作物品异常！");
        }
    }


    @PostMapping("deletePlayerBackpack")
    @Decrypt
    @Encrypt
    public Result deletePlayerBackpack(@RequestParam("id") String id) {
        Result result = comPlayerBackpackService.delete(id);
        return result;
    }


    //用户管理
    @GetMapping("userCharacters")
    public ModelAndView userCharacters() {
        List<ExcelCharacterAttri> excelCharacterAttris = excelCharacterAttriService.getListFromCache(GameEnum.REDIS_KEY_EXCEL_CHARACTER_ATTRI.getMessage());

        return new ModelAndView("sys/aComUser/userCharacters" ,"characterAttris",CopyUtil.copyList(excelCharacterAttris,ExcelCharacterAttriVo.class));
    }


    @PostMapping("findCharacters")
    @Decrypt
    @Encrypt
    public Result<?> findCharacters(ComUsersVo comUsersVo) {
        if (comUsersVo.getAddress() != null) {
            //查询用户id
            ComUsersVo _comUsersVo = comUsersService.findByAddress(comUsersVo.getAddress());
            if (!_comUsersVo.equals(null)) {
                //如果存在用户数据，继续查询背包
                ComCharactersVo vo = new ComCharactersVo();
                vo.setUserId(_comUsersVo.getUserId());
                vo.setPage(comUsersVo.getPage());
                vo.setRows(comUsersVo.getRows());
                vo.setSidx(comUsersVo.getSidx());
                vo.setSord(comUsersVo.getSord());
                return comCharactersService.page(vo);
            }
        }
        return Result.of(new PageInfo<>());
    }

    @PostMapping("saveCharacters")
    @Decrypt
    @Encrypt
    public Result<?> saveCharacters(ComCharactersVo vo) {
        Result result = comCharactersService.save(vo);
        return result;
    }

    /**
     * 直接根据roleId添加角色
     *
     * @param userId
     * @param roleId
     * @return
     */
    @PostMapping("addCharacters")
    @Encrypt
    public Result<ComCharactersClientVo> addCharacters(@RequestParam(value = "userId") String userId,
                                                       @RequestParam(value = "roleId") Integer roleId) {
        long time = System.currentTimeMillis() + RedisData.getCharacterTimeout();
        String _redisKey = "SYS_CHARACTERS_ADD_" + userId;
        try {
            // 防止重复操作
            if (!redisLock.lock(_redisKey, String.valueOf(time))) {
                return Result.of(null, false, "保存繁忙，稍后再试！");
            }
            //拿出一个角色对应的配置数据来生成角色
            ExcelCharacterAttriVo excelCharacterAttriVo = excelCharacterAttriService.getVo(roleId);
            if (excelCharacterAttriVo == null) {
                return Result.of(null, false, ResultEnum.ROLE_DOES_NOT_EXIST);
            }
            //根据roleId 对应的数据，生成玩家数据,属性
            ComCharactersClientVo comCharacters = comCharactersService.addRole(excelCharacterAttriVo, userId);
            return Result.of(comCharacters);
        } catch (Exception e) {
            return Result.of(null, false, ResultEnum.ROLE_ADD_ERROR);
        }
    }

    /**
     * 删除角色时候，如果正在工作，则不能删除
     *
     * @param id
     * @return
     */
    @PostMapping("deleteCharacters")
    @Decrypt
    @Encrypt
    public Result deletePlayerBackpack(@RequestParam("id") Integer id) {
        ComCharactersVo comCharactersVo = comCharactersService.getVo(id);
        if (comCharactersVo == null) {
            return Result.of(null, false, ResultEnum.ROLE_DOES_NOT_EXIST);
        }
        long time = System.currentTimeMillis() + RedisData.getCharactersTimeout();
        String _redisKey = RedisData.getCharactersKey(comCharactersVo.getUserId(), comCharactersVo.getRoleId());
        try {
            // 防止重复操作
            if (!redisLock.lock(_redisKey, String.valueOf(time))) {
                return Result.of(null, false, ResultEnum.REDIS_IS_LOCK);
            }
            if (comCharactersVo.getProfessional().equals(GameEnum.PRO_WORK_NORMAL.getValue())) {
                //如果没指派工作，可以删除 ，加操作锁
                Result result = comCharactersService.delete(id);
                return result;
            } else {
                return Result.of(null, false, ResultEnum.ROLE_WORK_ING);
            }
        } catch (Exception e) {
            return Result.of(e.getMessage(), false, ResultEnum.ROLE_DELETE_ERROR);
        } finally {
            redisLock.unlock(_redisKey, String.valueOf(time));
        }
    }
}
