package cn.pluss.platform.impl;

import cn.pluss.platform.AppMenuService;
import cn.pluss.platform.dict.DictService;
import cn.pluss.platform.entity.AppMenu;
import cn.pluss.platform.entity.Dict;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.AppMenuMapper;
import cn.pluss.platform.mapper.AppMenuUserTypeMapper;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.HttpUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

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

/**
 * <p>
 * app页面菜单 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2020-09-27
 */
@Service
@RequiredArgsConstructor
public class AppMenuServiceImpl extends ServiceImpl<AppMenuMapper, AppMenu> implements AppMenuService {

    private final DictService dictService;

    private final AppMenuUserTypeMapper appMenuUserTypeMapper;

    private final UserAppService userAppService;

    @Override
    public AppMenu getOne(Wrapper<AppMenu> queryWrapper) {
        final AppMenu one = super.getOne(queryWrapper);
        AppMenu.wrapper(one);
        return one;
    }

    @Override
    public List<Map<String, Object>> getHomeMenu(HttpServletRequest request) {
        // 1、安卓; 2、iOS
        int clientType = HttpUtils.isIOS(request)? 2: 1;

        final String demoFlag = request.getHeader("demo");

        List<Map<String, Object>> result = new ArrayList<>();
        UserApp userApp = userAppService.queryUserAppByToken();
        String userType = userApp.getUserType();
        Dict dict = new Dict().setName("首页");
        List<Dict> list = dictService.list(new QueryWrapper<>(dict));
        dict = list.get(0);
        List<AppMenu> appMenuList;
        if ("1".equals(demoFlag)) {
            appMenuList = baseMapper.getByNavCodeAll(dict.getId(),userType);
        } else {
            appMenuList = baseMapper.getByNavCode(dict.getId(),userType, clientType);
        }

        Map<String, Object> map = null;
        for (AppMenu appMenu : appMenuList) {
            AppMenu.wrapper(appMenu);
            menuPathConvert(appMenu, request);
            if (map == null || !map.get("type").equals(appMenu.getMenuGroupDesc())) {
                map = new HashMap<>();
                map.put("type", appMenu.getMenuGroupDesc());
                map.put("data", new ArrayList<AppMenu>());
                result.add(map);
            }
            ArrayList<AppMenu> data = (ArrayList<AppMenu>) map.get("data");
            data.add(appMenu);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getSpreadPageMenu(HttpServletRequest request) {
        // 1、安卓; 2、iOS
        int clientType = HttpUtils.isIOS(request)? 2: 1;

        List<Map<String, Object>> result = new ArrayList<>();
        UserApp userApp = userAppService.queryUserAppByToken();
        Dict dict = new Dict().setName("推广");
        List<Dict> list = dictService.list(new QueryWrapper<>(dict));
        dict = list.get(0);
        String userType = userApp.getUserType();
        List<AppMenu> appMenuList = baseMapper.getByNavCode(dict.getId(),userType, clientType);

        Map<String, Object> map = null;
        for (AppMenu appMenu : appMenuList) {
            AppMenu.wrapper(appMenu);
            menuPathConvert(appMenu, request);
            if ("agent".equals(userApp.getUserType()) && "升级".equals(appMenu.getName())) {
                appMenu.setName("费率");
            }

            // TODO 只有服务商才会有的菜单，后期写活
            if ("promoter".equals(userApp.getUserType()) && "业务员".equals(appMenu.getName())) {
                continue;
            }

            // TODO 只有服务商才会有的菜单，后期写活
            if ("promoter".equals(userApp.getUserType()) && "代理商".equals(appMenu.getName())) {
                continue;
            }

            if (map == null || !map.get("type").equals(appMenu.getMenuGroupDesc())) {
                map = new HashMap<>();
                map.put("type", appMenu.getMenuGroupDesc());
                map.put("data", new ArrayList<AppMenu>());
                result.add(map);
            }

            if (StringUtils.equals(appMenu.getName(), "开代理") && !"ZY_BST".equals(userApp.getRoleCode())) {
                continue;
            }

            ArrayList<AppMenu> data = (ArrayList<AppMenu>) map.get("data");
            data.add(appMenu);
        }

        return result;
    }

    @Override
    public boolean saveOrUpdate(AppMenu entity) {
        entity.setUpdateTime(new Date());

        AppMenu appMenu = new AppMenu().setCode(entity.getCode());
        appMenu = baseMapper.selectOne(new QueryWrapper<>(appMenu));

        if (appMenu != null && !Objects.equals(entity.getId(), appMenu.getId())) {
            throw new MsgException("菜单code不能重复");
        }

        AppMenu.setByMenuType(entity);

        return super.saveOrUpdate(entity);
    }

    private void menuPathConvert(AppMenu menu, HttpServletRequest request) {
        if (!HttpUtils.isIOS(request)) {
            return;
        }

        if (StringUtils.isNotBlank(menu.getPath())) {
            menu.setPath(menu.getPath().replace("?u=${u}&p=${p}", ""));
        }
    }
}
