package cn.pluss.platform.controller.userRewardInfo;


import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.areaCity.AreaCityService;
import cn.pluss.platform.base.BaseModelController;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.enums.UserRoleEnum;
import cn.pluss.platform.rewardConfig.RewardConfigService;
import cn.pluss.platform.user.UserRoleService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.userRewardInfo.UserRewardInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 用户奖励信息表 前端控制器
 * </p>
 *
 * @author bzg
 * @since 2022-02-22
 */
@Controller
@RequestMapping("/userRewardInfo")
public class UserRewardInfoController extends BaseModelController<UserRewardInfoService, UserRewardInfo> {

    @Resource
    private AreaCityService areaCityService;

    @Resource
    private UserAppService userAppService;

    @Resource
    private RewardConfigService rewardConfigService;

    @Resource
    private UserInfoService userInfoService;

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/index")
    public String index(HttpServletRequest request) {
        return "userRewardInfo/list";
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = {"/detail/{id}", "/detail"})
    public String detail(HttpServletRequest request, @PathVariable(value = "id", required = false) Integer id) {
        List<AreaCity> areaCities = areaCityService.queryOnlyProvince();
        List<RewardConfig> list = rewardConfigService.list();
        if (id != null) {
            UserRewardInfo entity = baseService.getById(id);
            if(entity != null){
                UserInfo userInfo = userInfoService.getById(entity.getUserId());
                if(userInfo == null){
                    entity.setLoginName(userInfo.getLoginName());
                }
            }
            request.setAttribute("entity", entity);
        }
        request.setAttribute("pList", areaCities);
        request.setAttribute("rList", list);
        return "userRewardInfo/detail";
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/save")
    @Override
    public Result<String> save(@RequestBody UserRewardInfo entity) {
        try {
            if(StringUtils.isEmpty(entity.getLoginName()) && entity.getUserId() == null){
                return ResultGenerator.genFailResult("缺失用户ID和登录账号至少填写一个");
            }
            String loginName = entity.getLoginName();
            UserInfo info = null;
            if(StringUtils.isNotEmpty(loginName)){
                info = userInfoService.getUserInfoByLoginName(loginName);
                if(info == null){
                    return ResultGenerator.genFailResult("登录账号有误！");
                }
            }else{
                 info = userInfoService.getById(entity.getUserId());
                if(info == null){
                    return ResultGenerator.genFailResult("用户ID有误！");
                }

            }
            entity.setPhone(info.getPhone());
            entity.setUserId(Integer.valueOf(info.getId().toString()));
            if(entity.getUserId() == null){
                return ResultGenerator.genFailResult("缺失userId");
            }
            if(entity.getReId() == null){
                return ResultGenerator.genFailResult("缺失奖励ID");
            }
            UserApp userApp = userAppService.getUserAppByUserId(entity.getUserId());
            if(userApp == null){
                return ResultGenerator.genFailResult("无效的用户ID参数");
            }
            RewardConfig byId = rewardConfigService.getById(entity.getReId());
            if(byId == null){
                return ResultGenerator.genFailResult("当前奖励类型配置不存在");
            }
            if(!byId.getRoleCode().equals(userApp.getRoleCode())){
                return ResultGenerator.genFailResult("当前奖励所属类型和用户类型不匹配！");
            }
            entity.setRName(byId.getName());
            if(entity.getId() == null){
                QueryWrapper<UserRewardInfo> queryWrapper = new QueryWrapper<UserRewardInfo>()
                        .eq("userId",entity.getUserId()).likeRight("areaNo",entity.getAreaNo());
                List<UserRewardInfo> list = this.baseService.list(queryWrapper);
                if(!list.isEmpty()){
                    return ResultGenerator.genFailResult("区域设置有误，当前设置区域已经存在，或已被包含！");
                }
            }
            try {
                super.save(entity);
                //设置成区域合伙人
                userApp.setAreaMark(1);
                userAppService.updateById(userApp);
                return ResultGenerator.genSuccessResult("操作成功",null);
            }catch (Exception e){
                return ResultGenerator.genFailResult("唯一约束冲突，当前用户已经存在一个该区域的配置，请勿重复添加");
            }
        }catch (Exception e){
            return ResultGenerator.genFailResult("系统开小差了");
        }
    }

    @Override
    public Result<Page<UserRewardInfo>> page(Page<UserRewardInfo> page, UserRewardInfo condition, OrderItem orderItem) {
        orderItem.setColumn("createTime");
        orderItem.setAsc(false);
        return super.page(page, condition, orderItem);
    }

    @RequestMapping(value = "getAreaInfo")
    @ResponseBody
    public Result<List<AreaCity>> getAreaInfo() {
        List<AreaCity> areaCities = areaCityService.queryProvince();
        return ResultGenerator.genSuccessResult("查询成功",areaCities);
    }

    @RequestMapping(value = "/getNextAreaInfo/{areaCode}")
    @ResponseBody
    public Result<List<AreaCity>> getNextAreaInfo(@PathVariable("areaCode") String areaCode) {
        List<AreaCity> list = areaCityService.queryParentCode(areaCode);
        return ResultGenerator.genSuccessResult("查询成功",list);
    }



}
