package com.fufan.mtsaas.modules.sysmgr.symenu.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.base.log.service.TSysLogSvc;
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.symenu.bo.request.MenuQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.symenu.bo.request.MenuSaveRequest;
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.symenu.bo.request.MenuQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.symenu.bo.request.MenuSaveRequest;
import com.fufan.mtsaas.modules.sysmgr.symenu.dao.SYmenuDao;
import com.fufan.mtsaas.modules.sysmgr.symenu.model.SYmenu;
import com.fufan.mtsaas.modules.sysmgr.symenu.service.SYmenuSvc;
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.*;

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

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

    @Autowired
    private TSysLogSvc tSysLogSvc;

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

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

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

        List<SYmenu> 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);

            tSysLogSvc.saveLogInfo(Long.valueOf(entitym.getId()), "menu", "新增菜单", "菜单名称:" + entitym.getMenuDisp(), "新增", "成功", 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()), "menu", "新增菜单", "菜单名称:" + entitym.getMenuDisp(), "新增", "失败", requestPojo);

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

    }

    /**
     * 修改
     *
     * @param entitym
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doUpdate(SYmenu entitym, RequestPojo requestPojo) {
        log.debug("SYmenuSvcImpl.doUpdate parameter: {}", entitym);
        Result result = new Result();
        //非空验证
        if(StringUtils.isEmpty(entitym.getCompanyID()) || 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);

            tSysLogSvc.saveLogInfo(Long.valueOf(entitym.getId()), "menu", "修改菜单", "菜单名称:" + entitym.getMenuDisp(), "更新", "成功", requestPojo);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        }catch (Exception e){
            tSysLogSvc.saveLogInfo(Long.valueOf(entitym.getId()), "menu", "修改菜单", "菜单名称:" + entitym.getMenuDisp(), "修改", "失败", 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(MenuQueryRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYmenuSvcImpl.doDelete parameter: {}", map);
        //非空验证
        String CompanyID = map.getCompanyID();
        String MenuID = map.getMenuID();

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

            tSysLogSvc.saveLogInfo(Long.valueOf(entitym.get(0).getId()), "menu", "删除菜单", "菜单名称:" + entitym.get(0).getMenuDisp(), "删除", "成功", requestPojo);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        }catch (Exception e){
            tSysLogSvc.saveLogInfo(Long.valueOf(entitym.get(0).getId()), "menu", "删除菜单", "菜单名称:" + entitym.get(0).getMenuDisp(), "删除", "失败", requestPojo);

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

        return result;

    }

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

        return this.doSave(entitym, requestPojo);
    }

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

        return this.doUpdate(entitym, requestPojo);
    }
}
