package com.infoepoch.pms.dispatchassistant.controller.basic;

import com.infoepoch.pms.dispatchassistant.common.component.RedisTool;
import com.infoepoch.pms.dispatchassistant.common.component.Result;
import com.infoepoch.pms.dispatchassistant.common.constant.ErrorCodes;
import com.infoepoch.pms.dispatchassistant.common.exception.NotLoginException;
import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
import com.infoepoch.pms.dispatchassistant.common.utils.JsonUtils;
import com.infoepoch.pms.dispatchassistant.common.utils.UrlTool;
import com.infoepoch.pms.dispatchassistant.domain.basic.menu.Menu;
import com.infoepoch.pms.dispatchassistant.domain.basic.menu.MenuService;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.Organization;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.OrganizationRoot;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.OrganizationService;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.IUserRepository;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.User;
import com.infoepoch.pms.dispatchassistant.domain.oa.user.IUserPmsRepository;
import com.infoepoch.pms.dispatchassistant.domain.oa.user.UserPms;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/menu")
public class MenuController {

    @Autowired
    private Auth auth;

    @Autowired
    private RedisTool redisTool;
    @Autowired
    private MenuService menuService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private IUserPmsRepository userPmsRepository;
    @Autowired
    private IUserRepository userRepository;

    @Value("${spring.application.name}")
    private String applicationContext;

    /**
     * 取移动用户菜单
     *
     * @return
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public Result getMain() throws NotLoginException, ValidationException {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> userMap = new HashMap<>();
        User userReq = auth.getUserReq();
        List<Menu> menus = menuService.queryMainMenu(userReq.getId());
        // 填充菜单栏地址
        fillMenuUrlRecursion(menus);
        userMap.put("id", userReq.getId());
        userMap.put("userName", userReq.getFullname());
        userMap.put("organizationId", userReq.getOrganizationId());
        Organization organization = Optional.ofNullable(OrganizationRoot.getByIdReq(userReq.getOrganizationId()))
                .orElse(new Organization());
        userMap.put("department", organization.getName());
        userMap.put("email", userReq.getEmail());
        userMap.put("phone", userReq.getMobile());
        map.put("user", userMap);
        map.put("menus", menus);
        if (userReq.getOrgConfirmStatus() == null || userReq.getOrgConfirmStatus() == 0) {
            List<UserPms> userPmsList = userPmsRepository.selectByReference3(userReq.getUsername());
            if (CollectionUtils.isEmpty(userPmsList)) {
                // 用户组织确认标识，true-已确认 false-未确认
                map.put("userOrgConfirmFlag", true);
            } else {
                // 用户组织确认标识，true-已确认 false-未确认
                map.put("userOrgConfirmFlag", false);
//                boolean flag = false;
//                for(UserPms userPms : userPmsList) {
//                    if(userPms.getOaOrgCode().equals(organization.getOaOrgCode())) {
//                        flag = true;
//                    }
//                }
//                if(flag) {
//                    // 用户组织确认标识，true-已确认 false-未确认
//                    map.put("userOrgConfirmFlag", true);
//                    userReq.setOrgConfirmStatus(1);
//                    userRepository.update(userReq);
//                    // 刷新redis用户缓存
//                    String sign = ServletTool.getSign();
//                    redisTool.put(RedisKeys.AUTHED_USER + sign, userReq, 2, TimeUnit.HOURS);
//                } else {
//                    // 用户组织确认标识，true-已确认 false-未确认
//                    map.put("userOrgConfirmFlag", false);
//                }
            }
        } else {
            // 用户组织确认标识，true-已确认 false-未确认
            map.put("userOrgConfirmFlag", true);
        }

        return Result.successData(map);
    }

    /**
     * 培训平台菜单
     *
     * @return
     */
    @GetMapping("/supermarket-main")
    public Result supermarketMain() throws NotLoginException {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> userMap = new HashMap<>();
        User userReq = auth.getUserReq();
        List<Menu> menus = menuService.querySupermarketMenu(userReq.getId());
        // 填充菜单栏地址
        fillMenuUrlRecursion(menus);
        userMap.put("id", userReq.getId());
        userMap.put("userName", userReq.getFullname());
        userMap.put("organizationId", userReq.getOrganizationId());
        Organization organization = OrganizationRoot.getOrganizationById(userReq.getOrganizationId());
        userMap.put("department", organization.getName());
        userMap.put("email", userReq.getEmail());
        userMap.put("phone", userReq.getMobile());
        resultMap.put("user", userMap);
        resultMap.put("menus", menus);
        if (userReq.getOrgConfirmStatus() == null || userReq.getOrgConfirmStatus() == 0) {
            List<UserPms> userPmsList = userPmsRepository.selectByReference3(userReq.getUsername());
            if (CollectionUtils.isEmpty(userPmsList)) {
                // 用户组织确认标识，true-已确认 false-未确认
                resultMap.put("userOrgConfirmFlag", true);
            } else {
                // 用户组织确认标识，true-已确认 false-未确认
                resultMap.put("userOrgConfirmFlag", false);
            }
        } else {
            // 用户组织确认标识，true-已确认 false-未确认
            resultMap.put("userOrgConfirmFlag", true);
        }
        return Result.successData(resultMap);
    }

    /**
     * 培训平台菜单
     *
     * @return
     */
    @GetMapping("/portal-main")
    public Result portalMain() throws NotLoginException {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> userMap = new HashMap<>();
        User userReq = auth.getUserReq();
        List<Menu> menus = menuService.queryPortalMenu(userReq.getId());
        // 填充菜单栏地址
        fillMenuUrlRecursion(menus);
        userMap.put("id", userReq.getId());
        userMap.put("userName", userReq.getFullname());
        userMap.put("organizationId", userReq.getOrganizationId());
        Organization organization = OrganizationRoot.getOrganizationById(userReq.getOrganizationId());
        userMap.put("department", organization.getName());
        userMap.put("email", userReq.getEmail());
        userMap.put("phone", userReq.getMobile());
        resultMap.put("user", userMap);
        resultMap.put("menus", menus);
        if (userReq.getOrgConfirmStatus() == null || userReq.getOrgConfirmStatus() == 0) {
            List<UserPms> userPmsList = userPmsRepository.selectByReference3(userReq.getUsername());
            if (CollectionUtils.isEmpty(userPmsList)) {
                // 用户组织确认标识，true-已确认 false-未确认
                resultMap.put("userOrgConfirmFlag", true);
            } else {
                // 用户组织确认标识，true-已确认 false-未确认
                resultMap.put("userOrgConfirmFlag", false);
            }
        } else {
            // 用户组织确认标识，true-已确认 false-未确认
            resultMap.put("userOrgConfirmFlag", true);
        }
        return Result.successData(resultMap);
    }

    /**
     * 填充菜单栏地址
     *
     * @param menuList
     */
    private void fillMenuUrlRecursion(List<Menu> menuList) {
        for (Menu menu : menuList) {
            menu.modifyUrl(UrlTool.splicingUrlWithCheck(applicationContext, menu.getUrl()));
            if (CollectionUtils.isNotEmpty(menu.getChildren())) {
                fillMenuUrlRecursion(menu.getChildren());
            }
        }
    }

    /**
     * 普通用户菜单管理使用
     *
     * @return
     */
    @RequestMapping(value = "/main-list", method = RequestMethod.POST)
    public Result getMainMenuList() {
        List<Menu> menus;
        try {
            menus = menuService.query(true);
        } catch (Exception e) {
            return Result.error(ErrorCodes.DEFAULT, e.getMessage());
        }
        return Result.successData(menus);
    }

    /**
     * 修改菜单
     *
     * @param jsonStr
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    public Result modifyMenu(@RequestBody String jsonStr) {
        Menu menu = null;
        try {
            menu = JsonUtils.jsonToObject(jsonStr, Menu.class);
        } catch (Exception e) {
            return Result.error(ErrorCodes.DEFAULT, e.getMessage());
        }
        menuService.modifyMenuById(menu);
        return Result.success();
    }

    /**
     * 创建菜单
     *
     * @param jsonStr
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Result createMenu(@RequestBody String jsonStr) {
        Menu menu;
        try {
            menu = JsonUtils.jsonToObject(jsonStr, Menu.class);
        } catch (Exception e) {
            return Result.error(ErrorCodes.DEFAULT, e.getMessage());
        }
        menuService.createMenu(menu);
        return Result.success();
    }

    /**
     * 删除菜单
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    public Result removeMenu(@RequestParam("id") String id) {
        if (StringUtils.isBlank(id)) {
            return Result.error(ErrorCodes.DEFAULT, "参数错误！");
        }
        menuService.removeMenuById(id);
        return Result.success();
    }


    /**
     * 根据id查询菜单
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getMenuById", method = RequestMethod.GET)
    public Result getMenuById(@RequestParam("id") String id) {
        if (StringUtils.isBlank(id)) {
            return Result.error(ErrorCodes.DEFAULT, "参数错误！");
        }
        Menu menu = menuService.getMenuById(id);
        return Result.successData(menu);
    }

}
