package com.dgtly.wxportal.service.impl;

import com.dgtly.common.constant.UserConstants;
import com.dgtly.common.core.controller.ApiBaseController;
import com.dgtly.common.core.domain.Ztree;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.system.domain.SysRole;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.mapper.SysRoleMenuMapper;
import com.dgtly.system.service.ISysConfigService;
import com.dgtly.wxportal.domain.RoleMagnet;
import com.dgtly.wxportal.domain.WxMagnet;
import com.dgtly.wxportal.mapper.WxMagnetMapper;
import com.dgtly.wxportal.service.IWxMagnetService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 菜单 业务层处理
 *
 * @author dgtly
 */
@Service
public class WxMagnetServiceImpl implements IWxMagnetService
{
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private WxMagnetMapper wxMagnetMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private ISysConfigService configService;

    protected final Logger logger = LoggerFactory.getLogger(WxMagnetServiceImpl.class);


    /**
     * 查询H5磁贴列表
     *
     * @param wxMagnet 菜单信息
     * @return 磁贴列表
     */
    @Override
    public List<WxMagnet> selectMagnetList(WxMagnet wxMagnet)
    {

        List<WxMagnet> menuList = wxMagnetMapper.selectMagnetList(wxMagnet);
        return menuList;
    }

    @Override
    public List<WxMagnet> selectTileMagnetList(WxMagnet wxMagnet) {
        List<WxMagnet> menuList = wxMagnetMapper.selectTileMagnetList(wxMagnet);
        return menuList;
    }


    /**
     * 查询磁贴使用数量
     *
     * @param magnetId 菜单ID
     * @return 结果
     */
    @Override
    public Integer selectCountRoleMagnetByMagnetId(Long magnetId) {
        return wxMagnetMapper.selectCountRoleMagnetByMagnetId(magnetId);
    }

    /**
     * 删除磁贴管理信息
     *
     * @param magnetId 磁贴ID
     * @return 结果
     */
    @Override
    public int deleteMagnetById(Long magnetId) {
        return wxMagnetMapper.deleteMagnetById(magnetId);
    }

    /**
     * 根据磁铁ID查询信息
     *
     * @param magnetId 磁铁ID
     * @return 菜单信息
     */
    @Override
    public WxMagnet selectMagnetById(Long magnetId) {
        return wxMagnetMapper.selectMagnetById(magnetId);
    }

    /**
     * 校验菜磁贴名称是否唯一
     *
     * @param wxMagnet 磁贴信息
     * @return 结果
     */
    @Override
    public String checkMagnetNameUnique(WxMagnet wxMagnet) {
        Long magnetId = StringUtils.isNull(wxMagnet.getMagnetId()) ? -1L : wxMagnet.getMagnetId();
        WxMagnet info = wxMagnetMapper.checkMagnetNameUnique(wxMagnet.getMagnetName());
        if (StringUtils.isNotNull(info) && info.getMagnetId().longValue() != magnetId.longValue())
        {
            return UserConstants.MENU_NAME_NOT_UNIQUE;
        }
        return UserConstants.MENU_NAME_UNIQUE;
    }

    /**
     * 新增保存磁贴信息
     *
     * @param wxMagnet 磁贴信息
     * @return 结果
     */
    @Override
    public int insertMagnet(WxMagnet wxMagnet) {
        return wxMagnetMapper.insertMagnet(wxMagnet);
    }

    /**
     * 修改保存磁贴信息
     *
     * @param wxMagnet 磁贴信息
     * @return 结果
     */
    @Override
    public int updateMagnet(WxMagnet wxMagnet) {
        return wxMagnetMapper.updateMagnet(wxMagnet);
    }

    /**
     * 根据角色ID查询磁贴
     *
     * @param role 角色对象
     * @return 磁贴列表
     */
    @Override
    public List<Ztree> roleMagnetTreeData(SysRole role, SysUser user) {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        WxMagnet wxMagnet = new WxMagnet();
        //wxMagnet.setVisible("0");
        List<WxMagnet> wxMagnetList;
        if (user.isAdmin())
        {
            wxMagnetList = wxMagnetMapper.selectMagnetList(wxMagnet);
        }
        else
        {
            wxMagnetList = wxMagnetMapper.selectMagnetAllByUserId(wxMagnet,user.getUserId());
        }
        if (StringUtils.isNotNull(roleId))
        {
            List<String> roleMagnetList = wxMagnetMapper.selectMagnetIdByRoleId(roleId);
            ztrees = initZtree(wxMagnetList, roleMagnetList);
        }
        else
        {
            ztrees = initZtree(wxMagnetList, null);
        }
        return ztrees;
    }



    @Override
    public List<WxMagnet> selectMagnetListByRole(WxMagnet wxMagnet, SysUser user) {
        List<WxMagnet> wxMagnetList = null;
        if (user.isAdmin())
        {
            wxMagnetList = wxMagnetMapper.selectMagnetList(wxMagnet);
        }
        else
        {
            wxMagnetList = wxMagnetMapper.selectMagnetAllByUserId(wxMagnet,user.getUserId());
        }
        return wxMagnetList;
    }

    @Override
    public int upDateRoleMagnet(String roleId, String magnetIds) {
        //
        int i = wxMagnetMapper.deleteRoleMagnetByRoleId(roleId);
        List<RoleMagnet> roleMagnetList = new ArrayList<>();
        String s[] = magnetIds.split(",");
        if(!magnetIds.trim().equals("")){
            for(String str:s){
                RoleMagnet roleMagnet = new RoleMagnet();
                roleMagnet.setMagnetId(Long.parseLong(str));
                roleMagnet.setRoleId(Long.parseLong(roleId));
                roleMagnetList.add(roleMagnet);
            }
            return wxMagnetMapper.batchRoleMagnet(roleMagnetList);
        }else{
            return i;
        }
    }

    /**
     * 根据用户id查询所拥有的的磁贴
     * @param userId
     * @return
     */
    @Override
    public List<WxMagnet> selectMagnetByUserId(String userId, String cw, String salesLevel) {
//        List<WxMagnet> list;
//        if (StringUtils.isNotEmpty(cw) && null != salesLevel && "customer_level".equals(salesLevel)) {
//            String roleId = cw.equals("1") ? configService.selectConfigByKey("libang.customer.roleid") : configService.selectConfigByKey("libang.cw.roleid");
//            list = wxMagnetMapper.selectMagnetByCw(userId, roleId);
//        } else {
//            list = wxMagnetMapper.selectMagnetByUserId(userId);
//        }
        List<WxMagnet> list  = wxMagnetMapper.selectMagnetByUserId(userId);
        if(list!=null && list.size()>0){
            for(WxMagnet wxMagnet: list){
                logger.info("isEncry::::"+wxMagnet.getIsEncry());
                if("1".equals(wxMagnet.getIsEncry())){
                    String sapEmploeeId = this.wxMagnetMapper.selectSapEmploeeIdByUserId(userId);
                    logger.info("sapEmploeeId::::"+sapEmploeeId);
                    if(StringUtils.isNotEmpty(sapEmploeeId)){
                        String encry = KL(sapEmploeeId);
                        wxMagnet.setUrl(wxMagnet.getUrl()+"?empCode="+encry);
                        logger.info("url::::"+wxMagnet.getUrl());
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<WxMagnet> selectWxMagnetRoleByUserId(Long userId, String magnetName) {
        List<WxMagnet> list  = wxMagnetMapper.selectWxMagnetRoleByUserId(userId,magnetName);

        return list;
    }


    public static String KL(String inStr) {
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;
    }



    /**
     * 对象转磁贴树
     *
     * @param wxMagnetList 磁贴列表
     * @param roleMagnetList 角色已存在磁贴单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<WxMagnet> wxMagnetList, List<String> roleMagnetList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleMagnetList);
        for (WxMagnet wxMagnet : wxMagnetList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(wxMagnet.getMagnetId());
            ztree.setpId(0L);
            ztree.setName(wxMagnet.getMagnetName());
            ztree.setTitle(wxMagnet.getMagnetName());
            if (isCheck)
            {
                ztree.setChecked(roleMagnetList.contains(wxMagnet.getMagnetId().toString()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

}
