package com.sys.bus.jx.service;

import com.jfinal.aop.Enhancer;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.sys.bus.model.Org;
import com.sys.bus.model.OrgPerson;
import com.sys.bus.model.SysCode;
import com.sys.bus.sys.model.DtBean;
import com.sys.bus.syscode.service.SysCodeService;
import com.sys.core.model.PageBean;
import com.sys.core.utils.Conditions;
import com.sys.core.utils.Tool;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class OrgService {
    static SysCodeService codeService = Enhancer.enhance(SysCodeService.class);
    public int disableOrg(String orgId){
        Org org = Org.dao.findById(orgId);
        org.setOrgStatus("2");
        org.update();
        return 0;
    }
    public int enableOrg(String orgId){
        Org org = Org.dao.findById(orgId);
        org.setOrgStatus("1");
        org.update();
        return 0;
    }
    public List<String> getAllOrgType(){
        SysCode sysCode = codeService.getSysCodeName("组织类型");
        String orgType = "集团,工控,地产";
        if(sysCode!=null && StringUtils.isNotBlank(sysCode.getSyscodeValue())){
            orgType = sysCode.getSyscodeValue().trim().replace("，",",");
        }
        List<String> list = new ArrayList<>();
        for (String s : orgType.split(",")) {
            if(StringUtils.isBlank(s))continue;
            list.add(s.trim());
        }

        return list;
    }

    /**
     * 删除考核组织
     * @param orgId
     * @return 0成功   1被考核引用 2被授权引用
     */
    public int deleteOrg(String orgId){
        Org org = Org.dao.findById(orgId);
        String sql = "select count(*) count from ct_jx_entry where entry_orgid=? ";
        List<Org> orgs = Org.dao.find(sql, orgId);
        int count = orgs.get(0).get("count");
        if(count>0){
            return 1;
        }
        sql = "select count(*) count from ct_jx_orgperson where orgperson_orgid=?";
        orgs = Org.dao.find(sql, orgId);
        count = orgs.get(0).get("count");
        if(count>0){
            return 2;
        }
        org.delete();
        return 0;
    }
    public int deleteOrgPerson(String orgPersonId){
        OrgPerson orgPerson = OrgPerson.dao.findById(orgPersonId);

        return orgPerson.delete()?0:1;
    }

    /**
     * 保存考核组织
     * @param orgId
     * @param creatorId
     * @return 0成功   1重复组织
     */
    public int saveOrg(String orgId,String orgType,String orgName,boolean update,String creatorId){
        Org org = Org.dao.findById(orgId);
        if(!update && org !=null) return 1;
        if(org==null){
            org = new Org();
        }
        org.setOrgId(orgId);
        org.setOrgType(orgType);
        org.setOrgName(orgName);
        org.setOrgStatus("1");
        org.setOrgCreatetime(Tool.getCurrTime());
        org.setOrgCreatorid(creatorId);
        if(update){
            org.update();
        }else{
            org.save();
        }

        return 0;


    }

    /**
     * 保存考核组织授权
     * @param orgId
     * @param pid
     * @param creatorId
     * @return 0成功   1重复
     */
    public int saveOrgPerson(String orgId,String pid,String creatorId){
        OrgPerson op = new OrgPerson();
        op.setOrgpersonOrgid(orgId);
        op.setOrgpersonPid(pid);
        List<OrgPerson> list = OrgPerson.dao.find(this.getOrgPersonSqlPara(op));
        if(list!=null &&list.size()>0){
            return 1;
        }
        op.setOrgpersonId(Tool.uuid());
        op.setOrgpersonCreatorid(creatorId);
        op.setOrgpersonCreatetime(Tool.getCurrTime());
        op.save();
        return 0;
    }
    public int changePermission(String newPersonId,String pid,String creatorId){
        OrgPerson op = new OrgPerson();
        op.setOrgpersonPid(pid);
        List<OrgPerson> list = OrgPerson.dao.find(this.getOrgPersonSqlPara(op));
        if(list==null || list.size()==0){
            throw new RuntimeException("原员工没有权限，无法转移！");
        }
        for(OrgPerson orgPerson : list){

            OrgPerson op1 = new OrgPerson();
            op1.setOrgpersonOrgid(orgPerson.getOrgpersonOrgid());
            op1.setOrgpersonPid(newPersonId);
            List<OrgPerson> list1 = OrgPerson.dao.find(this.getOrgPersonSqlPara(op1));
            if(list1!=null &&list1.size()>0){//是否已经有要操作的权限
                orgPerson.delete();
                continue;
            }
            orgPerson.setOrgpersonPid(newPersonId);
            orgPerson.setOrgpersonCreatorid(creatorId);
            orgPerson.setOrgpersonCreatetime(Tool.getCurrTime());
            orgPerson.update();
        }
        return 0;
    }
    public int copyPermission(String newPersonId,String pid,String creatorId){
        OrgPerson op = new OrgPerson();
        op.setOrgpersonPid(pid);
        List<OrgPerson> list = OrgPerson.dao.find(this.getOrgPersonSqlPara(op));
        if(list==null || list.size()==0){
            throw new RuntimeException("原员工没有权限，无法复制！");
        }
        for(OrgPerson orgPerson : list){
            OrgPerson op1 = new OrgPerson();
            op1.setOrgpersonOrgid(orgPerson.getOrgpersonOrgid());
            op1.setOrgpersonPid(newPersonId);
            List<OrgPerson> list1 = OrgPerson.dao.find(this.getOrgPersonSqlPara(op1));
            if(list1!=null &&list1.size()>0){//是否已经有要操作的权限
                continue;
            }
            orgPerson.setOrgpersonId(Tool.uuid());
            orgPerson.setOrgpersonPid(newPersonId);
            orgPerson.setOrgpersonCreatorid(creatorId);
            orgPerson.setOrgpersonCreatetime(Tool.getCurrTime());
            orgPerson.save();
        }
        return 0;
    }
    public int clearPermission(String pid,String creatorId){
        OrgPerson op = new OrgPerson();
        op.setOrgpersonPid(pid);
        List<OrgPerson> list = OrgPerson.dao.find(this.getOrgPersonSqlPara(op));
        if(list==null || list.size()==0){
            throw new RuntimeException("原员工没有权限，无法批量删除！");
        }
        for(OrgPerson orgPerson : list){
            orgPerson.delete();
        }
        return 0;
    }
    /**
     * 获取所有的组织授权
     */
    public List<OrgPerson> getOrgPersonList(){
        String sql = " select p.fname_l2 pname,p.fid pid,p.fname_l2||'_'||p.fnumber plname,a.fname_l2,a.fdisplayname_l2,op.*,o.*  from ct_jx_orgPerson op " +
                " left join t_bd_person p on p.fid=op.orgperson_pid "+
                " left join ct_jx_org o on o.org_id=op.orgperson_orgid "+
                " left join t_org_admin a on o.org_id  = a.fid  " +
                "   order by op.orgperson_pid,org_status,a.flevel,orgperson_Createtime  ";
        List<OrgPerson> list = OrgPerson.dao.find(sql);
        return list;
    }
    /**
     * 获取所有的组织授权
     */
    public List<OrgPerson> getOrgPersonList(String orgId,String pId){
        String sql = " select p.fname_l2 pname,a.fname_l2,a.fdisplayname_l2,op.*,o.*  from ct_jx_orgPerson op " +
                " left join t_bd_person p on p.fid=op.orgperson_pid "+
                " left join ct_jx_org o on o.org_id=op.orgperson_orgid "+
                " left join t_org_admin a on o.org_id  = a.fid  where 1=1 " +
                (StringUtils.isNotBlank(orgId)?" and op.orgperson_orgid ='"+orgId+"'":"") +
                (StringUtils.isNotBlank(pId)?" and (op.orgperson_pid ='"+pId+"' or p.fname_l2='"+pId+"' )":"") +
                "   order by op.orgperson_pid,org_status,a.flevel,orgperson_Createtime  ";
        List<OrgPerson> list = OrgPerson.dao.find(sql);
        return list;
    }
    public PageBean getOrgPersonList(String orgId,String pId,Integer pageNumber, Integer pageSize){

        String sqlCount  =
                        " select count(1)  from ct_jx_orgPerson op " +
                        " left join t_bd_person p on p.fid=op.orgperson_pid "+
                        "  where 1=1 " +
                        (StringUtils.isNotBlank(orgId)?" and op.orgperson_orgid ='"+orgId+"'":"") +
                        (StringUtils.isNotBlank(pId)?" and (op.orgperson_pid ='"+pId+"' or p.fname_l2='"+pId+"' )":"") ;


        String sqlPara  =
                " select p.fname_l2 pname,a.fname_l2,a.fdisplayname_l2,op.*,o.*  from ct_jx_orgPerson op " +
                        " left join t_bd_person p on p.fid=op.orgperson_pid "+
                        " left join ct_jx_org o on o.org_id=op.orgperson_orgid "+
                        " left join t_org_admin a on o.org_id  = a.fid  where 1=1 " +
                        (StringUtils.isNotBlank(orgId)?" and op.orgperson_orgid ='"+orgId+"'":"") +
                        (StringUtils.isNotBlank(pId)?" and (op.orgperson_pid ='"+pId+"' or p.fname_l2='"+pId+"' )":"") +
                        "   order by op.orgperson_pid,org_status,a.flevel,orgperson_Createtime  ";

        PageBean pageBean = new PageBean();
        Page<DtBean> page = new DtBean().dao().paginateByFullSql(pageNumber, pageSize, sqlCount, sqlPara);
        pageBean.setCount(page.getTotalRow());
        pageBean.setData(page.getList());
        return pageBean;
    }

    public PageBean getUpdateRatingPermissionList(String cycleId,Integer pageNumber, Integer pageSize){

        String sqlCount  =
                " select  count(1) \n" +
                        "from CT_JX_updateRatingPermission urp \n" +
                        "left join ct_jx_cycle  cycle\n" +
                        "on cycle.cycle_id = urp.cycle_id\n" +
                        "left join t_org_admin org \n" +
                        "on org.FID = urp.org_id\n" +
                        "where 1=1" +
                        (StringUtils.isNotBlank(cycleId)?" and cycle.CYCLE_ID ='"+cycleId+"'":"") ;

        String sqlPara  =
                " select \n" +
                        "urp.PERMISSION_ID as permissionId,\n" +
                        "cycle.cycle_name as cycleName,\n" +
                        "org.FDisplayName_l2 as orgName," +
                        "urp.IS_SUBORDINATE as isSubordinate,\n" +
                        "urp.IS_ENABLE as enable\n" +
                        "from CT_JX_updateRatingPermission urp \n" +
                        "left join ct_jx_cycle  cycle\n" +
                        "on cycle.cycle_id = urp.cycle_id\n" +
                        "left join t_org_admin org \n" +
                        "on org.FID = urp.org_id\n" +
                        "where 1=1 " +
                        (StringUtils.isNotBlank(cycleId)?" and cycle.CYCLE_ID ='"+cycleId+"'":"") +
                        " ORDER BY cycle.CYCLE_TYPE desc,cycle.cycle_year desc,cycle.cycle_yearType desc,cycle.cycle_quarter desc ,cycle.CYCLE_MONTH desc ";

        PageBean pageBean = new PageBean();
        Page<DtBean> page = new DtBean().dao().paginateByFullSql(pageNumber, pageSize, sqlCount, sqlPara);
        pageBean.setCount(page.getTotalRow());
        pageBean.setData(page.getList());
        return pageBean;
    }


    /**
     * 获取员工所有的组织授权
     * @param pid
     */
    public List<Org> getOrgList(String pid){
        String sql = " select a.fname_l2,a.fdisplayname_l2,o.*  from ct_jx_orgPerson op " +
                " left join t_bd_person p on p.fid=op.orgperson_pid "+
                " left join ct_jx_org o on o.org_id=op.orgperson_orgid "+
                " left join t_org_admin a on o.org_id  = a.fid where  op.orgperson_pid=? " +
                "   order by org_status,a.flevel,orgperson_Createtime  ";
        List<Org> list = Org.dao.find(sql,pid);
        return list;
    }
    /**
     * 获取员工有效组织的组织授权
     * @param pid
     */
    public List<Org> getEnableOrgList(String pid){
        String admin = codeService.getSysCodeName("绩效管理员").getSyscodeValue();
        if(admin.equals(pid)){
            String sql = " select  o.*,a.fname_l2,a.fdisplayname_l2 from ct_jx_org o " +
                    " left join t_org_admin a on o.org_id  = a.fid  " +
                    "   order by org_status,org_Createtime  ";
            return Org.dao.find(sql);
        }
        String sql = " select a.fname_l2,a.fdisplayname_l2,o.*  from ct_jx_orgPerson op " +
                " left join t_bd_person p on p.fid=op.orgperson_pid "+
                " left join ct_jx_org o on o.org_id=op.orgperson_orgid "+
                " left join t_org_admin a on o.org_id  = a.fid where  op.orgperson_pid=? and o.org_status=1" +
                "   order by org_status,a.flevel,orgperson_Createtime  ";
        List<Org> list = Org.dao.find(sql,pid);
        return list;
    }
    /**
     * 获取所有的组织 包括禁用的考核组织
     */
    public List<Org> getOrgList(){
        String sql = " select  o.*,a.fname_l2,a.fdisplayname_l2 from ct_jx_org o " +
                " left join t_org_admin a on o.org_id  = a.fid  " +
                "   order by org_status,org_Createtime desc ";
        List<Org> list = Org.dao.find(sql);
        return list;
    }
    public Org getOrgById(String orgId){
        String sql = " select  o.*,a.fname_l2,a.fdisplayname_l2 from ct_jx_org o " +
                " left join t_org_admin a on o.org_id  = a.fid  " +
                "  where o.org_id=?";
        List<Org> list = Org.dao.find(sql,orgId);
        return list.get(0);
    }
//    /**
//     * 获取所有的有效考核组织
//     */
//    public List<Org> getEnableOrgList(){
//        String sql = " select  o.*,a.fname_l2,a.fdisplayname_l2 from ct_jx_org o " +
//                " left join t_org_admin a on o.org_id = a.fid  " +
//                " where o.org_status='1'  order by flevel  ";
//        List<Org> list = Org.dao.find(sql);
//        return list;
//    }
    /**
     * SqlPara
     *
     * @param org
     * @return
     */
    public SqlPara getSqlPara(Org org) {
        Conditions condi = new Conditions();
        condi.modelToCondition(org);
        SqlPara sp = condi.getSqlPara();
        sp.setSql(sp.getSql());
        return sp;
    }
    /**
     * SqlPara
     *
     * @param orgPerson
     * @return
     */
    public SqlPara getOrgPersonSqlPara(OrgPerson orgPerson) {
        Conditions condi = new Conditions();
        condi.modelToCondition(orgPerson);
        SqlPara sp = condi.getSqlPara();
        sp.setSql(sp.getSql());
        return sp;
    }
}
