package com.gic.haoban.manage.web.controller;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.manage.api.dto.qdto.role.HaobanMenuQDTO;
import com.gic.haoban.manage.api.dto.qdto.role.HaobanRoleMenuQDTO;
import com.gic.haoban.manage.api.dto.qdto.role.HaobanRoleQDTO;
import com.gic.haoban.manage.api.dto.role.HaobanMenuDTO;
import com.gic.haoban.manage.api.dto.role.HaobanRoleDTO;
import com.gic.haoban.manage.api.enums.role.RoleClerkTypeEnum;
import com.gic.haoban.manage.api.service.role.HaobanMenuApiService;
import com.gic.haoban.manage.api.service.role.HaobanRoleApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.log.LogRecordUserServiceImpl;
import com.gic.log.record.anno.GicLogRecord;
import com.gic.log.record.util.GicLogRecordCategoryEnum;
import com.gic.log.record.util.GicLogRecordEvaluationContext;
import com.gic.log.record.util.GicLogRecordOptTypeEnum;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author mozhu
 * @date 2022/9/7 3:03 下午
 */
@RestController
@RequestMapping("/role")
public class HaobanRoleController extends WebBaseController {

    private static final Logger logger = LoggerFactory.getLogger(HaobanRoleController.class);

    @Autowired
    private HaobanRoleApiService haobanRoleApiService;
    @Autowired
    private HaobanMenuApiService haobanMenuApiService;

    /**
     * 修改
     *
     * @param haobanRoleQDTO
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @GicLogRecord(value = "${#logContent}",
            category = GicLogRecordCategoryEnum.HAOBAN_ROLE,
            optType = GicLogRecordOptTypeEnum.EDIT_HAOBAN_ROLE,
            userFunc = LogRecordUserServiceImpl.class,
            optPage = "好办小程序权限-编辑")
    public RestResponse edit(@RequestBody HaobanRoleQDTO haobanRoleQDTO) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        StringBuffer logContent = getEditLog(haobanRoleQDTO, login);
        haobanRoleQDTO.setSystemFlag(1);
        ServiceResponse serviceResponse = haobanRoleApiService.edit(haobanRoleQDTO, login);
        if (!serviceResponse.isSuccess()) {
            GicLogRecordEvaluationContext.noWriteLog();
        }
        if (logContent != null) {
            GicLogRecordEvaluationContext.putAttribute("logContent", logContent.toString());
            GicLogRecordEvaluationContext.putOptTargetId(AuthWebRequestUtil.getLoginUser().getClerkId());
        }
        return RestResponse.successResult();
    }

    private StringBuffer getEditLog(HaobanRoleQDTO haobanRoleQDTO, WebLoginDTO login) {
        HaobanRoleMenuQDTO clerkMenus = haobanRoleQDTO.getClerkMenus();
        HaobanRoleMenuQDTO manegeClerkMenus = haobanRoleQDTO.getManegeClerkMenus();
        HaobanRoleMenuQDTO managerMenus = haobanRoleQDTO.getManagerMenus();
        StringBuffer stringBuffer = new StringBuffer();
        if (clerkMenus != null) {
            Integer clerkType = clerkMenus.getClerkType();
            List<String> addMenuCodes = clerkMenus.getAddMenuCodes();
            List<String> delMenuCodes = clerkMenus.getDelMenuCodes();
            setEditLogByType(stringBuffer, clerkType, addMenuCodes, delMenuCodes);
        }

        if (manegeClerkMenus != null) {
            Integer clerkType = manegeClerkMenus.getClerkType();
            List<String> addMenuCodes = manegeClerkMenus.getAddMenuCodes();
            List<String> delMenuCodes = manegeClerkMenus.getDelMenuCodes();
            setEditLogByType(stringBuffer, clerkType, addMenuCodes, delMenuCodes);
        }
        if (managerMenus != null) {
            Integer clerkType = managerMenus.getClerkType();
            List<String> addMenuCodes = managerMenus.getAddMenuCodes();
            List<String> delMenuCodes = managerMenus.getDelMenuCodes();
            setEditLogByType(stringBuffer, clerkType, addMenuCodes, delMenuCodes);
        }
        return stringBuffer;
    }

    private void setEditLogByType(StringBuffer stringBuffer, Integer clerkType, List<String> addMenuCodes, List<String> delMenuCodes) {
        if (CollectionUtils.isNotEmpty(addMenuCodes)) {
            logger.info("新增菜单code：{}", JSON.toJSONString(addMenuCodes));
            for (String menuCode : addMenuCodes) {
                ServiceResponse<String> serviceMenuNameByCode = haobanMenuApiService.getMenuNameByCode(menuCode);
                String menuName = serviceMenuNameByCode.getResult();
                String log = RoleClerkTypeEnum.getNameByCode(clerkType) + "/" + menuName + "/" + "勾选" + "\r\n";
                stringBuffer.append(log);
            }
        }

        if (CollectionUtils.isNotEmpty(delMenuCodes)) {
            logger.info("删除菜单code:{}",JSON.toJSONString(delMenuCodes));
            //删除勾选的
            for (String menuCode : delMenuCodes) {
                ServiceResponse<String> serviceMenuNameByCode = haobanMenuApiService.getMenuNameByCode(menuCode);
                String menuName = serviceMenuNameByCode.getResult();
                String log = RoleClerkTypeEnum.getNameByCode(clerkType) + "/" + menuName + "/" + "取消勾选" + "\r\n";
                stringBuffer.append(log);
            }
        }
    }

    /**
     * 获取菜单
     *
     * @param clerkType
     * @return
     */
    @RequestMapping(value = "/getHaobanMenuTreeList", method = RequestMethod.GET)
    public RestResponse<List<HaobanMenuDTO>> getHaobanMenuTreeList(Integer clerkType) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        ServiceResponse<List<HaobanMenuDTO>> serviceResponse = haobanMenuApiService.getHaobanMenuTreeList(login.getWxEnterpriseId(),login.getEnterpriseId(), clerkType);
        return RestResponse.successResult(serviceResponse.getResult());
    }

    /**
     * 根据角色查询菜单
     *
     * @return
     */
    @RequestMapping(value = "/queryMenuByClerkType", method = RequestMethod.GET)
    public RestResponse<HaobanRoleDTO> queryMenuByClerkType(Integer clerkType) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        ServiceResponse<HaobanRoleDTO> serviceResponse = haobanRoleApiService.getMenuByWxEnterpriseIdAndClerkType(login.getWxEnterpriseId(), clerkType, 1);
        return RestResponse.successResult(serviceResponse.getResult());
    }

    /**
     * 新增菜单
     *
     * @param haobanMenuQDTOList
     * @return
     */
    @RequestMapping(value = "/addMenu", method = RequestMethod.POST)
    @IgnoreLogin
    @com.gic.web.common.ano.IgnoreLogin
    public RestResponse addMenuList(@RequestBody List<HaobanMenuQDTO> haobanMenuQDTOList) {
        if (CollectionUtils.isEmpty(haobanMenuQDTOList)) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_2.getCode()),HaoBanErrCode.ERR_2.getMsg());
        }
        haobanMenuApiService.addList(haobanMenuQDTOList);
        return RestResponse.successResult();
    }

    /**
     * 新增单个菜单
     * @param haobanMenuQDTOList
     * @return
     */
    @RequestMapping(value = "/add-menuCode", method = RequestMethod.POST)
    @IgnoreLogin
    @com.gic.web.common.ano.IgnoreLogin
    public RestResponse addMenu(@RequestBody List<HaobanMenuQDTO> haobanMenuQDTOList) {
        if (CollectionUtils.isEmpty(haobanMenuQDTOList)) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_2.getCode()),HaoBanErrCode.ERR_2.getMsg());
        }
        haobanMenuApiService.add(haobanMenuQDTOList);
        return RestResponse.successResult();
    }

    /**
     * 获取所有菜单
     * @return
     */
    @RequestMapping(value = "/getAllMenu", method = RequestMethod.GET)
    @IgnoreLogin
    @com.gic.web.common.ano.IgnoreLogin
    public RestResponse<List<HaobanMenuDTO>> getAllMenu() {
        ServiceResponse<List<HaobanMenuDTO>> allMenuList = haobanMenuApiService.getAllMenuList();
        return RestResponse.successResult(allMenuList.getResult());
    }

}
