package com.ruoyi.web.userLogin.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.DeptTypeEnum;
import com.ruoyi.common.enums.SysRoleEnum;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.project.mapper.WxProjectInfoMapper;
import com.ruoyi.web.userLogin.mapper.WechatUserLoginMapper;
import com.ruoyi.web.userLogin.service.IWechatUserLoginService;
import com.yanzhu.jh.project.domain.SurProject;
import com.yanzhu.jh.project.mapper.SurProjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @version : V1.0
 * @ClassName: WechatUserLoginServiceImpl
 * @Description: 微信用户登录
 * @Auther: JiangYuQi
 * @Date: 2020/7/7 18:03
 */
@Service
public class WechatUserLoginServiceImpl implements IWechatUserLoginService {

    private static Map<String,String>appInfo  = new HashMap<>();

    static {
        //产发数字系统
        appInfo.put("wxc44b5d588f599758","b4da7402397f559395db7c1b0534c369");
    }

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SurProjectMapper surProjectMapper;

    @Autowired
    private WechatUserLoginMapper wechatUserLoginMapper;

    @Autowired
    private WxProjectInfoMapper ProjectInfoMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 获取用户信息
     * @param loginName
     * @return
     */
    @Override
    public Map<String, Object> findUserInfo(String loginName,String openId) {
        Map<String,Object> data = new HashMap<>();
        Map<String, Object> userData = wechatUserLoginMapper.findUserInfo(loginName);
        Map<String,Object> userInfo = new HashMap<>();
        userInfo.put("loginName",loginName);
        userInfo.put("userName",userData.get("user_name"));
        userInfo.put("nickName",userData.get("nick_name"));
        userInfo.put("deptName",userData.get("dept_name"));
        userInfo.put("deptId",userData.get("dept_id"));
        userInfo.put("userId",userData.get("user_id"));
        userInfo.put("remark",userData.containsKey("remark")?userData.get("remark"):"");
        userInfo.put("roleId",userData.get("roleId"));
        userInfo.put("roleName",userData.get("roleName"));
        userInfo.put("minRoleId",userData.get("minRoleId"));
        /** 查询当前用户项目信息 **/

        SurProject surProject = new SurProject();
        String nowRole = Convert.toStr(userData.get("minRoleId"));
        if(SysRoleEnum.ZGS.getCode().equals(nowRole)){
            Long deptId = this.getZgsDept(Convert.toLong(userData.get("dept_id"))).getDeptId();
            surProject.setNowDept(Convert.toStr(deptId));
        }else{
            surProject.setNowDept(Convert.toStr(userData.get("dept_id")));
        }
        //当前角色时管理员时，修改角色为集团公司
        if(Convert.toInt(SysRoleEnum.JTGS.getCode())>Convert.toInt(nowRole)){
            nowRole = SysRoleEnum.JTGS.getCode();
        }
        surProject.setNowRole(nowRole);
        surProject.setNowUser(Convert.toStr(userData.get("user_id")));
        List<SurProject> projectList  = surProjectMapper.selectSurProjectList(surProject);
        //只有一个项目时直接保存项目信息
        if(projectList!=null && projectList.size()==1){
            Map<String,Object> projectInfo = new HashMap<>();
            projectInfo.put("projectId",projectList.get(0).getId());
            projectInfo.put("projectName",projectList.get(0).getProjectName());
            projectInfo.put("projectInfoList",projectList);
            projectInfo.put("shengName","西安市");
            projectInfo.put("shiName","西咸新区");
            projectInfo.put("quName","泾河新城");
            projectInfo.put("logCompanyName",userData.get("dept_name"));
            data.put("projectInfo",projectInfo);
        }
        data.put("userinfo",userInfo);
        //存储用户openid
        Map<String,Object> map = new HashMap<>();
        map.put("loginName",loginName);
        map.put("userId", Convert.toStr(userData.get("user_id")));
        map.put("nickname",userData.get("nick_name"));
        map.put("openId",openId);
        //验证手机号码是否绑定
        int count = wechatUserLoginMapper.checkBindByOpenId(openId);
        if(count > 0){
            wechatUserLoginMapper.updateUserOpenId(map);
        }else {
            wechatUserLoginMapper.addUserOpenId(map);
        }
        return data;
    }

    /**
     * 根据openId查询用户认证对象
     * @param openId
     * @return
     */
    public Map<String, Object> getLoginUserByOpenId(String openId) {
        Map<String,Object> userMap = wechatUserLoginMapper.getUserNameByOpenId(openId);
        if(userMap!=null){
            return this.findUserInfo(userMap.get("loginName").toString(),openId);
        }else{
            return null;
        }

    }

    /**
     * 查询子公司部门ID
     *
     * @param deptId 部门ID
     * @return 结果
     */
    private SysDept getZgsDept(Long deptId){
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        if(DeptTypeEnum.ZGS.getCode().equals(sysDept.getTypeFlag())){
            //comFlag标识为1是子公司
            if(DeptTypeEnum.COMFLAG.getCode().equals(sysDept.getComFlag())){
                return sysDept;
            }else{
                return getZgsDept(sysDept.getParentId());
            }
        }else{
            return sysDept;
        }
    }

    @Override
    public Map<String, Object> getOpenId(String code, String appId) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appInfo.get(appId)+"&js_code="+code+"&grant_type=authorization_code";
        String resultStr = HttpUtil.get(url);
        JSONObject json = JSONObject.parseObject(resultStr);
        //删除参数session_key，否则小程序检测关键参数暴露，提示整改
        json.remove("session_key");
        return json;
    }

    /**
     * 根据用户查询菜单信息
     * @param username
     * @return
     */
    @Override
    public List<Map<String,Object>> selectRoleMenuList(String username) {
        return wechatUserLoginMapper.selectRoleMenuList(username);
    }

    @Override
    public Map<String, Object> getDeptAll(Map<String,Object> map) {
        //当前登录账号角色信息
        String nowRole = null;
        if(map.get("minRoleId")!=null && !"undefined".equals(map.get("minRoleId"))){
            nowRole = map.get("minRoleId").toString();
        }else{
            nowRole = Convert.toStr(sysRoleMapper.getUserMinRoleId(Convert.toLong(map.get("userId"))));
        }

        Map<String,Object> dataMap = new HashMap<>(16);
        //组装数据
        dataMap.put("shengName","西安市");
        dataMap.put("shiName","西咸新区");
        dataMap.put("quName","泾河新城");
        //公司信息
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> totalMap = new HashMap<>(16);
        //查询出公司信息
        if(SysRoleEnum.ADMIN.getCode().equals(nowRole) || SysRoleEnum.SUPR.getCode().equals(nowRole) || SysRoleEnum.JTGS.getCode().equals(nowRole) ){
            List<Map<String,Object>> companyList = ProjectInfoMapper.getZGSDeptInfoByMap(map);
            totalMap.put("id","0");
            totalMap.put("text","泾河产业发展集团");
            list.add(totalMap);
            for(Map<String,Object> companyMap:companyList){
                totalMap = new HashMap<>(16);
                totalMap.put("id",companyMap.get("dept_id"));
                totalMap.put("text",companyMap.get("dept_name"));
                list.add(totalMap);
            }
        }else if(SysRoleEnum.ZGS.getCode().equals(nowRole)){
            SysDept sysDept = this.getZgsDept(Convert.toLong(map.get("deptId")));
            totalMap.put("id",sysDept.getDeptId());
            totalMap.put("text",sysDept.getDeptName());
            list.add(totalMap);
        }else if(SysRoleEnum.COMMON.getCode().equals(nowRole)){
            //普通角色，获取真实部门
            SysDept sysDept = this.getZgsDept(Convert.toLong(map.get("deptId")));
            //判断当前部门是否是产业发展集团
            if(DeptTypeEnum.JTGS.getCode().equals(sysDept.getTypeFlag()) || DeptTypeEnum.ZGS.getCode().equals(sysDept.getTypeFlag())){
                sysDept = this.getZgsDept(Convert.toLong(sysDept.getDeptId()));
                totalMap.put("id",sysDept.getDeptId());
                totalMap.put("text",sysDept.getDeptName());
                list.add(totalMap);
            }else{
                //普通角色
                totalMap.put("id",sysDept.getDeptId());
                totalMap.put("text",sysDept.getDeptName());
                list.add(totalMap);
            }
        }else{
            //监理单位/总包单位/分包单位
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(map.get("deptId")));
            totalMap.put("id",sysDept.getDeptId());
            totalMap.put("text",sysDept.getDeptName());
            list.add(totalMap);
        }
        dataMap.put("province_list",list);
        dataMap.put("deptId",map.get("deptId"));
        dataMap.put("logCompanyName",list.get(0).get("text"));
        dataMap.put("companyId",list.get(0).get("text"));
        return dataMap;
    }

    @Override
    public Map<String,Object> updataUser(Map<String, Object> map) {
        Map<String,Object> infoMap = new HashMap<>();
        String oldPws = Convert.toStr(map.get("oldPsw"));
        SysUser sysUser = sysUserMapper.selectUserByUserName(Convert.toStr(map.get("loginName")));
        if(!SecurityUtils.matchesPassword(oldPws,sysUser.getPassword())) {
            infoMap.put("data","-1");
            infoMap.put("info","旧密码错误，请重新输入！");
            return infoMap;
        }
        if(!Convert.toStr(map.get("newPsw")).equals(Convert.toStr(map.get("password")))){
            infoMap.put("data","-2");
            infoMap.put("info","两次密码不一致，请重新输入！");
            return infoMap;
        }
        map.put("password",SecurityUtils.encryptPassword(Convert.toStr(map.get("password"))));
        if(wechatUserLoginMapper.updataUser(map) > 0){
            infoMap.put("data","200");
            infoMap.put("info","操作成功");
        }else {
            infoMap.put("data","-3");
            infoMap.put("info","操作失败！");
        }
        return infoMap;
    }
}
