package com.pine.admin.modules.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pine.admin.modules.base.service.RedisService;
import com.pine.admin.modules.system.dao.SysPermissionDao;
import com.pine.admin.modules.system.dao.SysUserDao;
import com.pine.admin.modules.system.entity.ActiveUser;
import com.pine.admin.modules.system.entity.SysPermission;
import com.pine.admin.modules.system.entity.SysUser;
import com.pine.admin.modules.system.service.SysService;
import com.pine.admin.shiro.DealerOpenIdToken;
import com.pine.admin.shiro.ShiroUserInfo;
import com.pine.common.dto.Result;
import com.pine.common.exception.ApiException;
import com.pine.common.utils.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

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

/**
 * @author Create By Pine
 * zhangsong@crmhby.com
 * @date 2018/3/27 10:44
 */
@Service
@Slf4j
public class SysServiceImpl implements SysService {
    @Autowired
    private SysUserDao sysUserMapper;

    @Autowired
    private SysPermissionDao sysPermissionMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public ActiveUser authenticat(String userCode, String password) {

        /**
         * 认证过程： 根据用户身份(账号)查询数据库，如果查询不到则用户不存在
         * 对输入的密码和数据库密码进行比对，如果一致则认证通过
         */

        // 根据用户账号查询数据库
        SysUser sysUser = new SysUser();

        sysUser.setUsercode(userCode);

        sysUser = sysUserMapper.querySysUser(sysUser);

        // 数据库密码（MD5加密后的密码）
        String password_db = sysUser.getPassword();

        // 对输入的密码和数据库密码进行比对，如果一致，认证通过
        // 对页面输入的密码进行MD5加密
        String password_input_md5 = MD5Util.getMD5(password);

        //得到用户id
        Integer userId = sysUser.getId();
        //根据用户id查询菜单
        List<SysPermission> menus = this.findMenuListByUserId(userId);
        //根据用户id查询权限url
        List<SysPermission> permissions = this.findPermissionListByUserId(userId);

        //认证通过，返回用户身份信息
        ActiveUser activeUser = new ActiveUser();
        activeUser.setUserId(userId);
        activeUser.setUserCode(userCode);
        activeUser.setUserName(sysUser.getUsername());

        //放入权限范围的菜单和url
        activeUser.setMenus(menus);
        activeUser.setPermissions(permissions);

        return activeUser;
    }

    @Override
    public List<SysPermission> findMenuListByUserId(Integer userId) {
        return sysPermissionMapper.findMenuListByUserId(userId);
    }

    @Override
    public List<SysPermission> findPermissionListByUserId(Integer userId) {
        return sysPermissionMapper.findPermissionListByUserId(userId);
    }

    @Override
    public String decryptUser(String ips, String casualBacking) {
        log.info("ip:"+ips);
        String responseString = RSAUtils.changeSpecialToString(casualBacking);
        if (StringUtils.isEmpty(responseString)) {
            log.error("offlineAudit fail due to rsa decrypt fail");
            throw new ApiException("秘钥解析失败");
        }
//        String redisKey = RSAUtils.encrypt(RSAUtils.publicKey, ip + ":" + responseString);
        String redisKey = ips + ":" + responseString;

        log.info("免密登录key：" + redisKey);

        Map<String, String> map = new HashMap<>();
        map.put("key", redisKey);
        log.info(redisKey);
        String dealerInfo = PostUtil.formUpload(Constant.LOGIN_REDIS_API, map, null, "");
        log.info("url:"+Constant.LOGIN_REDIS_API+"PARAM:"+map.get("key"));
        log.info("获取经销商信息：" + dealerInfo);
        if (StringUtils.isEmpty(dealerInfo)) {
            throw new ApiException("用户未登录");
        }
        Map maps = (Map) JSON.parse(dealerInfo);

        if (maps.get("code").equals(-1)) {
            throw new ApiException(maps.get("msg").toString());
        }

        ShiroUserInfo userInfo = JSONObject.parseObject(maps.get("data").toString(), ShiroUserInfo.class);


        if (!userInfo.getAccount().equals(responseString)) {
            throw new ApiException("非法操作");
        }

        if (StringUtils.isEmpty(userInfo.getDealerID())) {
            throw new ApiException("用户信息丢失");
        }

        if (StringUtils.isEmpty(userInfo.getName())) {
            throw new ApiException("用户信息丢失");
        }

        userInfo.getCreateTime();

        return maps.get("data").toString();
    }

    @Override
    public DealerOpenIdToken dealerLogin(String userCode, String password) {
        DealerOpenIdToken dealerOpenIdToken;
        try {
            Map<String, String> map = new HashMap<>();
            map.put("account", userCode);
            map.put("password", PasswordEncryptorUtils.md5AndBase64Encryptor(password));

            String s2 = PostUtil.formUpload(Constant.LOGIN_URL, map, null, "");
            log.info("经销商登录：" + s2);
            Map maps = (Map) JSON.parse(s2);

            if (maps.get("code").equals(-1)) {
                throw new ApiException(maps.get("msg").toString());
            }

            if (null == maps.get("data")) {
                String dd = "{\"erp\":\"8888\",\"dealerId\":8888,\"name\":\"商城管理员\",\"roleType\":\"商城管理员\"}";
                dealerOpenIdToken = new DealerOpenIdToken(dd);
            } else {
                dealerOpenIdToken = new DealerOpenIdToken(maps.get("data").toString());
            }
            return dealerOpenIdToken;

        } catch (Exception e) {
            throw new ApiException(e.getMessage());
        }
    }
}
