package cn.palmte.work.model;

import cn.palmte.work.utils.DateKit;
import cn.palmte.work.utils.InterfaceUtil;
import cn.palmte.work.utils.ObjectKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import top.jfunc.common.db.bean.Page;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Repository
public class SysRoleRepositoryImpl implements SysRoleRepositoryCustom {
    private static final Logger logger = LoggerFactory.getLogger(SysRoleRepositoryImpl.class);
    @Autowired
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Page<SysRole> getAllRoleListByPage(ConcurrentHashMap<String, String> searchInfo, String pageNumber, int roleType) {

        Page<SysRole> pager = new Page(Integer.parseInt(pageNumber));
        int pageSize=pager.getPageSize();
        int thisPage = (Integer.parseInt(pageNumber) - 1) * pageSize;
        String sql=getSelect()+getSqlExceptSelect(searchInfo,roleType)+ " limit " + thisPage + "," + pageSize;
        String countSql=" SELECT COUNT(*) FROM("+getSelect()+getSqlExceptSelect(searchInfo,roleType)+") count_table";
        Query nativeQuery= entityManager.createNativeQuery(sql);
        Query  countQuery= entityManager.createNativeQuery(countSql);
        // 总条数
        BigInteger totalRow=new BigInteger("0");
        List<Object[]> list= nativeQuery.getResultList();
        List<SysRole> resultList=new ArrayList();
        if (!list.isEmpty()){
            totalRow=(BigInteger)countQuery.getSingleResult();
            for (Object[] objs:list){
                SysRole role=new SysRole();
                role.setId(ObjectKit.toInt(objs[0]));
                role.setName(ObjectKit.toString(objs[1]));
                role.setType(ObjectKit.toInt(objs[2]));
                role.setLevel(ObjectKit.toInt(objs[3]));
                role.setIsEnable(ObjectKit.toInt(objs[4]));
                role.setDeleted(ObjectKit.toInt(objs[5]));
                role.setCreatedBy(ObjectKit.toInt(objs[6]));
                role.setLastUpdatedBy(ObjectKit.toInt(objs[8]));

                Date createTime = null;
                Date lastUpdateTime = null;
                try {
                    if (objs[7] != null) {
                        createTime = DateKit.getDate(objs[7].toString());
                    }
                    if (objs[9] != null) {
                        lastUpdateTime = DateKit.getDate(objs[9].toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                role.setCreatedTime(createTime);
                role.setLastUpdatedTime(lastUpdateTime);
                resultList.add(role);
            }
        }
        pager.setList(resultList);
        pager.setTotalRow(totalRow.intValue());
        return pager;
    }

    @Override
    public List<SysRole> geBelowRoleTypes(int roleType) {
        ConcurrentHashMap<String, String> searchInfo = new ConcurrentHashMap<>();
        String sql = "select * from sys_role where is_deleted=0 and is_enable=1 and type!=0";
        //获取当前角色等级的下一级角色类型
        Query nativeQuery = null;
        if (roleType > 0) {
            sql = sql + " and type>:roleType ";
            nativeQuery = entityManager.createNativeQuery(sql);
            nativeQuery.setParameter("roleType", roleType);
        } else {
            nativeQuery = entityManager.createNativeQuery(sql);
        }
        List<Object[]> list = nativeQuery.getResultList();
        List<SysRole> resultList = new ArrayList();
        for (Object[] objs : list) {
            SysRole role = new SysRole();
            role.setId(ObjectKit.toInt(objs[0]));
            role.setName(ObjectKit.toString(objs[1]));
            role.setType(ObjectKit.toInt(objs[2]));
            role.setLevel(ObjectKit.toInt(objs[3]));
            role.setIsEnable(ObjectKit.toInt(objs[4]));
            role.setDeleted(ObjectKit.toInt(objs[5]));
            role.setCreatedBy(ObjectKit.toInt(objs[6]));
            role.setLastUpdatedBy(ObjectKit.toInt(objs[8]));
            Date createTime = null;
            Date lastUpdateTime = null;
            try {
                if (objs[7] != null) {
                    createTime = DateKit.getDate(objs[7].toString());
                }
                if(objs[9]!=null){
                    lastUpdateTime = DateKit.getDate(objs[9].toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            role.setCreatedTime(createTime);
            role.setLastUpdatedTime(lastUpdateTime);
            resultList.add(role);
        }
        return resultList;
    }

    @Override
    public List<SysRole> getBelowTypes(int roleType) {
        String sql = "select * from sys_role where is_deleted=0 and is_enable=1 ";
        //获取当前角色等级的下一级角色类型
        Query nativeQuery = null;
        sql = sql + " and type>:roleType";
        nativeQuery = entityManager.createNativeQuery(sql);
        nativeQuery.setParameter("roleType", roleType);

        List<Object[]> list = nativeQuery.getResultList();
        List<SysRole> resultList = new ArrayList();
        for (Object[] objs : list) {
            SysRole role = new SysRole();
            role.setId(ObjectKit.toInt(objs[0]));
            role.setName(ObjectKit.toString(objs[1]));
            role.setType(ObjectKit.toInt(objs[2]));
            role.setLevel(ObjectKit.toInt(objs[3]));
            role.setIsEnable(ObjectKit.toInt(objs[4]));
            role.setDeleted(ObjectKit.toInt(objs[5]));
            role.setCreatedBy(ObjectKit.toInt(objs[6]));
            role.setLastUpdatedBy(ObjectKit.toInt(objs[8]));
            Date createTime = null;
            Date lastUpdateTime = null;
            try {
                if(objs[7]!=null){
                    createTime = DateKit.getDate(objs[7].toString());
                }
                if(objs[9]!=null){
                    lastUpdateTime = DateKit.getDate(objs[9].toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            role.setCreatedTime(createTime);
            role.setLastUpdatedTime(lastUpdateTime);
            resultList.add(role);
        }
        return resultList;
    }


    public String getSelect(){
        String select = "select tsr.*";
        return select;
    }


    public String getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo,int roleType){
        // 判断是否是系统管理员
        String str=roleType==0?">=":">";
        String sqlExceptSelect = "from sys_role tsr where type "+str+" (select type from sys_role, sys_user_role where sys_user_role.role_id = sys_role.id and sys_user_role.user_id="
                + InterfaceUtil.getAdminId() + " AND sys_user_role.is_deleted=0 )  and tsr.is_deleted=0 ";
        StringBuffer sql=new StringBuffer(sqlExceptSelect);
        for(Map.Entry<String, String> item : searchInfo.entrySet()){
            sql.append(buildQuery(item));
        }
        sql.append("order by tsr.created_time desc");

        return sql.toString();
    }



    private String buildQuery(Map.Entry<String, String> item){
        String sql = "";
        if(item.getKey().equals("name")){
            sql += " and tsr.name like '%" + item.getValue() + "%' ";
        }
        return sql;
    }


}
