package com.ruoyi.web.controller.front;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.AccessFromType;
import com.ruoyi.common.enums.ExamType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dz.domain.DzCards;
import com.ruoyi.dz.domain.DzClasses;
import com.ruoyi.dz.domain.DzControl;
import com.ruoyi.dz.domain.DzSchool;
import com.ruoyi.dz.service.IDzCardsService;
import com.ruoyi.dz.service.IDzClassesService;
import com.ruoyi.dz.service.IDzControlService;
import com.ruoyi.dz.service.IDzSchoolService;
import com.ruoyi.enums.CardDistributeStatus;
import com.ruoyi.enums.CardStatus;
import com.ruoyi.enums.UserTypeEnum;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.web.service.CommService;
import com.ruoyi.web.service.SysLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/front/user")
@Api(tags = "前台-用户")
public class UserController extends BaseController {
    private final IDzControlService dzControlService;
    private final SysLoginService loginService;
    private final SysPermissionService permissionService;
    private final TokenService tokenService;
    private final CommService commService;
    private final ISysConfigService configService;
    private final IDzCardsService dzCardsService;
    private final IDzSchoolService dzSchoolService;
    private final IDzClassesService dzClassesService;

    public UserController(IDzControlService dzControlService, SysLoginService loginService, SysPermissionService permissionService, TokenService tokenService, CommService commService, ISysConfigService configService, IDzCardsService dzCardsService, IDzSchoolService dzSchoolService, IDzClassesService dzClassesService) {
        this.dzControlService = dzControlService;
        this.loginService = loginService;
        this.permissionService = permissionService;
        this.tokenService = tokenService;
        this.commService = commService;
        this.configService = configService;
        this.dzCardsService = dzCardsService;
        this.dzSchoolService = dzSchoolService;
        this.dzClassesService = dzClassesService;
    }

    @GetMapping(value = "provinces")
    @Anonymous
    @ApiOperation("省份列表")
    public AjaxResult provinces()
    {
        DzControl cond = new DzControl();
        cond.setIsValid(1);
        return AjaxResult.success(dzControlService.selectDzControlList(cond).stream().map(t -> {
            JSONObject o = new JSONObject();
            o.put("dictValue", t.getLocation());
            o.put("dictLabel", t.getLocation());
            return o;
        }).collect(Collectors.toList()));
    }

    @GetMapping(value = "examTypes")
    @Anonymous
    @ApiOperation("考生类型列表")
    public AjaxResult examTypes(@RequestParam String location)
    {
        DzControl cond = new DzControl();
        cond.setIsValid(1);
        cond.setLocation(location);
        List<DzControl> list = dzControlService.selectDzControlList(cond);
        String examTypes;
        if(CollectionUtils.isEmpty(list) || StringUtils.isBlank(examTypes = list.get(0).getExamTypes())) {
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(Arrays.stream(examTypes.split(",")).map(t -> {
            JSONObject o = new JSONObject();
            o.put("dictValue", t);
            o.put("dictLabel", ExamType.valueOf(t).title());
            return o;
        }).collect(Collectors.toList()));
    }

    @GetMapping(value = "examMajors")
    @Anonymous
    @ApiOperation("专业类别列表")
    public AjaxResult examMajor(@RequestParam String location, @RequestParam ExamType examType)
    {
        List<JSONObject> list = new ArrayList<>();
        if(ExamType.VHS.equals(examType)) {
            JSONObject o = new JSONObject();
            o.put("dictValue", 1);
            o.put("dictLabel", "农林类");
            list.add(o);
            o = new JSONObject();
            o.put("dictValue", 2);
            o.put("dictLabel", "养殖类");
            list.add(o);
        }
        return AjaxResult.success(list);
    }

    @GetMapping(value = "graduateYears")
    @Anonymous
    @ApiOperation("毕业年份列表")
    public AjaxResult graduateYear(@RequestParam String location, @RequestParam ExamType examType)
    {
//        DzControl cond = new DzControl();
//        cond.setIsValid(1);
//        cond.setLocation(location);
//        List<DzControl> list = dzControlService.selectDzControlList(cond);
//        Integer year;
//        if(CollectionUtils.isEmpty(list) || null == (year = list.get(0).getSubmitYear())) {
//            year = Calendar.getInstance().get(Calendar.YEAR);
//        }
//        List<JSONObject> resultList = new ArrayList<>();
//        for(int i = year; i <= year + 6; i++) {
//            JSONObject o = new JSONObject();
//            o.put("dictValue", i);
//            o.put("dictLabel", String.valueOf(i));
//            resultList.add(o);
//        }ss
        int begin = 2026;
        int end = ExamType.VHS.equals(examType) ? 2028 : 2026;
        List<JSONObject> resultList = new ArrayList<>();
        for(int i = begin; i<= end; i++) {
            JSONObject o = new JSONObject();
            o.put("dictValue", i);
            o.put("dictLabel", String.valueOf(i));
            resultList.add(o);
        }

        return AjaxResult.success(resultList);
    }

    @GetMapping("/getSchoolList")
    @Anonymous
    @ApiOperation("查询学校列表")
    public TableDataInfo getSchoolList(@ApiParam("keyword") String keyword)
    {
        DzSchool dzSchool = new DzSchool();
        dzSchool.setCampus(false);
        dzSchool.setName(keyword);
        startPage();
        List<DzSchool> list = dzSchoolService.selectDzSchoolList(dzSchool);
        return getDataTable(list);
    }

    @GetMapping("/getClassList")
    @Anonymous
    @ApiOperation("查询学校班级列表")
    public AjaxResult getClassList(@ApiParam("schoolId") Long schoolId)
    {
        DzClasses cCond = new DzClasses();
        cCond.setSchoolId(schoolId);
        List<DzClasses> list = dzClassesService.selectDzClassesList(cCond);
        return AjaxResult.success(list);
    }



    /**
     * 登录方法
     *
     * @param loginBody 登录信息i
     * @return 结果
     */
    @PostMapping("userLogin")
    @ApiOperation("前台登陆")
    @Anonymous
    public AjaxResult userLogin(@RequestBody LoginBody loginBody)
    {
        // 生成令牌
        AjaxResult ajax = loginService.login(loginBody.getMobile(), loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation("前台个人信息")
    public AjaxResult getInfo(HttpServletRequest request)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("card", loginUser.getCard());
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("isDefaultModifyPwd", commService.initPasswordIsModify(user.getPwdUpdateDate()));
        ajax.put("isPasswordExpired", commService.passwordIsExpiration(user.getPwdUpdateDate()));

        //获取app的配置文件
        String type = request.getHeader("type");
        //H5 wechat frontApp均需要菜单
        if(AccessFromType.isFrontApp(type)||AccessFromType.isH5(type)||AccessFromType.isWechat(type)){
            String appConfig = configService.selectConfigByKey("app.common.config");
            com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(appConfig);
            ajax.put("appConfig", json);
        }
        return ajax;
    }

    @PostMapping("verifyCard")
    @ApiOperation("校验卡")
    @Anonymous
    public AjaxResult verifyCard(@ApiParam("卡号") @RequestParam String cardNo, @ApiParam("密码") @RequestParam String password)
    {
        DzCards cards = dzCardsService.selectDzCardsByCardNo(cardNo);
        if(null == cards || !cards.getPassword().equals(password)) {
            return AjaxResult.error("卡号或密码不正确");
        }
//        if(CardStatus.Free.getVal().equals(cards.getStatus())||CardStatus.Open.getVal().equals(cards.getStatus())) {
//            return AjaxResult.error("卡未分配");
//        }else if(CardStatus.Active.getVal().equals(cards.getStatus())) {
//            return AjaxResult.error("卡已使用");
//        }

        if(!CardStatus.Paid.getVal().equals(cards.getStatus())) {
            return AjaxResult.error("无效卡");
        }
        if(null != cards.getAssignSchoolId()) {
            cards.setAssignSchoolName(dzSchoolService.selectDzSchoolById(cards.getAssignSchoolId()).getName());
        }
        return AjaxResult.success(cards);
    }
}
