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

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fufan.mtsaas.config.RedissonCommand;
import com.fufan.mtsaas.constant.RedisKeyConstant;
import com.fufan.mtsaas.modules.base.log.bo.request.LogSaveRequest;
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.systation.bo.request.StationQueryRequest;
import com.fufan.mtsaas.modules.sysmgr.systation.bo.request.StationSaveRequest;
import com.fufan.mtsaas.modules.sysmgr.systation.bo.response.StationResponse;
import com.fufan.mtsaas.modules.sysmgr.systation.dao.SYstationDao;
import com.fufan.mtsaas.modules.sysmgr.systation.model.SYstation;
import com.fufan.mtsaas.modules.sysmgr.systation.service.SYstationSvc;
import com.fufan.mtsaas.util.DateFormatTool;
import com.fufan.mtsaas.util.ParamUtil;
import com.github.pagehelper.ISelect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RLock;
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.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Liby
 * @since 2019-08-14
 */
@Service("SYstationSvcImpl")
@Slf4j
@Primary
public class SYstationSvcImpl extends ServiceImpl<SYstationDao, SYstation> implements SYstationSvc {
    @Autowired
    private SYstationDao entitymDao;

    @Autowired
    private RedissonCommand redissonCommand;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TSysLogSvc tSysLogSvc;

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

    /**
     * 查询
     *
     * @param map
     * @return Result.class
     */
    @Override
    public Result doQueryPage(StationQueryRequest map) {
        RequestPojo requestPojo = ParamUtil.doChange();
        Result result = new Result();
        //分页查询
        Page page = new Page();
        log.debug("SYstationSvcImpl.doQueryPage parameter: {}", map);
        Map<String, String> mapData = new HashMap<>();

//        String stationRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getId());
//        if (org.apache.commons.lang3.StringUtils.isNotEmpty(String.valueOf(map.getId())) && org.apache.commons.lang3.StringUtils.isEmpty(stationRedisId)) {
//            result.setResStatus(ResStatus.STATUS_SUCCESS);
//            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
//            page.setTotal(0);
//            result.setResData(page);
//            return result;
//        }
        String Name = map.getStationName();

        if (!COMPANY_ID.equals(requestPojo.getCustId())) {
            mapData.put("CompanyID", requestPojo.getCustId());
        }
        mapData.put("stationID", String.valueOf(map.getId()));
        mapData.put("stationName", Name);

        List<SYstation> 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("SYstationSvcImpl.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 map
     * @param requestPojo
     * @return Result.class
     */
    @Override
    // @Transactional
    public Result doSave(StationSaveRequest map, RequestPojo requestPojo) {
        Integer stationId = map.getId();
        log.debug("SYstationSvcImpl.doSave parameter: {}", map);
        Result result = new Result();

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        if (!COMPANY_ID.equals(requestPojo.getCustId())) {
            mapData.put("CompanyID", requestPojo.getCustId());
        }
        mapData.put("stationName", map.getStationName());

        List<SYstation> entitys = entitymDao.selectList(page, mapData);
        if (CollectionUtils.isNotEmpty(entitys) && entitys.size() > 0) {
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("该岗位名称" + map.getStationName() + ResStatus.STATUS_EXISTENCE_MSG);
            return result;
        }

        SYstation entitym = new SYstation();
        BeanUtils.copyProperties(map, entitym);

        entitym.setId(-1);
        entitym.setCompanyID(requestPojo.getCustId());
        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 {
            RLock rLock = redissonCommand.getFairLock(String.valueOf(entitym.getId()));
            if (rLock.tryLock()) {
                try {
                    int rec = entitymDao.insert(entitym);
                    log.debug("新增数据返回 {}", rec);
                    result.setResStatus(ResStatus.STATUS_SUCCESS);
                    result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
                } catch (Exception e) {
                    log.error("INSERT SYstation " + e.getLocalizedMessage());
                } finally {
                    rLock.unlock();
                }
            }
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(Long.valueOf(entitym.getId()));
                logSaveRequest.setRelatedType("position");
                logSaveRequest.setLogTitle("新增岗位");
                logSaveRequest.setLogContent("岗位账户：" + entitym.getId() + "岗位名称:" + entitym.getStationName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("新增");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, requestPojo);
            } catch (Exception e) {
                log.error(e.getMessage());
            }

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

        return result;

    }

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

        SYstation entitym = new SYstation();
        BeanUtils.copyProperties(map, entitym);

        entitym.setUpdatedPerson(requestPojo.getUserName());
        entitym.setUpdatedDT(DateFormatTool.dateToString(DateFormatTool.DATETIME_FORMAT, new Date()));

        try {
            RLock rLock = redissonCommand.getFairLock(String.valueOf(entitym.getId()));
            if (rLock.tryLock()) {
                try {
                    int rec = entitymDao.update(entitym);
                } catch (Exception e) {
                    log.error("UPDATE SYstation " + e.getLocalizedMessage());
                } finally {
                    rLock.unlock();
                }
            }
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(Long.valueOf(entitym.getId()));
                logSaveRequest.setRelatedType("position");
                logSaveRequest.setLogTitle("修改岗位");
                logSaveRequest.setLogContent("岗位账户：" + entitym.getId() + "岗位名称:" + entitym.getStationName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("修改");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, requestPojo);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            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(DeleteRequest map, RequestPojo requestPojo) {
        Result result = new Result();
        log.debug("SYstationSvcImpl.doDelete parameter: {}", map);
        //非空验证
        Integer stationID = map.getId();

        Page page = new Page();
        Map<String, String> mapData = new HashMap<>();
        String stationRedisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + stationID);
        mapData.put("stationID", String.valueOf(stationID));
        List<SYstation> entitym = entitymDao.selectList(page, mapData);
        if (entitym == null || entitym.size() == 0) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg("数据不存在");
            return result;
        }

        try {
            int rec = entitymDao.deleteById(Integer.valueOf(stationID));
            if (rec > 0) {
                stringRedisTemplate.delete(RedisKeyConstant.USER_MODIFY_LOCK + ":" + stationID);
                stringRedisTemplate.delete(RedisKeyConstant.USER_TOKEN + ":" + entitym.get(0).getCompanyID() + ":" + stationID);
                ;
            }
            log.debug("删除数据返回 {}", rec);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(Long.valueOf(stationRedisId));
                logSaveRequest.setRelatedType("position");
                logSaveRequest.setLogTitle("删除岗位");
                logSaveRequest.setLogContent("岗位账户：" + entitym.get(0).getId() + "岗位名称:" + entitym.get(0).getStationName());
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("删除");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, requestPojo);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        } catch (Exception e) {
            log.error("删除数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("删除出错：" + e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus()().setRollbackOnly();
        }

        return result;

    }

}
