package com.hzs.system.config.controller.manage;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.system.config.*;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.system.config.param.MenuSaveParam;
import com.hzs.system.config.service.*;
import com.hzs.system.config.param.MenuQueryParam;
import com.hzs.system.config.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description: 菜单配置表 控制器
 * Author: jiang chao
 * Time: 2022/10/8 14:58
 * Classname: BdMenuController
 * PackageName: com.hzs.system.config.controller.manage
 */
@Slf4j
@RestController
@RequestMapping("/manage/bd-menu")
public class BdMenuController extends BaseController {

    @Autowired
    private IBdMenuService iBdMenuService;
    @Autowired
    private IBdMenuAuthorityService iBdMenuAuthorityService;
    @Autowired
    private IBdMenuDetailService iBdMenuDetailService;
    @Autowired
    private IBdGradeService iBdGradeService;
    @Autowired
    private IBdAwardsService iBdAwardsService;

    /**
     * 查询菜单权限列表
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.AUTHORITY_CONFIG, business = EOperationBusiness.MENU_AUTHORITY_FRONT, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(MenuQueryParam param) {
        DateUtils.handTimeStartAndEnd(param.getCreationTime());

        Integer pkCountry = SecurityUtils.getPkCountry();

        param.setPkCountry(pkCountry);
        startPage();
        List<MenuQueryVO> list = iBdMenuService.queryList(param);

        if (CollectionUtil.isNotEmpty(list)) {
            // 等级列表
            List<BdGrade> gradeTmpList = iBdGradeService.queryGradeConfigByCondition(pkCountry);
            Map<Integer, BdGrade> gradeMap = new HashMap<>(gradeTmpList.size());
            for (BdGrade bdGrade : gradeTmpList) {
                gradeMap.put(bdGrade.getPkId(), bdGrade);
            }
            // 奖衔列表
            List<BdAwards> awardsTmpList = iBdAwardsService.queryAwards(pkCountry);
            Map<Integer, BdAwards> awardsMap = new HashMap<>(awardsTmpList.size());
            for (BdAwards bdAwards : awardsTmpList) {
                awardsMap.put(bdAwards.getPkId(), bdAwards);
            }

            for (MenuQueryVO menuQueryVO : list) {
                if (StringUtils.isNotEmpty(menuQueryVO.getGradeValues())) {
                    // 存在会员等级，处理等级
                    List<MenuQueryGradeVO> gradeList = new ArrayList<>();
                    for (String grade : menuQueryVO.getGradeValues().split(",")) {
                        BdGrade bdGrade = gradeMap.get(Integer.parseInt(grade));
                        if (null != bdGrade) {
                            gradeList.add(MenuQueryGradeVO.builder()
                                    .grade(bdGrade.getPkTransaction())
                                    .build());
                        }
                    }
                    menuQueryVO.setGradeList(gradeList);
                }

                if (StringUtils.isNotEmpty(menuQueryVO.getAwardValues())) {
                    // 存在真实奖衔，处理奖衔
                    List<MenuQueryAwardsVO> awardsList = new ArrayList<>();
                    for (String award : menuQueryVO.getAwardValues().split(",")) {
                        BdAwards bdAwards = awardsMap.get(Integer.parseInt(award));
                        if (null != bdAwards) {
                            awardsList.add(MenuQueryAwardsVO.builder()
                                    .award(bdAwards.getPkTransaction())
                                    .build());
                        }
                    }
                    menuQueryVO.setAwardList(awardsList);
                }

                if (StringUtils.isNotEmpty(menuQueryVO.getAuthorityValues())) {
                    // 存在权限中心，处理权限
                    List<MenuQueryAuthorityVO> authorityList = new ArrayList<>();
                    for (String authority : menuQueryVO.getAuthorityValues().split(",")) {
                        ERegistrationAuthority registrationAuthority = ERegistrationAuthority.getEnumByValue(Integer.parseInt(authority));
                        if (null != registrationAuthority) {
                            authorityList.add(MenuQueryAuthorityVO.builder()
                                    .authority(registrationAuthority.getValue())
                                    .build());
                        }
                    }
                    menuQueryVO.setAuthorityList(authorityList);
                }

                if (StringUtils.isNotEmpty(menuQueryVO.getMenuValues())) {
                    // 存在菜单明细，处理菜单
                    List<MenuQueryMenuVO> menuList = new ArrayList<>();
                    for (String menu : menuQueryVO.getMenuValues().split(",")) {
                        menuList.add(MenuQueryMenuVO.builder()
                                .menu(Integer.parseInt(menu))
                                .build());
                    }
                    menuQueryVO.setMenuList(menuList);
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 保存菜单权限配置
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.AUTHORITY_CONFIG, business = EOperationBusiness.MENU_AUTHORITY_FRONT, method = EOperationMethod.INSERT)
    @PutMapping
    public AjaxResult save(@RequestBody MenuSaveParam param) {
        if (CollectionUtils.isEmpty(param.getMenuValueList())) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        return toAjax(iBdMenuService.saveMenu(param, SecurityUtils.getUserId(), SecurityUtils.getPkCountry()));
    }

    /**
     * 修改菜单权限配置
     *
     * @param param
     * @return
     */
    @Log(module = EOperationModule.AUTHORITY_CONFIG, business = EOperationBusiness.MENU_AUTHORITY_FRONT, method = EOperationMethod.UPDATE)
    @PostMapping
    public AjaxResult edit(@RequestBody MenuSaveParam param) {
        if (null == param.getMenuId() || CollectionUtils.isEmpty(param.getMenuValueList())) {
            // 缺少参数
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }

        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();

        BdMenu bdMenu = iBdMenuService.getById(param.getMenuId());
        if (!pkCountry.equals(bdMenu.getPkCountry())) {
            return AjaxResult.error("当前国家与菜单权限不匹配");
        }

        return toAjax(iBdMenuService.updateMenu(param, SecurityUtils.getUserId(), pkCountry));
    }

    /**
     * 查看菜单权限详情
     *
     * @param pkId
     * @return
     */
    @GetMapping("/{pkId}")
    public AjaxResult detail(@PathVariable("pkId") Integer pkId) {
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();

        BdMenu bdMenu = iBdMenuService.getById(pkId);
        if (null == bdMenu) {
            return AjaxResult.error("菜单权限不存在");
        }
        if (!pkCountry.equals(bdMenu.getPkCountry())) {
            return AjaxResult.error("当前国家与菜单权限不匹配");
        }

        // 返回VO
        MenuViewVO menuViewVO = new MenuViewVO();
        menuViewVO.setPkId(bdMenu.getPkId());

        QueryWrapper<BdMenuAuthority> menuAuthorityWrapper = new QueryWrapper<>();
        menuAuthorityWrapper.eq("PK_MENU", pkId);
        menuAuthorityWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        menuAuthorityWrapper.orderByAsc("AUTHORITY_TYPE", "AUTHORITY_VALUE");
        List<BdMenuAuthority> menuAuthorityList = iBdMenuAuthorityService.list(menuAuthorityWrapper);

        // 等级处理
        menuViewVO.setGradeIdList(menuAuthorityList.stream().filter((obj) -> EPermissionType.GRADE.getValue() == obj.getAuthorityType()).map(BdMenuAuthority::getAuthorityValue).collect(Collectors.toList()));
        // 奖衔处理
        menuViewVO.setAwardsIdList(menuAuthorityList.stream().filter((obj) -> EPermissionType.AWARDS.getValue() == obj.getAuthorityType()).map(BdMenuAuthority::getAuthorityValue).collect(Collectors.toList()));
        // 权限处理
        menuViewVO.setAuthorityIdList(menuAuthorityList.stream().filter((obj) -> EPermissionType.AUTHORITY.getValue() == obj.getAuthorityType()).map(BdMenuAuthority::getAuthorityValue).collect(Collectors.toList()));

        QueryWrapper<BdMenuDetail> menuDetailWrapper = new QueryWrapper<>();
        menuDetailWrapper.eq("PK_MENU", pkId);
        List<BdMenuDetail> menuDetailList = iBdMenuDetailService.list(menuDetailWrapper);
        // 菜单配置明细处理
        menuViewVO.setMenuValueList(menuDetailList.stream().map(BdMenuDetail::getDetailValue).collect(Collectors.toList()));

        return AjaxResult.success(menuViewVO);
    }

    /**
     * 删除菜单权限
     *
     * @param pkId
     * @return
     */
    @Log(module = EOperationModule.AUTHORITY_CONFIG, business = EOperationBusiness.MENU_AUTHORITY_FRONT, method = EOperationMethod.DELETE)
    @DeleteMapping("/{pkId}")
    public AjaxResult delete(@PathVariable("pkId") Integer pkId) {
        return toAjax(iBdMenuService.removeById(pkId));
    }


}
