package com.sifang.modules.sunshine.SystemSetting.dao;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTraderEmploye;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.util.LayuiPage;
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;
import java.util.Objects;

@Repository
public class TraderEmployeDao extends BaseDao<CrmTraderEmploye> {

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

    public List<Record> getTaderEmployeData(Map<String, String> map, String id, String traderId) {
        StringBuffer sf = new StringBuffer();
        sf.append("SELECT a.*,b.login_name,b.password FROM crm_trader_employe a ");
        sf.append("LEFT JOIN sys_user b ON b.id = a.`user_id` AND b.`status`= '0' AND b.`user_type` = '7' ");
        sf.append(" where a.trader_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() + "%' ");
            }
            if (map.containsKey("roleId") && StrKit.notBlank(map.get("roleId"))) {
                sf.append(" and a.role_id = '" + map.get("roleId").trim() + "' ");
            }
        }
        sf.append(" and a.status = '0' ");
        return Db.find(sf.toString(), traderId);

    }

    public List<Record> findPageData(LayuiPage page ,Map<String,String> map ,String traderId){
        SqlBuilder sql = new SqlBuilder();
        sql.line(" SELECT a.*,b.login_name,b.password FROM crm_trader_employe a  ")
                .line(" LEFT JOIN sys_user b ON b.id = a.`user_id` AND b.`status`= '0' AND b.`user_type` = '7'   ")
                .line(" where a.trader_id =? ",traderId);
        if (map != null) {
            if (map.containsKey("name") && StrKit.notBlank(map.get("name"))) {
                sql.like("  and a.name like  ? ", map.get("name").trim() );
            }
            if (map.containsKey("mobile") && StrKit.notBlank(map.get("mobile"))) {
                sql.like("  and a.mobile like  ? ", map.get("mobile").trim() );
            }
            if (map.containsKey("roleId") && StrKit.notBlank(map.get("roleId"))) {
                sql.line(" and a.role_id = ? ", map.get("roleId").trim() );
            }
        }
        sql.line(" and a.status = '0' ");
        if (StrKit.notNull(page)) {
            sql.limit(page.getPage(), page.getLimit());
        }
        return Db.find(sql.build(), sql.params());
    }

    public long findPageCount(Map<String, String> map, String traderId) {
        SqlBuilder sql = new SqlBuilder();
        sql.line(" SELECT  COUNT(1)   FROM crm_trader_employe a  ")
                .line(" LEFT JOIN sys_user b ON b.id = a.`user_id` AND b.`status`= '0' AND b.`user_type` = '7'   ")
                .line(" where a.trader_id =? ",traderId);
        if (map != null) {
            if (map.containsKey("name") && StrKit.notBlank(map.get("name"))) {
                sql.like("  and a.name like  ? ", map.get("name").trim() );
            }
            if (map.containsKey("mobile") && StrKit.notBlank(map.get("mobile"))) {
                sql.like("  and a.mobile like  ? ", map.get("mobile").trim() );
            }
            if (map.containsKey("roleId") && StrKit.notBlank(map.get("roleId"))) {
                sql.line(" and a.role_id = ? ", map.get("roleId").trim() );
            }
        }
        sql.line(" and a.status = '0' ");
        return Db.queryLong(sql.build(), sql.params());
    }


    public List<Record> getEmpByName(String name,String siteId) {
        StringBuilder sb = new StringBuilder("");
        sb.append("select id,name from crm_trader_employe where status='0' and name =? and trader_id=?");
        List<Record> list = Db.find(sb.toString(), name,siteId);
        return list;
    }

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

        return rd!=null;
    }

    /**
     * 修改员工保存之前进行校验登录账号是否已经存在
     */
    public boolean getExistsLoginNameNew(String userId, String loginName) {
        Record rd =  Db.findFirst(" select * from sys_user a where a.login_name = ? and a.status = '0' and a.id !=? ",
                    loginName, userId);

        return rd!= null;
    }


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

    /**
     * 删除员工信息
     *
     * @return
     */
    public boolean delEmployee(String id) {
        try {
            StringBuilder sb = new StringBuilder("");
            sb.append(" update crm_trader_employe 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 String getTraderId(String userId) {
        StringBuffer sf = new StringBuffer();
        sf.append("select s.id from crm_trader s where s.status ='0' and s.user_id = ? ");
        return Db.queryStr(sf.toString(), userId);
    }


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

    public CrmTraderEmploye findByUserId(String userId) {
        return getByHql(" from CrmTraderEmploye where userId =:p1", new Parameter(userId));
    }

    public String getTraderEmpPermission(String userId){
        return Db.queryStr("SELECT p.permission FROM `crm_platform_employee_role` p WHERE p.id=(SELECT e.role_id FROM `crm_trader_employe` e WHERE e.user_id=? ) ",userId);
    }

    /**
     * 查询二级代理商所属员工
     */
    public List<String> findSecondTraderEmp(String traderId) {
        return Db.query("SELECT user_id FROM crm_trader_employe WHERE trader_id = ? AND status = '0'", traderId);
    }

    /**
     * 查询角色下是否有员工
     */
    public boolean checkIfHasRole(String roleId, String traderId) {
        //首先查出该角色下有没有员工
        StringBuffer sf = new StringBuffer();
        sf.append(" SELECT COUNT(r.id) FROM `crm_trader_employe` r  ");
        sf.append(" WHERE r.trader_id = ? AND r.role_id LIKE");
        sf.append(" CONCAT('%',?,'%') AND r.status = '0' ");
        Long count = Db.queryLong(sf.toString(), traderId, roleId);
        if (count > 0) {
            return false; //该角色下有员工
        } else {
            return true;
        }
    }
}
