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

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
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.SYDept;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupDeptQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupDeptSaveBatchRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupDeptSaveRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupDeptInfo;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupDeptList;
import com.github.pagehelper.ISelect;
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.SYDept;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupDeptQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupDeptSaveBatchRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupDeptSaveRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupDeptInfo;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupDeptList;
import com.fufan.mtsaas.modules.sysmgr.sygroup.dao.SYgroupDeptDao;
import com.fufan.mtsaas.modules.sysmgr.sygroup.model.SYgroupDept;
import com.fufan.mtsaas.modules.sysmgr.sygroup.service.SYgroupDeptSvc;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Liby
 * @since 2019-08-18
 */
@Service("SYgroupDeptSvcImpl")
@Slf4j
@Primary
public class SYgroupDeptSvcImpl extends ServiceImpl<SYgroupDeptDao, SYgroupDept> implements SYgroupDeptSvc {
    @Autowired
    private SYgroupDeptDao entitymDao;

    @Autowired
    private SYDeptDao deptDao;

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

    /**
     * 查询
     *
     * @param map
     * @return Result.class
     * */
    @Override
    public Result doQueryPage(GroupDeptQueryRequest map) {
        Result result = new Result();
        //分页查询
        Page page = new Page();
        log.debug("SYgroupDeptSvcImpl.doQueryPage parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();
        String CompanyID = map.getCompanyID();
        String GroupID = map.getGroupID();
        String DepCode = map.getDepCode();

        //赋值默认
        if (StringUtils.isEmpty(CompanyID)) {
            CompanyID = COMPANY_CD;
        }

        mapData.put("CompanyID", CompanyID);
        mapData.put("GroupID", GroupID);
        mapData.put("DepCode", DepCode);

        List<SYGroupDeptInfo> 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("SYgroupDeptSvcImpl.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(SYgroupDept entitym, RequestPojo requestPojo) {
        log.debug("SYgroupDeptSvcImpl.doSave parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(com.alibaba.druid.util.StringUtils.isEmpty(entitym.getCompanyID()) || com.alibaba.druid.util.StringUtils.isEmpty(entitym.getGroupID()) || com.alibaba.druid.util.StringUtils.isEmpty(entitym.getDepCode())){
            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("GroupID", entitym.getGroupID());
        mapData.put("DepCode", entitym.getDepCode());


        List<SYGroupDeptInfo> entity = entitymDao.selectList(page, mapData);
        if(entity != null && entity.size() > 0){
            result.setResStatus(ResStatus.STATUS_EXISTENCE);
            result.setResMsg(ResStatus.STATUS_EXISTENCE_MSG);
            return result;
        }

        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()));
        try{
            int rec = entitymDao.insertRecords(entitym);
            log.debug("新增数据返回 {}",rec);

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

            result.setResData(page.setRecords(Arrays.asList(entitym)));
        }catch (Exception e){
            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(SYgroupDept entitym, RequestPojo requestPojo) {
        log.debug("SYgroupDeptSvcImpl.doUpdate parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(com.alibaba.druid.util.StringUtils.isEmpty(entitym.getCompanyID()) || com.alibaba.druid.util.StringUtils.isEmpty(entitym.getGroupID()) || com.alibaba.druid.util.StringUtils.isEmpty(entitym.getDepCode())){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        entitym.setUpdatedPerson(requestPojo.getUserName());
        entitym.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));
        try{
            int rec = entitymDao.updateRecords(entitym);
            log.debug("更新数据返回 {}",rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        }catch (Exception e){
            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(GroupDeptQueryRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYgroupDeptSvcImpl.doDelete parameter: {}", map);
        //非空验证
        String CompanyID = map.getCompanyID();
        String GroupID = map.getGroupID();
        String DepCode = map.getDepCode();
//
//        try {
//            CompanyID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("CompanyID").toString();
//            GroupID = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("GroupID").toString();
//            DepCode = JSON.parseObject(JSonUtil.collectToString(map)).getJSONObject("data").getJSONObject("param").get("DepCode").toString();
//        }catch (Exception e){
//            log.debug("SYgroupDeptSvcImpl.doQueryPage get doDelete parameter is not found.");
//        }

        if(com.alibaba.druid.util.StringUtils.isEmpty(CompanyID) || com.alibaba.druid.util.StringUtils.isEmpty(GroupID) || com.alibaba.druid.util.StringUtils.isEmpty(DepCode)){
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
            return result;
        }

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        mapData.put("CompanyID", CompanyID);
        mapData.put("GroupID", GroupID);
        mapData.put("DepCode", DepCode);
        List<SYGroupDeptInfo> entitym = entitymDao.selectList(page, mapData);
        if(entitym == null || entitym.size() == 0){
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg("数据不存在");
            return result;
        }

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

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

        return result;

    }

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

        return this.doSave(entitym, requestPojo);
    }

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

        return this.doUpdate(entitym, requestPojo);
    }

    /**
     * 查询未选择的记录
     *
     * @param map
     * @return Result.class
     * */
    @Override
    public Result doQueryUnSelectPage(GroupDeptQueryRequest map) {
        Result result = new Result();
        //分页查询
        Page page = new Page();
        log.debug("SYgroupDeptSvcImpl.doQueryUnSelectPage parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();
        String CompanyID = map.getCompanyID();
        String GroupID = map.getGroupID();
        String DepCode = map.getDepCode();
        mapData.put("CompanyID", CompanyID);
        mapData.put("GroupID", GroupID);
        mapData.put("DepCode", DepCode);

        List<SYDept> entitys;

//        ParamUtil.setPage(map, page);
        entitys = deptDao.selectunList(page, mapData);
        log.debug("SYgroupDeptSvcImpl.doQueryUnSelectPage selectunList entitys: {}", entitys);
        SYGroupDeptList groupList = new SYGroupDeptList();
        groupList.setUnselected(entitys);

        entitys = deptDao.selectpickedList(page, mapData);
        log.debug("SYgroupDeptSvcImpl.doQueryUnSelectPage selectpickedList entitys: {}", entitys);
        groupList.setSelected(entitys);

        List<SYGroupDeptList> list = new ArrayList<>();
        list.add(groupList);
        log.debug("SYgroupDeptSvcImpl.doQueryUnSelectPage list: {}", list);

        page.setTotal(list.size());
        page.setRecords(list);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    /**
     * 批量更新
     *
     * @param map
     * @param requestPojo
     * @return Result.class
     */
    @Override
    @Transactional
    public Result doBatchUpdate(GroupDeptSaveBatchRequest map, RequestPojo requestPojo) {
        log.info("SYgroupDeptSvcImpl.doBatchUpdate {}", map);
        Result result = new Result();

        //处理已存在记录
        Page page = new Page();
        HashMap mapData = new HashMap();
        if(map.getList().size() > 0) {
            mapData.put("CompanyID", map.getList().get(0).getCompanyID());
            mapData.put("GroupID", map.getList().get(0).getGroupID());
            int lnRec = entitymDao.deleteByPk(mapData);

            for (GroupDeptSaveRequest aRecordsList : map.getList()) {
                //非空验证
                if (com.alibaba.druid.util.StringUtils.isEmpty(aRecordsList.getCompanyID()) || com.alibaba.druid.util.StringUtils.isEmpty(aRecordsList.getGroupID())) {
                    result.setResStatus(ResStatus.STATUS_WRONGFUL);
                    result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }

                mapData = new HashMap<>();
                mapData.put("CompanyID", aRecordsList.getCompanyID());
                mapData.put("GroupID", aRecordsList.getGroupID());
                mapData.put("DepCode", aRecordsList.getDepCode());

                List<SYGroupDeptInfo> entity = entitymDao.selectList(page, mapData);
                if (entity != null && entity.size() > 0) {
                    result.setResStatus(ResStatus.STATUS_EXISTENCE);
                    result.setResMsg(ResStatus.STATUS_EXISTENCE_MSG);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }

                SYgroupDept entitym = new SYgroupDept();
                BeanUtils.copyProperties(aRecordsList, entitym);
                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()));

                try {
                    int rec = entitymDao.insertRecords(entitym);
                    log.debug("新增数据返回 {}", rec);
                } catch (Exception e) {
                    log.error("新增数据出错", e);
                    result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
                    result.setResMsg("新增数据出错：" + e.getMessage());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            }
        }

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

        return result;
    }

}
