package com.sifang.modules.site.siteInfo.dao;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.sys.util.SqlBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

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

@Repository
public class SiteEmployeeDao {

    /**
     * 获取服务商员工设置列表数据
     *
     * @return
     */
    public List<Record> getSiteEmployeeData(Map<String, String> params, String siteId) {
        return getSiteEmployeeDatas(params, "", siteId);
    }

    public List<Record> getSiteEmployeeDatas(Map<String, String> map, String id, String siteId) {
        StringBuffer sf = new StringBuffer();
        sf.append("SELECT a.*,b.login_name,b.password FROM crm_site_employee a ");
        sf.append("LEFT JOIN sys_user b ON b.id = a.`user_id` AND b.`status`= '0' AND b.`user_type` = '5' ");
        sf.append(" where a.site_id =? ");
        if (StrKit.notBlank(id)) {
            sf.append(" and a.id = '" + id + "' ");
        }
        if (map != null) {
            if (map.containsKey("name") && StrKit.notBlank(map.get("name"))) {
                sf.append(" and a.name like '%" + map.get("name").trim() + "%' ");
            }
            if (map.containsKey("mobile") && StrKit.notBlank(map.get("mobile"))) {
                sf.append(" and a.mobile like '%" + map.get("mobile").trim() + "%' ");
            }
        }
        sf.append(" and a.status = '0' and a.role = '2'");
        return Db.find(sf.toString(), siteId);

    }

    /**
     * 新增员工之前进行校验登录账号是否已经存在
     */
    public Record getExistsLoginName(String id, String loginName, String mobile) {
        Record rd = null;
        if (StrKit.isBlank(id)) {//新增的form
            rd = Db.findFirst(" select * from sys_user a where (a.login_name = ? or mobile=?) and a.status = '0' ", loginName, mobile);
        }
        return rd;
    }

    /**
     * 修改员工保存之前进行校验登录账号是否已经存在
     */
    public Record getExistsLoginNameNew(String id, String loginName) {
        Record rd = null;
        if (StringUtils.isNotBlank(id)) {//新增的form
            Record empRd = Db.findFirst(" select user_id from crm_site_employee  where id = ? and status = '0' ", id);
            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;
    }


    /**
     * 修改保存
     *
     * @param params
     * @return
     */
    public String updateEmployee(Map<String, String> params) {
        try {
            String updateEmployeeId = params.get("id");
            String loginName = params.get("loginName");

            Record rd = getExistsLoginNameNew(updateEmployeeId, loginName);
            if (rd != null && StrKit.notBlank(rd.getStr("id"))) {
                //登录名已存在
                return "existsLoginName";
            }

            String role = "2";
            String name = params.get("name");
            String mobile = params.get("mobile");
            String imgs = params.get("imgs");
            String years = params.get("years");

            StringBuilder sb = new StringBuilder("");
            sb.append(" update crm_site_employee a , sys_user b ");
            sb.append(" set a.name = ? ,a.role = ? , b.login_name = ?, a.mobile = ?, b.mobile = ? ,a.years = ?,a.license_img = ? ");
            sb.append(" where b.id = a.user_id and a.id = ? ");
            sb.append("  ");
            Db.update(sb.toString(), name, role, loginName, mobile, mobile, years, imgs, updateEmployeeId);
        } catch (Exception e) {
            e.printStackTrace();
            return "err";
        }
        return "ok";
    }


    /**
     * 查询修改员工信息页面数据
     *
     * @return
     */
    public Record getSiteEmployeeById(String id, String siteId) {
        List<Record> rds = getSiteEmployeeDatas(null, id, siteId);
        return rds == null ? null : rds.get(0);
    }

    /**
     * 删除员工信息
     *
     * @return
     */
    public boolean delEmployee(String id) {
        try {
            StringBuilder sb = new StringBuilder("");
            sb.append(" update crm_site_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;
    }

    /**
     * 获取当前服务商id
     *
     * @param userId
     * @return
     */
    public String getSiteId(String userId) {
        StringBuffer sf = new StringBuffer();
        sf.append("select s.id from crm_site s where s.status in('0','4') and s.user_id = ? ");
        return Db.queryStr(sf.toString(), userId);
    }


    public Record getSiteByUserId(String userId) {
        StringBuffer sf = new StringBuffer();
        sf.append("select * from crm_site s where s.status in('0','4') and s.user_id = ? ");
        return Db.findFirst(sf.toString(), userId);
    }

    /***
     * 获取服务商人员的角色
     */
    public Record getRole(String userId) {
        StringBuffer sf = new StringBuffer();
        sf.append("SELECT * FROM `crm_site_employee` WHERE user_id= ? ");
        return Db.findFirst(sf.toString(), userId);
    }

    /**
     * 判断是不是服务商人员中的工程师角色 ***
     */
    public Boolean isEngineer(String userId) {
        Record record = getRole(userId);
        Integer role = record.getInt("role");
        if (2 == role) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断服务商人员有没有经过平台授权  ***
     */
    public Boolean isAuthorize(String userId) {
        String sql = "SELECT STATUS FROM `crm_site` WHERE user_id= ?";
        String status = Db.queryStr(sql, userId);
        if (SourceConstants.TWO.equals(status)) {
            return false;
        } else {
            return true;
        }
    }

    public String getEmpName(String userId) {
        String sql = "select name from crm_platform_employee where status='0' and user_id =?";
        Record record = Db.findFirst(sql, userId);
        if (record != null) {
            return record.getStr("name");
        } else {
            return null;
        }
    }

    public List<Record> findRolesByUserId(String userId){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select er.* ")
                .line("from crm_platform_employee_role er")
                .line("where exists (select 1 from crm_platform_employee e")
                .line("inner join crm_platform_employee_role_rel r on e.id=r.employee_id")
                .line("where e.user_id=? and find_in_set(er.id, r.role_ids))", userId);
        return Db.find(builder.build(), builder.params());
    }

    /**
     * 查找项目工程师列表
     */
    public List<Record> findProjectEmpList(String type){
        SqlBuilder builder = new SqlBuilder();
        builder.line("select e.* ")
                .line("from crm_platform_employee e")
                .line("left join crm_platform_employee_role_rel r on e.id=r.employee_id")
                .line("where e.status='0' and exists (select 1 from")
                .line("crm_platform_employee_role er where find_in_set(er.id, r.role_ids)").inst("and er.type in ",type.split(","))
                .line(")")
                .line("order by e.create_time desc");
        return Db.find(builder.build());
    }

    public List<Record> findEmployeeByUserIds(String userId) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("select e.* ")
                .line("from crm_platform_employee e")
                .line("where e.status='0' and e.user_id=?", userId);
        return Db.find(builder.build(), userId);
    }

}
