package cn.palmte.work.model;


import cn.palmte.work.utils.DateKit;
import cn.palmte.work.utils.ObjectKit;
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 SysPermissionRepositoryImpl implements SysPermissionRepositoryCustom {
    @Autowired
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Page<SysPermission> getAllPermissionListByPage(ConcurrentHashMap<String, String> searchInfo, String pageNumber) {

        Page<SysPermission> pager = new Page(Integer.parseInt(pageNumber));
        int pageSize=pager.getPageSize();
        int thisPage = (Integer.parseInt(pageNumber) - 1) * pageSize;
        String sql=getSelect()+getSqlExceptSelect(searchInfo)+ " limit " + thisPage + "," + pageSize;
        String countSql=" SELECT COUNT(*) FROM("+getSelect()+getSqlExceptSelect(searchInfo)+") count_table";
        Query  nativeQuery= entityManager.createNativeQuery(sql);
        Query  countQuery= entityManager.createNativeQuery(countSql);
        BigInteger totalRow=new BigInteger("0");
        List<Object[]> list= nativeQuery.getResultList();
        List<SysPermission> resultList=new ArrayList();
        if (null!=list&&list.size()>0){
            // 总条数
            totalRow=(BigInteger)countQuery.getSingleResult();
            for (Object[] objs:list){
                SysPermission permission=new SysPermission();
                permission.setId(ObjectKit.toInt(objs[0]));
                permission.setName(ObjectKit.toString(objs[1]));
                permission.setUrl(ObjectKit.toString(objs[3]));
                permission.setPermission(ObjectKit.toString(objs[4]));
                permission.setParentId(ObjectKit.toInt(objs[5]));
                permission.setLevel(ObjectKit.toInt(objs[6]));
                permission.setType(ObjectKit.toInt(objs[7]));
                permission.setSort(ObjectKit.toInt(objs[8]));
                permission.setRemark(ObjectKit.toString(objs[9]));
                if(objs[10]!=null){
                    if((Boolean) objs[10]){
                        permission.setIsDeleted(1);
                    }else {
                        permission.setIsDeleted(0);
                    }
                }

                Date createTime = null;
                Date lastUpdateTime = null;
                try {
                    if(objs[12]!=null){
                        createTime = DateKit.getDate(objs[12].toString());
                    }
                    if(objs[14]!=null){
                        lastUpdateTime = DateKit.getDate(objs[14].toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                permission.setCreatedTime(createTime);
                permission.setCreator(ObjectKit.toString(objs[15]));
                permission.setUpdator(ObjectKit.toString(objs[16]));
                permission.setLastUpdatedTime(lastUpdateTime);
                resultList.add(permission);
            }
        }

        pager.setList(resultList);
        pager.setTotalRow(totalRow.intValue());
        return pager;
    }




    public String getSelect(){
        String select = " select p.*, (select user_name from sys_user u where p.created_by = u.id) as creator, "
                + " (select user_name from sys_user u where p.last_updated_by = u.id) as updator ";
        return select;
    }


    public String getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
//        StringBuffer sqlExceptSelect=new StringBuffer(" from sys_permission p where 1=1 and is_deleted= 0 ");
        StringBuffer sqlExceptSelect=new StringBuffer(" from sys_permission p where 1=1 and p.is_deleted = 0 ");
        for(Map.Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect.append(buildQuery(item));
        }
        sqlExceptSelect.append( " order by p.created_time desc");

        return sqlExceptSelect.toString();
    }



    private String buildQuery(Map.Entry<String, String> item){
        StringBuffer sql= new StringBuffer("");
        if(item.getKey().equals("pmsName")){
            sql.append( " and p.name like '%" + item.getValue() + "%' ");
        } else if(item.getKey().equals("pmsParentID")){
            sql.append( " and p.parent_id = " + item.getValue());
        } else if(item.getKey().equals("pmsLevel") && !"0".equals(item.getValue())){
            sql.append( " and p.level = " + item.getValue());
        } else if(item.getKey().equals("pmsType") && !"0".equals(item.getValue())){
            sql.append( " and p.type = " + item.getValue());
        } else if(item.getKey().equals("pmsID")){
            sql.append( " and p.id = " + item.getValue());
        } else if(item.getKey().equals("pmsUrl")){
            sql.append( " and p.url = '" + item.getValue() + "' ");
        } else if(item.getKey().equals("pmsDeleted") && !"-1".equals(item.getValue())){
            sql.append( " and p.is_deleted = " + item.getValue() + " ");
        }else if(item.getKey().equals("pmsCode")){
            sql.append( " and p.permission = '" + item.getValue() + "' ");
        }

        return sql.toString();
    }

}
