package com.dhcc.finance.main.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.dhcc.common.constant.FinanceStatusCode;
import com.dhcc.common.constant.SysConstants;
import com.dhcc.common.constant.SysStatusCode;
import com.dhcc.common.model.CurrencyMeta;
import com.dhcc.common.model.SysUserInfo;
import com.dhcc.common.model.response.RestfulResponse;
import com.dhcc.common.util.CacheDataUtil;
import com.dhcc.common.util.SnowflakeIdWorker;
import com.dhcc.finance.main.domain.CwBdReportlock;
import com.dhcc.finance.main.domain.CwBdReportlockExample;
import com.dhcc.finance.main.service.CwBdReportlockService;
import com.dhcc.finance.util.FinanceDateUtil;
import com.dhcc.finance.util.MetaDataUtil;

import brave.Tracer;

import com.dhcc.finance.constant.FinanceDictConsts;
import com.dhcc.finance.main.dao.CwBdReportlockMapper;
import com.dhcc.finance.main.domain.CwBdReportlockExample.Criteria;
@Service
public class CwBdReportlockServiceImpl implements CwBdReportlockService{
    
    @Autowired
    CwBdReportlockMapper cwBdReportlockMapper;
    
    @Autowired
    private Tracer tracer;
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 功能描述：期间锁定
     * @param cwBdReportlock
     * @return RestfulResponse<Object,CurrencyMeta>
     * @author likai
     * @date 2020年7月18日 上午10:40:11 
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> periodLock(String lockPeriod) {
        // TODO Auto-generated method stub
        CwBdReportlock reportlock = new CwBdReportlock ();
        Date date = new Date();
        // 锁上一个月，或比上一个月小的月份
        String up= FinanceDateUtil.getLast12Months(-1);
        if(lockPeriod.compareTo(up) <= 0 ) {
            reportlock.setLockPeriod(lockPeriod);
        } else {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.LOCKED_INFO_CHECK.message()
                  ,MetaDataUtil.getMeta(tracer,FinanceStatusCode.LOCKED_INFO_CHECK));
        }
        // 查询表中期间最大值
        CwBdReportlock cwBdReportlocks= cwBdReportlockMapper.selectMaxLockPeroid();
        if(cwBdReportlocks != null ) {
            String lockPeriodMax = cwBdReportlocks.getLockPeriodMax();
            if(lockPeriodMax.compareTo(lockPeriod) > 0)  {
                return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.PERIOD_LOCKED.message()
                        ,MetaDataUtil.getMeta(tracer,FinanceStatusCode.PERIOD_LOCKED));
            }
        }
        // 查询输入的项目期间是否锁定如果锁定，提示会计期间已锁定
        CwBdReportlockExample example = new CwBdReportlockExample ();
        Criteria criteria = example.createCriteria();
        criteria.andUseStateEqualTo(FinanceDictConsts.Syzt.EFFECTIVE);
        criteria.andLockPeriodEqualTo(lockPeriod);
        criteria.andSfLockEqualTo(FinanceDictConsts.Syzt.EFFECTIVE);
        List<CwBdReportlock> CwBdReportlocks= cwBdReportlockMapper.selectByExample( example);
        if (CwBdReportlocks.size() >0 && CwBdReportlocks != null) {
            return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.PERIOD_LOCKED.message()
                  ,MetaDataUtil.getMeta(tracer,FinanceStatusCode.PERIOD_LOCKED));
        } 
        //2.未锁定，新增数据，可以新增当前月份，或当前月份加1
        SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate,
                SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
        
        reportlock.setId(SnowflakeIdWorker.getInstance().nextIdString());
        reportlock.setLockPeriod(lockPeriod);
        reportlock.setSfLock(FinanceDictConsts.Syzt.EFFECTIVE);
        reportlock.setUseState(FinanceDictConsts.Syzt.EFFECTIVE);
        if (sysUserInfo != null) {
            reportlock.setCreateUser(sysUserInfo.getUserId());
            reportlock.setUpdateUser(sysUserInfo.getUserId());
        } else {
            reportlock.setCreateUser("admin");
            reportlock.setUpdateUser("admin");
        }
        reportlock.setCreateTime(date);
        reportlock.setUpdateTime(date);
        
       int res= cwBdReportlockMapper.insert(reportlock);
       if (res >0) {
           return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,
                   SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,
                   MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
       } 
       return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,SysConstants.DEFAULT_MESSAGE.OPERATION_FAIL,
               MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_FAIL));
    }
    
    /**
     * 功能描述：期间解锁
     * @param lockPeriod
     * @return RestfulResponse<Object,CurrencyMeta>
     * @author likai
     * @date 2020年7月18日 下午4:11:25
     * @修改日志：
     */
    @Override
    public RestfulResponse<Object, CurrencyMeta> periodUnlock(String lockPeriod) {
        // TODO Auto-generated method stub
        // 1.查询表中期间最大值
       CwBdReportlock cwBdReportlocks= cwBdReportlockMapper.selectMaxLockPeroid();
       String lockPeriodMax = cwBdReportlocks.getLockPeriodMax();
       
       Date date = new Date();
       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
       String now=format.format(date);
       String down= FinanceDateUtil.getLast12Months(1); // 当前月的上个月
       String up= FinanceDateUtil.getLast12Months(-1); // 当前月的下个月
       // 表中最大值等于传入值，解锁 或者传入值为当前月或当前月的下个月
       if (lockPeriod.compareTo(now) == 0 || lockPeriod.compareTo(down) == 0 || lockPeriod.compareTo(up) == 0) {
           
           CwBdReportlockExample example = new CwBdReportlockExample();
           Criteria criteria = example.createCriteria();
           criteria.andUseStateEqualTo(FinanceDictConsts.Syzt.EFFECTIVE);
           criteria.andLockPeriodEqualTo(lockPeriod);
           criteria.andSfLockEqualTo(FinanceDictConsts.Syzt.EFFECTIVE);
           
           CwBdReportlock cwBdReportlock = new CwBdReportlock();
           cwBdReportlock.setUseState(FinanceDictConsts.Syzt.INVALID);
           cwBdReportlock.setSfLock(FinanceDictConsts.Syzt.INVALID);
           
          int res= cwBdReportlockMapper.updateByExampleSelective(cwBdReportlock , example);
          if (res<=0) {
              return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.UNLOCKED_MESSAGE.message(),
                      MetaDataUtil.getMeta(tracer,FinanceStatusCode.UNLOCKED_MESSAGE));
          }
       } else {
           return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.UNLOCKED_INFO.message()
                   ,MetaDataUtil.getMeta(tracer,FinanceStatusCode.UNLOCKED_INFO));
       }
       // 2.传入的会计期间和表中的会计期间比较，   当前月份期间   可以解锁当前月份的上个月，当前月份，下个月
       return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,
               SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,
               MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
    }
    
    /**
     * 功能描述：查询表中期间锁定最大值
     * @param lockPeriod
     * @return RestfulResponse<Object,CurrencyMeta>
     * @author likai
     * @date 2020年7月18日 下午4:11:25
     * @修改日志：
     */
    public RestfulResponse<String, CurrencyMeta> seachMaxLockPeroid() {
        String lockPeriodMax = null;
        CwBdReportlock cwBdReportlocks= cwBdReportlockMapper.selectMaxLockPeroid();
        if(cwBdReportlocks != null ) {
             lockPeriodMax = cwBdReportlocks.getLockPeriodMax();
        }
        return new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,
                lockPeriodMax,MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
    }

}
