package com.yunfeiyun.agmp.pts.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.yunfeiyun.agmp.pts.constant.PtsConstants;
import com.yunfeiyun.agmp.pts.service.IPtsLinkService;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.ResConstants;
import com.yunfeiyun.agmp.common.constant.UserConstants;
import com.yunfeiyun.agmp.common.core.domain.entity.SysMenu;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseMenu;
import com.yunfeiyun.agmp.common.core.domain.model.LoginUser;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.framework.manager.ResManager;
import com.yunfeiyun.agmp.common.framework.web.service.ISysMenuService;
import com.yunfeiyun.agmp.common.framework.web.service.PolicyService;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
import com.yunfeiyun.agmp.common.web.system.domain.SysRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import com.yunfeiyun.agmp.pts.mapper.PtsLinkMapper;
import com.yunfeiyun.agmp.pts.domain.PtsLink;
import org.springframework.transaction.annotation.Transactional;

/**
 * 链接Service业务层处理
 * 
 * @author 杨晓辉
 * @date 2023-05-23
 */
@Service
public class PtsLinkServiceImpl implements IPtsLinkService
{
    @Autowired
    private PtsLinkMapper ptsLinkMapper;

    @Autowired
    private ISysMenuService sysMenuService;

    @Autowired
    ResManager resManager;

    /**
     * 查询链接
     * 
     * @param linkId 链接主键
     * @return 链接
     */
    @Override
    public PtsLink selectPtsLinkByLinkId(String linkId)
    {
        List<SysRes> resList = resManager.queryRes(linkId ,  ResConstants.BizType.SYSLINK.getKey());
        SysRes linkIcon = resList !=null && resList.size() > 0 ? resList.get(0): new SysRes();
        PtsLink ptsLink = ptsLinkMapper.selectPtsLinkByLinkId(linkId);
        ptsLink.setResId( linkIcon.getResId() );
        if(SpringUtils.getBean(PolicyService.class).isOssCloudPolicy()){
            ptsLink.setLinkIcon( linkIcon.getResOssUrl() );
        }else   ptsLink.setLinkIcon(linkIcon.getResUrl());
        return ptsLink;
    }

    /**
     * 查询链接列表
     * 
     * @param ptsLink 链接
     * @return 链接
     */
    @Override
    public List<PtsLink> selectPtsLinkList(PtsLink ptsLink,int type)
    {
        if(type == 0){
            List<PtsLink>  links = ptsLinkMapper.selectPtsLinkList(ptsLink);
            List<PtsLink> linksNew = links.stream().map(m -> {
                List<SysRes> resList = resManager.queryRes(m.getLinkId() ,  ResConstants.BizType.SYSLINK.getKey());
                SysRes linkIcon = resList !=null && resList.size() > 0 ? resList.get(0) : new SysRes();
                if(SpringUtils.getBean(PolicyService.class).isOssCloudPolicy()){
                    m.setLinkIcon( linkIcon.getResOssUrl() );
                }
                return m;
            }).collect(Collectors.toList());
            return linksNew;
        }

        else if(type == 1){
            List<PtsLink>  links = ptsLinkMapper.selectPtsLinkList(ptsLink);
            List<PtsLink> linksNew = links.stream().filter(v ->v.getLinkVisiblestatus().equals("0")).map(m -> {
                List<SysRes> resList = resManager.queryRes(m.getLinkId() ,  ResConstants.BizType.SYSLINK.getKey());
                SysRes linkIcon = resList !=null && resList.size() > 0 ? resList.get(0) : new SysRes();
                if(SpringUtils.getBean(PolicyService.class).isOssCloudPolicy()){
                    m.setLinkIcon( linkIcon.getResOssUrl() );
                }
                return m;
            }).collect(Collectors.toList());
            return linksNew;
        }
        return null;
    }

    /**
     * 新增链接
     * 
     * @param ptsLink 链接
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPtsLink(PtsLink ptsLink, LoginUser user)
    {
        try {
            ptsLink.setLinkId(ptsLink.getId());
            ptsLink.setLinkCreator(user.getUserId());
            ptsLink.setLinkCreateddate(DateUtils.dateTimeNow());
            ptsLink.setLinkModifier(user.getUserId());
            ptsLink.setLinkModifieddate(DateUtils.dateTimeNow());
            ptsLink.setLinkRemark(ptsLink.getLinkName());
            ptsLink.setLinkQuery(UserConstants.TYPE_EMPTY);
            ptsLink.setLinkOpentype(UserConstants.NO_FRAME);
            int nResult = ptsLinkMapper.insertPtsLink(ptsLink);
            SysRes.add( ptsLink.getResList() ,ResConstants.formType.ADD,ptsLink.getLinkId() );
            ptsLinkMapper.updatePtsLink(ptsLink);
            //同步菜单增加
            IBaseMenu menu = new SysMenu();
            menu.setMenuId(ptsLink.getLinkId());  //菜单Id就是LinkId
            menu.setMenuName(ptsLink.getLinkName());
            menu.setMenuParentid(PtsConstants.PTS_SYS_TOP_MENU_kEY);
            menu.setMenuPerms(UserConstants.TYPE_EMPTY);
            menu.setMenuOpentype(ptsLink.getLinkOpentype());  //外
            menu.setMenuPath(ptsLink.getLinkPath());
            menu.setMenuSeq(String.valueOf(ptsLink.getLinkSeq()));
            menu.setMenuVisiblestatus(ptsLink.getLinkVisiblestatus());
            menu.setMenuStatus(UserConstants.NORMAL);
            menu.setMenuType(UserConstants.TYPE_MENU);
            menu.setMenuIcon("guide");
            menu.setMenuCreator(user.getUserId());
            menu.setMenuCreateddate(DateUtils.dateTimeNow());
            menu.setMenuModifier(user.getUserId());
            menu.setMenuModifieddate(DateUtils.dateTimeNow());
            menu.setMenuApistatus(UserConstants.NORMAL);
            menu.setMenuRemark("门户模块-门户首页子系统展示");

            int n = sysMenuService.insertMenu(menu);
            return n;
        }catch (DuplicateKeyException e){
            throw new BizException(ErrorCode.ADD_MENU_NAME_ERROR.getCode(), ErrorCode.ADD_MENU_NAME_ERROR.getMessage());
        }
    }

    /**
     * 修改链接
     * 
     * @param ptsLink 链接
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePtsLink(PtsLink ptsLink,LoginUser user)
    {
        try {
            //更新资源
            SysRes.add( ptsLink.getResList() ,ResConstants.formType.ADD,ptsLink.getLinkId() );
            //同步菜单更新
            ptsLink.setLinkModifier(user.getUserId());
            ptsLink.setLinkModifieddate(DateUtils.dateTimeNow());
            ptsLink.setLinkRemark(ptsLink.getLinkName());
            ptsLink.setLinkQuery(UserConstants.TYPE_EMPTY);
            ptsLink.setLinkOpentype(UserConstants.NO_FRAME);
            List<SysRes> resIcon = resManager.queryRes(ptsLink.getLinkId() , ResConstants.BizType.SYSLINK.getKey());
            if(resIcon.size() > 0 ) {
                if(SpringUtils.getBean(PolicyService.class).isOssCloudPolicy()){
                    ptsLink.setLinkIcon( resIcon.get(0).getResOssUrl() );
                }else ptsLink.setLinkIcon( resIcon.get(0).getResUrl() );
            }
            ptsLinkMapper.updatePtsLink(ptsLink);
            IBaseMenu menu = new SysMenu();
            menu.setMenuId(ptsLink.getLinkId());  //菜单Id就是LinkId
            menu.setMenuName(ptsLink.getLinkName());
            menu.setMenuVisiblestatus(ptsLink.getLinkVisiblestatus());
            menu.setMenuPath(ptsLink.getLinkPath());
            menu.setMenuPerms(UserConstants.TYPE_EMPTY);
            menu.setMenuRemark("门户模块-门户首页子系统展示");
            menu.setMenuModifier(user.getUserId());
            menu.setMenuModifieddate(DateUtils.dateTimeNow());
            if (menu.getMenuId().equals(menu.getMenuParentid()))
            {
                throw new BizException(ErrorCode.ADD_MENU_PARENT_ERROR.getCode(),ErrorCode.ADD_MENU_PARENT_ERROR.getMessage());
            }
            int n = sysMenuService.updateMenu(menu);
            return n;
        }catch (DuplicateKeyException e){
            throw new BizException(ErrorCode.ADD_MENU_NAME_ERROR.getCode(), ErrorCode.ADD_MENU_NAME_ERROR.getMessage());
        }
    }

    /**
     * 批量删除链接
     * 
     * @param linkIds 需要删除的链接主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePtsLinkByLinkIds(String[] linkIds)
    {
        //同步菜单删除
        String linkIdss = String.join(",", linkIds);
        if (sysMenuService.hasChildByMenuId( linkIdss))
        {
            throw new BizException(ErrorCode.ADD_MENU_HAVCHILD_ERROR.getCode(),ErrorCode.ADD_MENU_HAVCHILD_ERROR.getMessage());
        }
        if (sysMenuService.checkMenuExistRole(linkIdss))
        {
            throw new BizException(ErrorCode.ADD_MENU_HAVGIVE_ERROR.getCode(),ErrorCode.ADD_MENU_HAVGIVE_ERROR.getMessage());
        }
        sysMenuService.deleteMenuById(linkIdss);
        //删除资源
        resManager.deleteRes(linkIds);
        int n = ptsLinkMapper.deletePtsLinkByLinkIds(linkIds);
        return n;
    }

    /**
     * 删除链接信息
     * 
     * @param linkId 链接主键
     * @return 结果
     */
    @Override
    public int deletePtsLinkByLinkId(String linkId)
    {
        //删除资源
        String[] resBusIds = new String[]{ linkId };
        resManager.deleteRes(resBusIds);
        return ptsLinkMapper.deletePtsLinkByLinkId(linkId);
    }
}
