package com.template.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.template.api.AlumniUserControllerAPI;
import com.template.common.utils.AesUtils;
import com.template.common.utils.WeiXiaoUtil;
import com.template.common.utils.paramUtils;
import com.template.model.enumModel.*;
import com.template.model.pojo.AlumniOrg;
import com.template.model.pojo.AlumniUser;
import com.template.model.request.insertAccountRequest;
import com.template.model.request.updateAccountRequest;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.*;
import com.template.services.AlumniOrgService;
import com.template.services.AlumniUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2024-11-20
 */
@RestController
public class AlumniUserController implements AlumniUserControllerAPI {

    @Autowired
    private WeiXiaoUtil weiXiaoUtil;
    @Autowired
    private AlumniUserService alumniUserService;
    @Autowired
    private AlumniOrgService alumniOrgService;

    @Override
    public CommonResult queryUsersPage(Integer userId, int currentPage, int pageCount, String name, String orgName, Integer collegeId, Integer periodId, Integer majorId, Integer classId) {
        PageUtils<AlumniUser> result = alumniUserService.queryPageList(currentPage, pageCount, name, orgName, collegeId, periodId, majorId, classId);

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryAccountPage(int currentPage, int pageCount, String account, String startTime, String endTime) {
        PageUtils<AlumniUser> pageDatas = alumniUserService.queryAccountPage(currentPage, pageCount, account, startTime, endTime);

        IPage<AccountVo> accountData = new Page<>();
        PageUtils<AccountVo> finallResult = new PageUtils<AccountVo>(accountData);
        List<AccountVo> datas = new ArrayList<>();
        for (AlumniUser ac : pageDatas.getList()) {
            AccountVo data = new AccountVo();
            data.setId(ac.getId());
            data.setName(ac.getName());
            data.setCardNumber(ac.getCardNumber());
            data.setAccount(ac.getAccount());
            data.setRoleId(ac.getRoleId());
            data.setRoleName(eRoleType.stringOf(ac.getRoleId()));
            data.setCreateAccountTime(ac.getCreateAccountTime());
            datas.add(data);
        }
        finallResult.setList(datas);
        finallResult.setTotalPage(pageDatas.getTotalPage());
        finallResult.setPageSize(pageDatas.getPageSize());
        finallResult.setCurrentPage(pageDatas.getCurrentPage());
        finallResult.setTotalCount(pageDatas.getTotalCount());

        return CommonResult.ok(finallResult);
    }

    @Override
    public CommonResult queryUsers(String keyword) {
        List<AlumniUser> result = alumniUserService.queryUsers(keyword);
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryPageUser(int currentPage, int pageCount, Integer departmentId) {
        //获取该部门下的所有子级部门ID
        List<Integer> childDepartmentIds = new ArrayList<>();
        List<AlumniOrg> departments = alumniOrgService.list(null);
        childDepartmentIds.add(departmentId);
        QueryDepartmentTreeRecords(departmentId, departments, childDepartmentIds);

        if (departmentId == null) {
            childDepartmentIds = null;
        }

        PageUtils<UserVo> result = null;
        if (childDepartmentIds != null && childDepartmentIds.size() > 0) {
            result = alumniUserService.queryUserPages(currentPage, pageCount, childDepartmentIds);
        } else {
            IPage<UserVo> userData = new Page<>();
            result = new PageUtils<UserVo>(userData);
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryMobileInfo(String cardNumber) {

        CommonResult result = weiXiaoUtil.queryUserInfos(cardNumber);
        return result;
    }

    @Override
    public CommonResult insertAccountData(insertAccountRequest iar, BindingResult bindingResult) {
        if (iar == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        AlumniUser existAccount = alumniUserService.queryDataByAccount(iar.getAccount());
        if (existAccount != null) {
            return CommonResult.fail("该账号已存在！");
        }

        String encPassword = AesUtils.encrypt(iar.getPassword());

        int result = 0;
        AlumniUser mobileUser = alumniUserService.queryDataByCardNumber(iar.getCardNumber());
        if (mobileUser == null) {
            mobileUser = new AlumniUser();
            mobileUser.setName(iar.getName());
            mobileUser.setCardNumber(iar.getCardNumber());
            mobileUser.setAccount(iar.getAccount());
            mobileUser.setPassword(encPassword);
            mobileUser.setRoleId(iar.getRoleId());
            mobileUser.setTypeId(eAccountType.Account.getValue());
            mobileUser.setCreateAccountTime(new Date());
            result = alumniUserService.insertAlumniUser(mobileUser);
        } else {
            mobileUser.setAccount(iar.getAccount());
            mobileUser.setPassword(encPassword);
            mobileUser.setRoleId(iar.getRoleId());
            mobileUser.setCreateAccountTime(new Date());
            result = alumniUserService.updateAlumniUser(mobileUser);
        }

        if (result <= 0) {
            return CommonResult.fail("新增失败");
        }


        return CommonResult.ok("新增成功");
    }

    @Override
    public CommonResult updateAccountData(updateAccountRequest uar, BindingResult bindingResult) {
        if (uar == null) {
            return CommonResult.fail("请传递参数");
        }
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        AlumniUser existAccount = alumniUserService.queryDataByAccount(uar.getAccount());
        if (existAccount.getId().intValue() != uar.getId().intValue()) {
            return CommonResult.fail("该账号已存在，更新失败");
        }

        AlumniUser au = alumniUserService.queryDataById(uar.getId());
        if (au == null) {
            return CommonResult.fail("数据已失效，更新失败");
        }
        au.setName(uar.getName());
        au.setCardNumber(uar.getCardNumber());
        au.setAccount(uar.getAccount());
        au.setRoleId(uar.getRoleId());

        int updateResult = alumniUserService.updateAlumniUser(au);
        if (updateResult <= 0) {
            return CommonResult.fail("更新失败");
        }

        return CommonResult.ok("更新成功");
    }

    @Override
    public CommonResult queryRoleTypes() {
        List<ListDataVO> result = new ArrayList<>();
        for (int i = 1; i <= eRoleType.values().length; i++) {
            ListDataVO data = new ListDataVO();
            data.setId(i);
            data.setName(ePassType.stringOf(i));
            result.add(data);
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult deleteUserById(int id) {
        AlumniUser user = alumniUserService.queryDataById(id);
        if (user == null) {
            return CommonResult.fail("数据已失效，删除失败");
        }
        user.setAccount(null);
        user.setPassword(null);
        user.setRoleId(null);
        int result = alumniUserService.updateAlumniUser(user);
        if (result <= 0) {
            return CommonResult.fail("删除失败");
        }

        return CommonResult.ok("删除成功");
    }

    @Override
    public CommonResult queryMobileUserPages(Integer userId, int currentPage, int pageCount, int typeId, String name) {

        IPage<AlumniMobileUserPageVo> accountData = new Page<>();
        PageUtils<AlumniMobileUserPageVo> result = new PageUtils<AlumniMobileUserPageVo>(accountData);

        if (typeId == eabookType.Alumnus.getValue()) {//校友通讯录
            //获取所有用户数据
            PageUtils<AlumniUser> pageDatas = alumniUserService.queryUserPage(currentPage, pageCount, name);
            List<AlumniMobileUserPageVo> datas = new ArrayList<>();
            for (AlumniUser pg : pageDatas.getList()) {
                AlumniMobileUserPageVo npv = new AlumniMobileUserPageVo();
                npv.setId(pg.getId());
                npv.setName(pg.getName());
                npv.setCollegeName(pg.getCollegeName()+"》"+pg.getPeriodName()+"》"+pg.getMajorName()+"》"+pg.getClassName());
                npv.setName(pg.getName());
                npv.setOrgName(pg.getOrgName());
                npv.setPhone(pg.getPhone());
                datas.add(npv);
            }
            result.setList(datas);
            result.setTotalPage(pageDatas.getTotalPage());
            result.setPageSize(pageDatas.getPageSize());
            result.setCurrentPage(pageDatas.getCurrentPage());
            result.setTotalCount(pageDatas.getTotalCount());

        } else {//班级通讯录
            //获取当前用户所在班级的用户信息
            AlumniUser au = alumniUserService.queryDataById(userId);
            if (au == null) {
                return CommonResult.fail("当前操作人已失效，无法获取班级通讯录");
            }

            PageUtils<AlumniUser> pageDatas = alumniUserService.queryUserPageByClassId(currentPage, pageCount, au.getClassId(),name);
            List<AlumniMobileUserPageVo> datas = new ArrayList<>();
            for (AlumniUser pg : pageDatas.getList()) {
                AlumniMobileUserPageVo npv = new AlumniMobileUserPageVo();
                npv.setId(pg.getId());
                npv.setName(pg.getName());
                npv.setCollegeName(pg.getCollegeName()+"》"+pg.getPeriodName()+"》"+pg.getMajorName()+"》"+pg.getClassName());
                npv.setName(pg.getName());
                npv.setOrgName(pg.getOrgName());
                npv.setPhone(pg.getPhone());
                datas.add(npv);
            }
            result.setList(datas);
            result.setTotalPage(pageDatas.getTotalPage());
            result.setPageSize(pageDatas.getPageSize());
            result.setCurrentPage(pageDatas.getCurrentPage());
            result.setTotalCount(pageDatas.getTotalCount());
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult queryTypes() {
        List<ListDataVO> result = new ArrayList<>();
        for (int i = 1; i <= eabookType.values().length; i++) {
            ListDataVO data = new ListDataVO();
            data.setId(i);
            data.setName(ePassType.stringOf(i));
            result.add(data);
        }

        return CommonResult.ok(result);
    }

    /**
     * 根据父级ID获取树形数据
     *
     * @param parentID 父级ID
     * @param lists    数据集合
     * @return
     */
    private List<DepartmentTreeVo> QueryDepartmentTreeRecords(Integer parentID, List<AlumniOrg> lists, List<Integer> departmentIds) {
        List<DepartmentTreeVo> newTrees = new ArrayList<>();

        List<AlumniOrg> datas = lists.stream().filter(e -> e.getParentId().equals(parentID)).collect(Collectors.toList());

        for (AlumniOrg data : datas) {
            departmentIds.add(data.getId());
            QueryDepartmentTreeRecords(data.getId(), lists, departmentIds);
        }

        return newTrees;
    }
    //endregion
}

