package com.dgtly.wxportal.service.impl;

import com.alibaba.fastjson.JSON;
import com.dgtly.common.constant.UserConstants;
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.HomeIconConfig;
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 com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
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
    JdbcTemplate jdbcTemplate;
    @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(),wxMagnet.getUserType());
        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());
        }
        for (WxMagnet magnet : wxMagnetList){
            if (StringUtils.isNotEmpty(magnet.getUserType())){
               if ("0".equals(magnet.getUserType())){
                   magnet.setMagnetName(magnet.getMagnetName()+"(好邦手)");
               }else if ("1".equals(magnet.getUserType())){
                   magnet.setMagnetName(magnet.getMagnetName()+"(经销商随身邦)");
               }else if ("2".equals(magnet.getUserType())){
                   magnet.setMagnetName(magnet.getMagnetName()+"(服务商随身邦)");
               }else if ("3".equals(magnet.getUserType())){
                   magnet.setMagnetName(magnet.getMagnetName()+"(金牌店随身邦)");
               }
            }
        }
        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,String  loginType) {
        List<WxMagnet> list  = wxMagnetMapper.selectMagnetByUserId(userId,loginType);
        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;
    }


    public static boolean isValidJson(String jsonStr) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(jsonStr);
            return true;
        } catch (Exception e) {
            return false;
        }


    }
    /*保存首页图标配置*/
    @Override
    public void updateHomeIcon(HomeIconConfig homeIconConfig) {
       //校验json字符串是否正确
       if(StringUtils.isNotBlank(homeIconConfig.getSmall_icon_extra())){
           if(!isValidJson(homeIconConfig.getSmall_icon_extra())){
              throw new RuntimeException("小图标json数据格式错误！");
           }
       }
        if(StringUtils.isNotBlank(homeIconConfig.getActivity_icon_extra())){
            if(!isValidJson(homeIconConfig.getActivity_icon_extra())){
                throw new RuntimeException("活动图标json数据格式错误！");
            }
        }
        if(homeIconConfig.getId()==null) {
            String insertSql = "INSERT INTO system_home_config (portal_background,small_icon_extra,activity_icon_extra,activity_icon_starttime,activity_icon_endtime,bottom_prompt_text,prompt_text_color,create_by,create_time) VALUES (?,?,?,?,?,?,?,?,now());";
            Object[] args = new Object[]{homeIconConfig.getPortal_background(), homeIconConfig.getSmall_icon_extra(), homeIconConfig.getActivity_icon_extra(), homeIconConfig.getActivity_icon_starttime(), homeIconConfig.getActivity_icon_endtime(), homeIconConfig.getBottom_prompt_text(), homeIconConfig.getPrompt_text_color(),homeIconConfig.getCreateBy()};
            jdbcTemplate.update(insertSql, args);
        }else {
            String updateSql = "update  system_home_config  set portal_background=?,small_icon_extra=?,activity_icon_extra=?,activity_icon_starttime=?,activity_icon_endtime=?,bottom_prompt_text=?,prompt_text_color=?,update_by=?,update_time=now() where id=?;";
            Object[] args = new Object[]{homeIconConfig.getPortal_background(), homeIconConfig.getSmall_icon_extra(), homeIconConfig.getActivity_icon_extra(), homeIconConfig.getActivity_icon_starttime(), homeIconConfig.getActivity_icon_endtime(), homeIconConfig.getBottom_prompt_text(), homeIconConfig.getPrompt_text_color(), homeIconConfig.getUpdateBy(), homeIconConfig.getId()};
            jdbcTemplate.update(updateSql, args);
        }
    }

    @Override
    public Map<String, Object> selectHomeIconInfoById() throws JsonProcessingException {
        List<Map<String,Object>> iconInfos=jdbcTemplate.queryForList("select * from system_home_config ");
        Map<String,Object> iconInfo= iconInfos.size()!=0?iconInfos.get(0):null;
        if(iconInfo!=null) {
            String smallIconString = iconInfo.get("small_icon_extra")!=null?iconInfo.get("small_icon_extra").toString():"";
            String activityIconString = iconInfo.get("activity_icon_extra")!=null?iconInfo.get("activity_icon_extra").toString():"";
            if (StringUtils.isNotBlank(smallIconString)) {
                Map mapType = JSON.parseObject(smallIconString, Map.class);
                iconInfo.put("smallIconObject", mapType);
                iconInfo.remove("small_icon_extra");
            }
            if (StringUtils.isNotBlank(activityIconString)) {

                ObjectMapper mapper = new ObjectMapper();

                    String[] array = mapper.readValue(activityIconString, String[].class);

                iconInfo.put("activityIconObject", array);
                iconInfo.remove("activity_icon_extra");
            }
            return iconInfo;
        }
        return null;
    }


}
