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

import com.alibaba.druid.util.StringUtils;
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.sygroup.bo.request.GroupMenuQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupMenuSaveBatchRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupMenuSaveRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupMenuInfo;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupMenuList;
import com.fufan.mtsaas.modules.sysmgr.sygroup.service.SYgroupMenuSvc;
import com.fufan.mtsaas.modules.sysmgr.symenu.dao.SYmenuDao;
import com.fufan.mtsaas.modules.sysmgr.symenu.model.SYmenu;
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.sygroup.bo.request.GroupMenuQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupMenuSaveBatchRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.request.GroupMenuSaveRequest;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupMenuInfo;
import com.fufan.mtsaas.modules.sysmgr.sygroup.bo.response.SYGroupMenuList;
import com.fufan.mtsaas.modules.sysmgr.sygroup.dao.SYgroupMenuDao;
import com.fufan.mtsaas.modules.sysmgr.sygroup.model.SYgroupMenu;
import com.fufan.mtsaas.modules.sysmgr.sygroup.service.SYgroupMenuSvc;
import com.fufan.mtsaas.modules.sysmgr.symenu.dao.SYmenuDao;
import com.fufan.mtsaas.modules.sysmgr.symenu.model.SYmenu;
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 java.util.*;

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

    @Autowired
    private SYmenuDao menuDao;

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

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

        //赋值默认
        if(StringUtils.isEmpty(CompanyID)){
            CompanyID = COMPANY_CD;
        }
        mapData.put("CompanyID", CompanyID);
        mapData.put("GroupID", GroupID);
        mapData.put("MenuID", MenuID);

        List<SYGroupMenuInfo> 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("SYgroupMenuSvcImpl.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(SYgroupMenu entitym, RequestPojo requestPojo) {
        log.debug("SYgroupMenuSvcImpl.doSave parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(StringUtils.isEmpty(entitym.getCompanyID()) || StringUtils.isEmpty(entitym.getGroupID()) || StringUtils.isEmpty(entitym.getMenuID())){
            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("MenuID", entitym.getMenuID());


        List<SYGroupMenuInfo> 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(SYgroupMenu entitym, RequestPojo requestPojo) {
        log.debug("SYgroupMenuSvcImpl.doUpdate parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(StringUtils.isEmpty(entitym.getCompanyID()) || StringUtils.isEmpty(entitym.getGroupID()) || StringUtils.isEmpty(entitym.getMenuID())){
            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(GroupMenuQueryRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYgroupMenuSvcImpl.doDelete parameter: {}", map);
        //非空验证
        String CompanyID = map.getCompanyID();
        String GroupID = map.getGroupID();
        String MenuID = map.getMenuID();

        if(StringUtils.isEmpty(GroupID)){
            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("MenuID", MenuID);

        List<SYGroupMenuInfo> 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(GroupMenuSaveRequest map, RequestPojo requestPojo) {
        log.info("doSaveMap {}", map);
        SYgroupMenu entitym = new SYgroupMenu();
        BeanUtils.copyProperties(map, entitym);

        return this.doSave(entitym, requestPojo);
    }

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

        return this.doUpdate(entitym, requestPojo);
    }

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

        List<SYmenu> entitys;

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

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

        List<SYGroupMenuList> list = new ArrayList<>();
        list.add(groupList);
        log.debug("SYgroupMenuSvcImpl.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(GroupMenuSaveBatchRequest map, RequestPojo requestPojo) {
        log.info("SYgroupMenuSvcImpl.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 (GroupMenuSaveRequest aRecordsList : map.getList()) {
                //非空验证
                if (StringUtils.isEmpty(aRecordsList.getCompanyID()) || StringUtils.isEmpty(aRecordsList.getGroupID())) {
                    result.setResStatus(ResStatus.STATUS_WRONGFUL);
                    result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }

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

                mapData = new HashMap<>();
                mapData.put("CompanyID", entitym.getCompanyID());
                mapData.put("GroupID", entitym.getGroupID());
                mapData.put("MenuID", entitym.getMenuID());

                List<SYgroupMenu> entitymQuery = entitymDao.selectGeneralList(page, mapData);
                if(Objects.nonNull(entitymQuery) && entitymQuery.size() > 0){
                    result.setResStatus(ResStatus.STATUS_EXISTENCE);
                    result.setResMsg(ResStatus.STATUS_EXISTENCE_MSG);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }

                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;

    }

}
