package com.sifang.modules.setting.dao;

import com.google.common.collect.Maps;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.platform.service.OnlineRechargeService;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.LayuiPage;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

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

@Repository
public class MemberDao {
    @Autowired
    MemberRoleDao memberRoleDao;

    private static final Logger logger = LoggerFactory.getLogger(OnlineRechargeService.class);

    public void saySth() {
        System.out.println(" dao say sth. ");
    }

    public List<Record> getMembers(Map<String, String> params,LayuiPage page){
        return getMembers(params, "",page);
    }
    public Long getMemberCount(Map<String, String> params){
        StringBuilder sb = new StringBuilder("");
        sb.append(" select count(a.id) ");
        sb.append(" from crm_platform_employee a ");
        sb.append(" left join crm_platform_employee_role_rel c on c.employee_id = a.id ");
        sb.append(" where  a.status = '0' ");
        sb.append(getCondition(params));
        return Db.queryLong(sb.toString());
    }
    public List<Record> getMembers(Map<String, String> params, String id, LayuiPage page){
        StringBuilder sb = new StringBuilder("");
        sb.append(" select a.id, a.status, a.name, a.mobile,a.provices, c.role_ids, b.login_name, a.hiredate,a.city,a.is_many,a.department_id ,d.name as gsname ,a.create_time ");
        sb.append(" from crm_platform_employee a inner join  sys_user  b on b.id = a.user_id and b.status = '0' and b.user_type = '4' ");
        sb.append(" left join crm_platform_employee_role_rel c on c.employee_id = a.id ");
        sb.append(" left join crm_department d ON a.department_id = d.id  ");
        sb.append(" where 1=1 ");
        if(StrKit.notBlank(id)){
            sb.append(" and a.id = '"+id+"' ");
        }
        sb.append(getCondition(params));
        sb.append(" and a.status = '0'  order by a.create_time desc");
        if(page!=null){
            sb.append(" limit " + page.getLimit() + " offset " + (page.getPage() - 1) * page.getLimit());
        }
        return Db.find(sb.toString());
    }

    public String getCondition(Map<String, String> params){
        StringBuilder sb = new StringBuilder("");
        if(params != null){
            if(params.containsKey("name") && StrKit.notBlank(params.get("name"))){
                sb.append(" and a.name like '%"+params.get("name").trim()+"%' ");
            }
            if(params.containsKey("mobile") && StrKit.notBlank(params.get("mobile"))){
                sb.append(" and a.mobile like '%"+params.get("mobile").trim()+"%' ");
            }
            if(params.containsKey("roleIds") && StrKit.notBlank(params.get("roleIds"))){
                sb.append(" and INSTR(c.role_ids,'" + params.get("roleIds") + "')>0 ");
            }
        }
        return sb.toString();
    }

    public Record getMembersById(String id){
        List<Record> rds = getMembers(null, id,null);
        return rds == null ? null : rds.get(0);
    }

    public List<Record> getMemberRoles(){
        User user = UserUtils.getUser();
        if(StringUtil.equalsAny(user.getUserType(), UserConstants.TYPE_TRADER,UserConstants.TYPE_JXS_EMP)){
            return Db.find(" SELECT * FROM crm_platform_employee_role a WHERE a.status = '0' and a.trader_id=? ORDER BY sort ASC ",user.getTraderId());
        }
        return Db.find(" SELECT * FROM crm_platform_employee_role a WHERE a.status = '0' and a.trader_id='1' ORDER BY sort ASC ");
    }

    public Map<String, String> transferRoleToMap(List<Record> roles){
        Map<String, String> map = Maps.newHashMap();
        for(Record rd : roles){
            map.put(rd.getStr("id"), rd.getStr("name"));
        }
        return map;
    }

    public boolean addMemberRole(String name){
        try{
            Db.update(" insert into   (id, name, status, default_tag) values (?, ?, ?, ?, ?) ",
                    IdGen.uuid(),  name, "0", 0);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public String addMember(Map<String, String> params) {
        try{
            String userId = IdGen.uuid();
            String memberId = IdGen.uuid();
            String createBy = UserUtils.getUser().getId();
            Date now = new Date();

            Record rd = getExistsLoginName("", params.get("loginName"));
            if(rd != null && StrKit.notBlank(rd.getStr("id"))){
                //登录名已存在
                return "existsLoginName";
            }
            String password = params.get("password");
          logger.info("平台添加新的员工  addMember "+params.get("loginName")+": "+password);
            StringBuilder usb = new StringBuilder("");
            usb.append(" insert into sys_user (id, login_name, password, user_type, mobile, create_by, create_date, create_type, status,department_id) ");
            usb.append(" values(?, ?, ?, ?, ?, ?, ?, ?, ?,?) ");
            Db.update(usb.toString(), userId, params.get("loginName"), HashKit.md5(password), "4", params.get("mobile"),
                    createBy, now, "1", "0", params.get("departmentId"));


            StringBuilder sb = new StringBuilder("");
            sb.append(" insert into crm_platform_employee (id, user_id, name, mobile, hiredate, status, create_by, create_time, provices,is_many,city,department_id) ");
            sb.append(" values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?) ");
            String hiredate = params.get("hiredate");
            if(hiredate .equals("")){
                Db.update(sb.toString(), memberId, userId, params.get("name"), params.get("mobile"), null, "0",
                        createBy, now, "","","",params.get("departmentId"));
            }else{
                Db.update(sb.toString(), memberId, userId, params.get("name"), params.get("mobile"), params.get("hiredate"), "0",
                        createBy, now, "","","",params.get("departmentId"));
            }

            refreshRoleRel(memberId, params.get("roleId"));

        }catch (Exception e){
            e.printStackTrace();
            return "err";
        }
        return "ok";
    }

    public String updateMember(Map<String, String> params){
        try{
            String memberId = params.get("id");
            String loginName = params.get("loginName");

            Record rd = getExistsLoginName(memberId, params.get("loginName"));
            if(rd != null && StrKit.notBlank(rd.getStr("id"))){
                //登录名已存在
                return "existsLoginName";
            }
            String depId = params.get("departmentId");
          //  Record memberRd = Db.findFirst(" select * from crm_platform_employee a where a.id = ? ", memberId);
         //   Record userRd = Db.findFirst(" select * from sys_user a where a.id = ? ", memberRd.getStr("user_id"));

            String name = params.get("name");
            String mobile = params.get("mobile");
            String roleIds = params.get("roleId");
            String password =  params.get("password");

            String hiredate = params.get("hiredate");
            Date htrDate =null;
            if(hiredate .equals("")){
                hiredate = null;
            }else{
                htrDate=DateUtils.parseDate(hiredate, "yyyy-MM-dd");
            }
            if("aqzaqaz@".equals(password)){
                StringBuilder sb = new StringBuilder("");
                sb.append(" update crm_platform_employee a , sys_user b ");
                sb.append(" set a.name = ? , b.login_name = ?, a.mobile = ?, b.mobile = ?, a.hiredate = ? ,a.department_id=?,b.department_id=?");
                sb.append(" where b.id = a.user_id and a.id = ? ");
                sb.append("  ");
                Db.update(sb.toString(), name, loginName, mobile, mobile, htrDate, depId,depId,memberId);
            }else{
                StringBuilder sb = new StringBuilder("");
                sb.append(" update crm_platform_employee a , sys_user b ");
                sb.append(" set a.name = ? , b.login_name = ?,b.password=?, a.mobile = ?, b.mobile = ?, a.hiredate = ? ,a.department_id=?,b.department_id=?");
                sb.append(" where b.id = a.user_id and a.id = ? ");
                sb.append("  ");
                Db.update(sb.toString(), name, loginName,HashKit.md5(password), mobile, mobile, htrDate, depId,depId,memberId);
            }

           logger.info("平台修改员工信息updateMember" +name+mobile);

            refreshRoleRel(memberId, roleIds);

        }catch (Exception e){
            e.printStackTrace();
            return "err";
        }
        return "ok";
    }

    public void refreshRoleRel(String memberId, String roleIds){
        Record rd = Db.findFirst(" select * from crm_platform_employee_role_rel a where a.employee_id = ? ", memberId);
        if(rd != null){
            //更新权限
            Db.update(" update crm_platform_employee_role_rel set role_ids = ? where employee_id = ? ", roleIds, memberId);
        }else{
            Db.update(" insert into crm_platform_employee_role_rel (id, employee_id, role_ids) values (?, ?, ?) ", IdGen.uuid(), memberId, roleIds);
        }
    }

    public boolean delMember(String id) {
        try{
            StringBuilder sb = new StringBuilder("");
            sb.append(" update crm_platform_employee a , sys_user b ");
            sb.append(" set a.status = '1', b.status = '1' ");
            sb.append(" where b.id = a.user_id and a.id = ? ");
            Db.update(sb.toString(), id);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean saveMemberRoleMenus(String roleId, String roleName, String permission) {
        try{
         /*   if(StrKit.isBlank(roleId)){
                Db.update(" insert into crm_platform_employee_role (id, name, status, default_tag, permission) values (?, ?, ?, ?, ?, ?) ",
                        IdGen.uuid(), "0", roleName, "0", 0, permission);
            }else{
             Db.update(" update crm_platform_employee_role set permission = ?, name=? where id = ? ", permission, roleName, roleId);
            }*/
            Db.update(" update crm_platform_employee_role set permission = ?  WHERE  id =? ", permission, roleId);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public Record getExistsLoginName(String employeeId, String loginName){
        Record rd = null;
        if(StrKit.isBlank(employeeId)){//新增的form
            rd = Db.findFirst(" select * from sys_user a where a.login_name = ? and a.status = '0' ", loginName);
        }else{//编辑的form
            Record empRd = Db.findFirst(" select user_id from crm_platform_employee  where id = ? and status = '0' ", employeeId);
            rd = Db.findFirst(" select * from sys_user a where a.login_name = ? and a.status = '0' and a.id !=? ",
                    loginName, empRd.getStr("user_id"));
        }
        return rd;
    }
    public Record getMemberByUserid(String user_Id){
       String sql="SELECT * FROM `crm_platform_employee`WHERE user_id=?";
       Record record=Db.findFirst(sql,user_Id);
       return  record;
    }

    /**
     * 保存服务商修改的员工权限 ***
     */
  public boolean saveSiteMemberRoleMenus(String siteId, Integer role, String permission) {
      Record record=memberRoleDao.getSitMemberRoleMenus(siteId,role);
      try {
          if (record == null) {
              Db.update(" INSERT INTO crm_site_employee_role VALUES(?, ?, ?, '0', ?)", IdGen.uuid(), siteId, role, permission);
          } else {
              Db.update(" UPDATE crm_site_employee_role SET permission=? WHERE site_id=? AND role=?", permission, siteId, role);
          }
      }catch (Exception e){
          e.printStackTrace();
          return false;
      }
      return true;
  }
    /***
     * 获取平台下的所有员工
     */

    public List<Record> getPlatformEmploye(){
        String sql=" SELECT e.id,e.user_id,e.name FROM `crm_platform_employee` e WHERE STATUS='0' ";
        return Db.find(sql);
    }
}
