package com.sifang.modules.smallprogram.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.site.siteInfo.dao.SiteEmployeeDao;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.util.AuthUtils;
import com.sifang.modules.sys.util.CrmUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class LoginService extends BaseService {
    @Autowired
   private UserDao userDao;

    @Autowired
    SiteEmployeeDao siteEmployeeDao;

    @Autowired
    TraderService traderService;

    /**
     * 验证手机登录
     */
    public Map<String,String>  ifLogin(String loginName,String password, String from){
        Map<String,String> map=new HashMap<>();
        if(StringUtil.isBlank(loginName)|| StringUtil.isBlank(password)){
            map.put("isLogin","false");
            map.put("msg","账号密码错误，请重新登录！");
            return map;
        }
         String md5Password = HashKit.md5(password.trim());
       User user=userDao.findByLoginName(loginName);
        if(user==null) {
            map.put("isLogin","202");
            map.put("msg","账号不存在，请重新登录！");
            return map;
        }
         if(md5Password.equals(user.getPassword())){
             String userType = user.getUserType();
             if ("RROJECT_MANAGE".equals(from)) {
                 if (User.USER_TYPE_ADVISOR.equals(userType) || User.USER_TYPE_KJ.equals(userType)) {
                     map.put("isLogin", "200");
                     map.put("userId", user.getId());
                     map.put("userType", getUserType(user));
                     map.put("currentUserType", userType);
                     map.put("userName", CrmUtils.getUserXM(user));
                     User user1 = UserUtils.getUser(user.getId());
                     Record record = CrmUtils.getByUserId(user);
                     map.put("mobile", record.getStr("mobile"));
                     map.put("traderId", record.getStr("trader_id"));
                     map.put("traderName",record.getStr("name"));
                     map.put("traderType",user1.getTraderType());
                     if (User.USER_TYPE_ADVISOR.equals(userType)) {
                         /*List<String> menuList = AuthUtils.findMiniTraderEmpPremins(record.getStr("id"));
                         if (menuList.size() < 1) {
                             map.put("isLogin", "203");
                             map.put("msg", "暂无权限登录，请让管理员授权登录！");
                             return map;
                         }
                         map.put("menuList", JSONObject.toJSONString(menuList));*/
                         List<String> menus = AuthUtils.getTraderEmpMenusForSmallProgram(record.getStr("role_id"));
                         if (menus == null || menus.isEmpty()) {
                             map.put("isLogin", "203");
                             map.put("msg", "暂无权限登录，请让管理员授权登录！");
                             return map;
                         }
                         // 获取权限
                         map.put("menuList", JSONObject.toJSONString(menus));
                     }
                 } else if (User.USER_TYPE_WXG.equals(userType)) {
                     // 平台员工登录-231206
                     Record r = CrmUtils.getByUserId(user);
                     EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
                     // TODO 先做权限判断
                     String menus = AuthUtils.getPlatEmpMenusForSmallProgram(r.getStr("id"), null);
                     if ("NULL".equals(menus)) {
                         map.put("isLogin","203");
                         map.put("msg","暂无权限登录，请让平台管理员授权登录！");
                         return map;
                     }
                     List<String> list = Lists.newArrayList();
                     String[] arr = menus.split(",");
                     Collections.addAll(list, arr);
                     // 登录成功 返回数据
                     map.put("isLogin", "200");
                     map.put("userId", user.getId());
                     map.put("userType", "PLATFORM_EMP");
                     map.put("currentUserType", userType);
                     map.put("userName", r.getStr("name"));
                     map.put("mobile", r.getStr("mobile"));
                     map.put("menuList", JSONObject.toJSONString(list));
                     map.put("menus", menus);
//                     map.put("traderList", JSONObject.toJSONString(traderService.getTraderList(map)));
                 }
                 else {
                     //暂无权限登陆
                     map.put("isLogin","203");
                     map.put("msg","暂无权限登录！");
                     return map;
                 }
             }else if(User.USER_TYPE_HUI.equals(userType)){
                    Record rd = siteEmployeeDao.getRole(user.getId());
                    if(rd!= null && rd.getInt("role")==2){
                        map.put("isLogin","200");
                        map.put("siteId",rd.getStr("site_id"));
                        map.put("userType",userType);
                        map.put("userId",user.getId());
                        map.put("userName",rd.getStr("name"));
                    }else{
                        //暂无权限登陆
                        map.put("isLogin","203");
                        map.put("msg","暂无权限登录！");
                        return map;
                    }
             }
         }else{
             map.put("isLogin","201");
             map.put("msg","密码错误！");
         }

     return map;
    }

    private String getUserType(User user){
        if (User.USER_TYPE_KJ.equals(user.getUserType())) {
            //代理商
            return "TRADER";
        } else if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            //代理商员工
            return "TRADER_EMP";
        } else if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            List<Record> list = siteEmployeeDao.findRolesByUserId(user.getId());
            Record role = list.get(0);
            //1.系统工程师（默认）2.项目工程师（默认）
            if(SourceConstants.ONE.equals(role.getStr("type"))){
                return "SYS_EMP";
            }else if(SourceConstants.TWO.equals(role.getStr("type"))){
                return "PRO_EMP";
            }
        }
        return "";
    }

    /**
     * 忘记密码后的重置密码
     */
    @Transactional(rollbackFor = Exception.class)
    public Result resetPassword(String telephoneNumber,String password){
        Result result=new Result();
        if(StringUtil.isBlank(telephoneNumber)|| StringUtil.isBlank(password)){
            result.setCode("500");
            return result;
        }
        try {
            User user=userDao.findByMobile(telephoneNumber);
            if(user!=null){
                user.setPassword(HashKit.md5(password));
                user.setUpdateTime(new Date());
                userDao.save(user);
                result.setCode("200");   //修改成功
            }else{
                result.setCode("500");   //修改失败
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("500");
        }

        return result;
    }
    /**
     * 重置密码时 点击获取验证码按钮---获取验证码
     */
    public String checkMobile(String mobile, String code) {
        try {
            Long count = Db.queryLong("select count(*) from sys_user a where a.status='0' and a.login_name='" + mobile + "'");
            if (count > 0) {
                return "ok";
            }
            return "noName";
        } catch (Exception e) {
            return "no";
        }

    }
    /**
     * 校验输入的验证码和手机获取的是否一致
     * @param codeMsg
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String checkConfirmCode(String code,String codeMsg,String mobile){
        String result = "ok";
        Long count = Db.queryLong("select count(*) from sys_user a where a.status='0' and a.login_name='" + mobile + "'");
        if(!codeMsg.equals(code)){
            return "wrongMsg";
        }
        if (count < 0) {
            return "noName";
        }

        return result;
    }
}
