package com.fufan.mtsaas.modules.sysmgr.sydept.service.impl;

import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fufan.mtsaas.modules.base.log.service.TSysLogSvc;
import com.fufan.mtsaas.modules.common.bo.request.DeleteRequest;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.sydept.dao.SYDeptDao;
import com.fufan.mtsaas.modules.sysmgr.sydept.model.SYDepVer;
import com.fufan.mtsaas.modules.sysmgr.sydept.model.SYDept;
import com.fufan.mtsaas.modules.sysmgr.sydept.service.SYDeptSvc;
import com.github.pagehelper.ISelect;
import com.fufan.mtsaas.modules.sysmgr.sydept.bo.request.DeptQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.sydept.bo.request.DeptSaveRequest;
import com.fufan.mtsaas.modules.sysmgr.sydept.dao.SYDepVerDao;
import com.fufan.mtsaas.modules.sysmgr.sydept.dao.SYDeptDao;
import com.fufan.mtsaas.modules.sysmgr.sydept.model.SYDepVer;
import com.fufan.mtsaas.modules.sysmgr.sydept.model.SYDept;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.sydept.bo.response.SYDeptPojo;
import com.fufan.mtsaas.modules.sysmgr.sydept.service.SYDeptSvc;
import com.fufan.mtsaas.util.DateFormatTool;
import com.fufan.mtsaas.util.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Liby
 * @since 2019-08-19
 */
@Service("SYDeptSvcImpl")
@Slf4j
@Primary
public class SYDeptSvcImpl extends ServiceImpl<SYDeptDao, SYDept> implements SYDeptSvc {
    @Autowired
    private SYDeptDao entitymDao;

    @Autowired
    private SYDepVerDao entitymverDao;

    @Autowired
    private TSysLogSvc tSysLogSvc;

    @Value("${DEFAULT_TOP_DEPCODE}")
    private String DEFAULT_TOP_DEPCODE;

    @Value("${COMPANY_CD}")
    private String COMPANY_CD;

    /**
     * 查询
     *
     * @param map
     * @return Result.class
     * */
    @Override
    public Result doQueryPage(DeptQueryRequest map) {
        Result result = new Result();
        //分页查询
        Page page = new Page();
        log.debug("SYDeptSvcImpl.doQueryPage parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();
        String CompanyID = map.getCompanyID();
        String VerNo = map.getVerNo();
        String SubID = map.getSubID();
        String DepName = map.getDepName();

        //2020-03-29设置默认值
        if(Objects.isNull(CompanyID) || StringUtils.isEmpty(CompanyID)){
            CompanyID = COMPANY_CD;
        }
        //VerNo为空时获取最近有效的版本
        if(Objects.isNull(VerNo) || StringUtils.isEmpty(VerNo)){
            Map<String, String> mapData1 = new HashMap<>();
            mapData1.put("CompanyID", CompanyID);
            List<SYDepVer> entitys = entitymverDao.selectList(page, mapData1);
            if(Objects.nonNull(entitys) && entitys.size() > 0){
                VerNo = entitys.get(0).getVerNo();
                log.debug("SYDeptSvcImpl 获取最新版本 VerNo: {}", VerNo);
            }
        }

        mapData.put("CompanyID", CompanyID);
        mapData.put("VerNo", VerNo);
        mapData.put("SubID", SubID);
        mapData.put("DepName", DepName);
        mapData.put("Division", map.getDivision());
        if (Objects.nonNull(map.getId()) && map.getId() != 0) {
            mapData.put("id", String.valueOf(map.getId()));
        }
        List<SYDept> entitys;

        //分页处理 -- 20192021 Liby
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                entitymDao.selectList(page, mapData);
            }
        });
        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        entitys = entitymDao.selectList(page, mapData);

        log.debug("SYDeptSvcImpl.doQueryPage entitys: {}", entitys);

        page.setTotal((int) total);
        page.setRecords(entitys);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    /**
     * 新增
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doSave(SYDept entitym, RequestPojo requestPojo) {
        log.debug("SYDeptSvcImpl.doSave parameter: {}", entitym);
        Result result = new Result();
        entitym.setCompanyID(requestPojo.getCustId());
        //非空验证
        if (StringUtils.isEmpty(entitym.getCompanyID()) || StringUtils.isEmpty(entitym.getParID()) || StringUtils.isEmpty(entitym.getVerNo())) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        //名称重复验证
        HashMap mapData = new HashMap();
        Page page = new Page();
        mapData.put("CompanyID", entitym.getCompanyID());
        mapData.put("DepName", entitym.getDepName());

        List<SYDept> entity = entitymDao.selectListbyPK(page, mapData);
        if(entity != null && entity.size() > 0){
            result.setResStatus(ResStatus.STATUS_EXISTENCE);
            result.setResMsg("部门名称" + entitym.getDepName() + ResStatus.STATUS_EXISTENCE_MSG);
            return result;
        }

        entitym.setVldFG("0");
        entitym.setRegisteredPerson(requestPojo.getUserName());
        entitym.setRegisteredDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        entitym.setUpdatedPerson(requestPojo.getUserName());
        entitym.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        //设置默认的父ID，如果部门区分级别为空或者级别为0 - 公司
        if (Objects.isNull(entitym.getParID()) && (null == entitym.getDepType() || entitym.getDepType().equals("0"))) {
            entitym.setParID("VJ");
        }

        try{

            int rec = entitymDao.insertRecords(entitym);
            log.debug("新增数据返回 {}",rec);

            tSysLogSvc.saveLogInfo(Long.valueOf(entitym.getId()), "department", "新增部门", "部门名称:" + entitym.getDepName(), "新增", "成功", requestPojo);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

            result.setResData(page.setRecords(Arrays.asList(entitym)));
        }catch (Exception e){
            tSysLogSvc.saveLogInfo(Long.valueOf(entitym.getId()), "department", "新增部门", "部门名称:" + entitym.getDepName(), "新增", "成功", requestPojo);

            log.error("新增数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }
        return result;

    }

    /**
     * 修改
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doUpdate(SYDept entitym, RequestPojo requestPojo) {
        log.debug("SYDeptSvcImpl.doUpdate parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if (Objects.isNull(entitym.getId())) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg("id" + ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        entitym.setUpdatedPerson(requestPojo.getUserName());
        entitym.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        try{
            int rec = entitymDao.updateByID(entitym);
            log.debug("更新数据返回 {}",rec);
            tSysLogSvc.saveLogInfo(Long.valueOf(entitym.getId()), "department", "更新部门", "部门名称:" + entitym.getDepName(), "更新", "成功", requestPojo);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        }catch (Exception e){
            tSysLogSvc.saveLogInfo(Long.valueOf(entitym.getId()), "department", "更新部门", "部门名称:" + entitym.getDepName(), "更新", "失败", requestPojo);

            log.error("修改数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("修改数据出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }
        return result;

    }

    /**
     * 删除
     *
     * @param map
     * @return Result.class
     * */
    @Override
    // @Transactional
    public Result doDelete(DeleteRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYDeptSvcImpl.doDelete parameter: {}", map);
        //非空验证
        String CompanyID = map.getCompanyID();
        Integer id = map.getId();
//        String SubID = map.getSubID();
//        String VerNo = map.getVerNo();

        if (Objects.isNull(id)) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg("id" + ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        Page page = new Page();
//        Map<String, String> mapData = new HashMap<>();
//        mapData.put("CompanyID", CompanyID);
//        mapData.put("VerNo", VerNo);
//        mapData.put("SubID", SubID);
        SYDept entitym = entitymDao.selectById(id);
        if (entitym == null) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg(ResStatus.STATUS_UNAVAILABLE_MSG);
            return result;
        }

        try{
            int rec = entitymDao.deleteById(id);
            log.debug("删除数据返回 {}",rec);

            tSysLogSvc.saveLogInfo(Long.valueOf(id), "department", "删除部门", "部门名称:" + entitym.getDepName(), "删除", "成功", requestPojo);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        }catch (Exception e){
            tSysLogSvc.saveLogInfo(Long.valueOf(id), "department", "删除部门", "部门名称:" + entitym.getDepName(), "删除", "失败", requestPojo);

            log.error("删除数据出错",e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("删除出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }

        return result;

    }

    @Override
    public Result doSaveMap(DeptSaveRequest map, RequestPojo requestPojo) {
        log.info("doSaveMap {}", map);
        SYDept entitym = new SYDept();
        BeanUtils.copyProperties(map, entitym);

        return this.doSave(entitym, requestPojo);
    }

    @Override
    public Result doUpdateMap(DeptSaveRequest map, RequestPojo requestPojo) {
        log.info("doUpdateMap {}", map);
        SYDept entitym = new SYDept();
        BeanUtils.copyProperties(map, entitym);

        return this.doUpdate(entitym, requestPojo);
    }

    /**
     * 查询部门结构
     *
     * @param map
     * @return Result.class
     * */
    @Override
    public Result doQueryStructure(Map<String, String> map) {
        Result result = new Result();
        //分页查询
        Page page = new Page();
        log.debug("SYDeptSvcImpl.doQueryStructure parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();
        String CompanyID = ParamUtil.getParamfromMap(map, "CompanyID");
        String VerNo = ParamUtil.getParamfromMap(map, "VerNo");
        String SubID = ParamUtil.getParamfromMap(map, "SubID");
        String ParID = null;

        if(null == SubID || StringUtils.isEmpty(SubID)){
            ParID = DEFAULT_TOP_DEPCODE;
        }

        //2020-03-29设置默认值
        if(Objects.isNull(CompanyID) || StringUtils.isEmpty(CompanyID)){
            CompanyID = COMPANY_CD;
        }

        //VerNo为空时获取最近有效的版本
        if(Objects.isNull(VerNo)|| StringUtils.isEmpty(VerNo)){
            Map<String, String> mapData1 = new HashMap<>();
            mapData1.put("CompanyID", CompanyID);
            List<SYDepVer> entitys = entitymverDao.selectList(page, mapData1);
            if(Objects.nonNull(entitys) && entitys.size() > 0){
                VerNo = entitys.get(0).getVerNo();
                log.debug("SYDeptSvcImpl 获取最新版本 VerNo: {}", VerNo);
            }
        }


        //缓存数据
        Map<String, String> mapData1 = new HashMap<>();
        mapData1.put("CompanyID", CompanyID);
        String DepName = map.get("depName");
        List<SYDept> entitys = entitymDao.selectList(page, mapData1);

        mapData.put("CompanyID", CompanyID);
        mapData.put("VerNo", VerNo);
        mapData.put("ParID", ParID);
        mapData.put("SubID", SubID);
        mapData.put("id", null);

        List<SYDeptPojo> entityRT = new ArrayList<>();
        entityRT = getChildNode(entitys, mapData, DepName);

        if(null != entityRT) {
            page.setTotal(entityRT.size());
        }else{
            page.setTotal(0);
        }
        page.setRecords(entityRT);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    private List<SYDeptPojo> getChildNode(List<SYDept> entityParRT, Map<String, String> tmpData, String DepName) {
        log.debug("SYDeptSvcImpl.getChildNode entityParRT: {}， tmpData： {}", entityParRT, tmpData);
        Page page = new Page();
        List<SYDeptPojo> entityRT = new ArrayList<>();
        List<SYDept> entitys;

        if (StringUtils.isNotEmpty(tmpData.get("DepName"))) {
            entitys = entityParRT.stream().filter(a -> Objects.nonNull(tmpData.get("CompanyID"))
                    && tmpData.get("CompanyID").equalsIgnoreCase(a.getCompanyID())
                    && Objects.nonNull(tmpData.get("VerNo"))
                    && tmpData.get("VerNo").equalsIgnoreCase(a.getVerNo())
                    && StringUtils.isNotEmpty(tmpData.get("DepName"))
                    && a.getDepName().contains(tmpData.get("DepName"))
                    && Objects.nonNull(tmpData.get("ParID"))
                    && tmpData.get("ParID").equalsIgnoreCase(a.getParID())).collect(Collectors.toList());
        } else {
            entitys = entityParRT.stream().filter(a -> Objects.nonNull(tmpData.get("CompanyID"))
                    && tmpData.get("CompanyID").equalsIgnoreCase(a.getCompanyID())
                    && Objects.nonNull(tmpData.get("VerNo"))
                    && tmpData.get("VerNo").equalsIgnoreCase(a.getVerNo())
                    && Objects.nonNull(tmpData.get("ParID"))
                    && tmpData.get("ParID").equalsIgnoreCase(a.getParID())).collect(Collectors.toList());
        }
//        entitys = entitymDao.selectListbyPK(page, tmpData);
        log.debug("SYDeptSvcImpl.getChildNode entitys: {}", entitys.size());
        if(null == entitys || entitys.size() == 0){
            return null;
        }

        for(SYDept entity: entitys){
            Map<String, String> mapData1 = new HashMap<>();
            mapData1.put("CompanyID", tmpData.get("CompanyID"));
            mapData1.put("VerNo", tmpData.get("VerNo"));
            mapData1.put("ParID", String.valueOf(entity.getId()));
            mapData1.put("id", null);
            if (entity.getParID().equals(DEFAULT_TOP_DEPCODE)) {
                mapData1.put("DepName", DepName);
            }

            SYDeptPojo pojo = new SYDeptPojo();
            BeanUtils.copyProperties(entity, pojo);
            List<SYDeptPojo> pojo1 = getChildNode(entityParRT, mapData1, "");
            log.debug("SYDeptSvcImpl.getChildNode mapData1: {}", mapData1);
            pojo.setLevel(pojo1);
            entityRT.add(pojo);
        }

//        entityParRT.setLevel(entityRT);

        return entityRT;
    }
}
