package cn.ibizlab.humanresource.core.pcm.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.humanresource.core.pcm.domain.HRTransferApply;
import cn.ibizlab.humanresource.core.pcm.filter.HRTransferApplySearchContext;
import cn.ibizlab.humanresource.core.pcm.service.IHRTransferApplyService;

import cn.ibizlab.humanresource.util.helper.CachedBeanCopier;
import cn.ibizlab.humanresource.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.humanresource.core.pcm.mapper.HRTransferApplyMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 实体[调动申请] 服务对象接口实现
 */
@Slf4j
@Service("HRTransferApplyServiceImpl")
public class HRTransferApplyServiceImpl extends ServiceImpl<HRTransferApplyMapper, HRTransferApply> implements IHRTransferApplyService {

    @Autowired
    @Lazy
    protected cn.ibizlab.humanresource.core.humanresource.service.IHREmployeeService hremployeeService;
    @Autowired
    @Lazy
    protected cn.ibizlab.humanresource.core.base.service.IHROrganizationService hrorganizationService;
    @Autowired
    @Lazy
    protected cn.ibizlab.humanresource.core.humanresource.service.IHRPostService hrpostService;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(HRTransferApply et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et)))
            return false;
        CachedBeanCopier.copy(get(et.getHrtransferapplyid()),et);
        return true;
    }

    @Override
    public void createBatch(List<HRTransferApply> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list,batchSize);
    }

    @Override
    @Transactional
    public boolean update(HRTransferApply et) {
        fillParentData(et);
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("hrtransferapplyid",et.getHrtransferapplyid())))
            return false;
        CachedBeanCopier.copy(get(et.getHrtransferapplyid()),et);
        return true;
    }

    @Override
    public void updateBatch(List<HRTransferApply> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        boolean result=removeById(key);
        return result ;
    }

    @Override
    public void removeBatch(Collection<String> idList) {
        removeByIds(idList);
    }

    @Override
    @Transactional
    public HRTransferApply get(String key) {
        HRTransferApply et = getById(key);
        if(et==null){
            et=new HRTransferApply();
            et.setHrtransferapplyid(key);
        }
        else{
        }
        return et;
    }

    @Override
    public HRTransferApply getDraft(HRTransferApply et) {
        fillParentData(et);
        return et;
    }

    @Override
    public boolean checkKey(HRTransferApply et) {
        return (!ObjectUtils.isEmpty(et.getHrtransferapplyid()))&&(!Objects.isNull(this.getById(et.getHrtransferapplyid())));
    }
    @Override
    @Transactional
    public boolean save(HRTransferApply et) {
        if(!saveOrUpdate(et))
            return false;
        return true;
    }

    @Override
    @Transactional
    public boolean saveOrUpdate(HRTransferApply et) {
        if (null == et) {
            return false;
        } else {
            return checkKey(et) ? this.update(et) : this.create(et);
        }
    }

    @Override
    public boolean saveBatch(Collection<HRTransferApply> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
        return true;
    }

    @Override
    public void saveBatch(List<HRTransferApply> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
    }


	@Override
    public List<HRTransferApply> selectByHremployeeid(String employeeid) {
        return baseMapper.selectByHremployeeid(employeeid);
    }

    @Override
    public void removeByHremployeeid(String employeeid) {
        this.remove(new QueryWrapper<HRTransferApply>().eq("hremployeeid",employeeid));
    }

	@Override
    public List<HRTransferApply> selectByHrorganizationid2(String organizationid) {
        return baseMapper.selectByHrorganizationid2(organizationid);
    }

    @Override
    public void removeByHrorganizationid2(String organizationid) {
        this.remove(new QueryWrapper<HRTransferApply>().eq("hrorganizationid2",organizationid));
    }

	@Override
    public List<HRTransferApply> selectByHrpostid2(String hrpostid) {
        return baseMapper.selectByHrpostid2(hrpostid);
    }

    @Override
    public void removeByHrpostid2(String hrpostid) {
        this.remove(new QueryWrapper<HRTransferApply>().eq("hrpostid2",hrpostid));
    }


    /**
     * 查询集合 DEFAULT
     */
    @Override
    public Page<HRTransferApply> searchDefault(HRTransferApplySearchContext context) {
        fillWFTaskContext(context);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<HRTransferApply> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<HRTransferApply>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }


    @Autowired
    private cn.ibizlab.humanresource.util.client.IBZWFFeignClient ibzwfFeignClient;

    /**
     * 查询工作流待办
     * @param context
     */
    private void fillWFTaskContext(HRTransferApplySearchContext context){

        if(!StringUtils.isEmpty(context.getUserTaskId()) && !StringUtils.isEmpty(context.getProcessDefinitionKey())){
            List<String> businessKeys= ibzwfFeignClient.getbusinesskeysByUserId("ibizhumanresources", cn.ibizlab.humanresource.util.security.AuthenticationUser.getAuthenticationUser().getUserid(),"hrtransferapplies",context.getProcessDefinitionKey(),context.getUserTaskId());
            if(businessKeys.size()>0){
                context.getSelectCond().in("hrtransferapplyid",businessKeys);
            }
            else{
                context.getSelectCond().apply("1<>1");
            }
        }
    }

    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(HRTransferApply et){
        //实体关系[DER1N_HRTRANSFERAPPLY_HREMPLOYEE_HREMPLOYEEID_327A4D]
        if(!ObjectUtils.isEmpty(et.getHremployeeid())){
            cn.ibizlab.humanresource.core.humanresource.domain.HREmployee hremployee=et.getHremployee();
            if(ObjectUtils.isEmpty(hremployee)){
                cn.ibizlab.humanresource.core.humanresource.domain.HREmployee majorEntity=hremployeeService.get(et.getHremployeeid());
                et.setHremployee(majorEntity);
                hremployee=majorEntity;
            }
            et.setHremployeename(hremployee.getEmployeename());
            et.setOrganizationid(hremployee.getOrganizationid());
            et.setOrganizationname(hremployee.getOrganizationname());
            et.setHrdutyname(hremployee.getHrdutyname());
            et.setHrpostname(hremployee.getHrpostname());
        }
        //实体关系[DER1N_HRTRANSFERAPPLY_HRORGANIZATION_HRORGANIZATIONID2_6BD9DC]
        if(!ObjectUtils.isEmpty(et.getHrorganizationid2())){
            cn.ibizlab.humanresource.core.base.domain.HROrganization hrorganization2=et.getHrorganization2();
            if(ObjectUtils.isEmpty(hrorganization2)){
                cn.ibizlab.humanresource.core.base.domain.HROrganization majorEntity=hrorganizationService.get(et.getHrorganizationid2());
                et.setHrorganization2(majorEntity);
                hrorganization2=majorEntity;
            }
            et.setHrorganizationname2(hrorganization2.getOrganizationname());
        }
        //实体关系[DER1N_HRTRANSFERAPPLY_HRPOST_HRPOSTID2]
        if(!ObjectUtils.isEmpty(et.getHrpostid2())){
            cn.ibizlab.humanresource.core.humanresource.domain.HRPost hrpost2=et.getHrpost2();
            if(ObjectUtils.isEmpty(hrpost2)){
                cn.ibizlab.humanresource.core.humanresource.domain.HRPost majorEntity=hrpostService.get(et.getHrpostid2());
                et.setHrpost2(majorEntity);
                hrpost2=majorEntity;
            }
            et.setHrpostname2(hrpost2.getHrpostname());
            et.setHrdutyname2(hrpost2.getHrdutyname());
        }
    }




    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith("insert")) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("update")) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("delete")) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    public List<HRTransferApply> getHrtransferapplyByIds(List<String> ids) {
         return this.listByIds(ids);
    }

    @Override
    public List<HRTransferApply> getHrtransferapplyByEntities(List<HRTransferApply> entities) {
        List ids =new ArrayList();
        for(HRTransferApply entity : entities){
            Serializable id=entity.getHrtransferapplyid();
            if(!ObjectUtils.isEmpty(id)){
                ids.add(id);
            }
        }
        if(ids.size()>0)
           return this.listByIds(ids);
        else
           return entities;
    }

}



