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

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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.ExcelUtils;
import com.dhcc.finance.main.dao.CwBdGlorgbookMapper;
import com.dhcc.finance.main.dao.CwGlBalanceMapper;
import com.dhcc.finance.main.dao.CwGlInitbuildTempMapper;
import com.dhcc.finance.main.dao.CwGlVoucherMapper;
import com.dhcc.finance.main.domain.CwGlInitbuildTemp;
import com.dhcc.finance.main.model.FileUploadRequest;
import com.dhcc.finance.main.model.FileUploadRequestTemp;
import com.dhcc.finance.main.service.CwGlBalanceService;
import com.dhcc.finance.util.MetaDataUtil;

import brave.Tracer;
import lombok.extern.slf4j.Slf4j;
/**
 * 功能描述：科目辅助余额表接口实现
 * @author dml
 * @date 2019年4月22日 上午10:58:40
 * @修改日志：
 */
@Slf4j
@Service
public class CwGlBalanceServiceImpl implements CwGlBalanceService{
	
	@Autowired
	private Tracer tracer;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Autowired
	CwGlBalanceMapper cwGlBalanceMapper;//辅助余额表

	@Autowired
	CwGlVoucherMapper cwGlVoucherMapper;//凭证信息
	@Autowired
    CwGlInitbuildTempMapper cwGlInitbuildTempMapper;
    @Autowired
    CwBdGlorgbookMapper cwBdGlorgbookMapper;
	
	private static final String PERIODSUFFIX ="-00";//年初会计期间后缀
	/*
	 * (非 Javadoc)  
	 * Title: earlyYearRecalculation 
	 * Description:年初重算
	 * @param pkGlorgbook
	 * @param year
	 * @return  
	 * @see com.dhcc.finance.main.service.CwGlBalanceService#earlyYearRecalculation(java.lang.String, java.lang.String)    
	 * @author dml
	 * @date 2019年4月22日 上午11:08:21
	 * @修改日志：
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public RestfulResponse<Object, CurrencyMeta> earlyYearRecalculation(String pkGlorgbook, String year) {
		// 校验是否为空
		if (StringUtils.isBlank(pkGlorgbook) || StringUtils.isBlank(year)) {
			return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,SysStatusCode.SERVER_CHECK_ERROR.message(),
					MetaDataUtil.getMeta(tracer,SysStatusCode.SERVER_CHECK_ERROR));
		}
		// 查询未记账业务数
		long countNotBooking = cwGlVoucherMapper.countNotBooking(pkGlorgbook,String.valueOf(Integer.parseInt(year)-1));
		// 校验该帐套下上年业务是否全部已记账
		if (countNotBooking != 0) {
			return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.EXISTENCE_OF_UNRECORDED.message(),
					MetaDataUtil.getMeta(tracer,FinanceStatusCode.EXISTENCE_OF_UNRECORDED));
		}
		String period = year+PERIODSUFFIX;
		// 删除之前的重算结果
		cwGlBalanceMapper.deleteEarlyYearRecalculation(pkGlorgbook, period);
		Map<String, Object> map =new HashMap<String, Object>();
		SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate, SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
		map.put("createUser", sysUserInfo == null? null:sysUserInfo.getUserId());
		map.put("createTime", new Date());
		map.put("pkGlorgbook", pkGlorgbook);
		map.put("period",period);
		map.put("lastPeriod", String.valueOf(Integer.parseInt(year)-1));
		// 新增年初重算
		cwGlBalanceMapper.insertEarlyYearRecalculation(map);
		// 校验计算结借贷是否平衡
		Map<String, BigDecimal> balanceCount = cwGlBalanceMapper.balanceCount(pkGlorgbook, period);
		log.info("借贷平衡计算结果>>>>>>>>>>>"+balanceCount);
		if (balanceCount.get("zcSum").compareTo(balanceCount.get("fzSum").add(balanceCount.get("syzqySum"))) !=0 ) {
			return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.FAIL,FinanceStatusCode.LOAN_NOT_BALANCE.message(),
					MetaDataUtil.getMeta(tracer,FinanceStatusCode.LOAN_NOT_BALANCE));
		}
		return new RestfulResponse<Object, CurrencyMeta>(SysConstants.CODE.SUCCESS,SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,
				MetaDataUtil.getMeta(tracer,SysStatusCode.OPERATION_SUCCESS));
	}
	
	/*
	 * (非 Javadoc)  
	 * Title: uploadCwGlBalance 
	 * Description:导入期初余额
	 * @param fileUploadRequest
	 * @param type
	 * @return  
	 * @see com.dhcc.finance.main.service.CwGlBalanceService#uploadCwGlBalance(com.dhcc.finance.main.model.FileUploadRequest, java.lang.String)    
	 * @author dml
	 * @date 2019年4月24日 下午3:56:32
	 * @修改日志：
	 */
	@Override
	public RestfulResponse<String, CurrencyMeta> uploadCwGlBalance(FileUploadRequest fileUploadRequest, String type) {
		/*
		MultipartFile[] files = fileUploadRequest.getFiles();
        StringBuffer result = new StringBuffer("");
        try {
            for (MultipartFile multipartFile : files) {
                String fileRealName = multipartFile.getOriginalFilename();
                int pointIndex = fileRealName.lastIndexOf('.');
                String fileSuffix = fileRealName.substring(pointIndex);//截取文件后缀
                File excelFile = File.createTempFile("cwGlBalanceInfo", fileSuffix);
                
                multipartFile.transferTo(excelFile);
                try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(excelFile), "UTF-8"))){
                	String readLine;
                	while (( readLine = bufferedReader.readLine()) != null) {
                    	System.out.println(readLine);
					}
                	
                }
              
                }
              
        } catch (Exception e) {
           // log.error("数据流操作异常", e);
        }
        if("".equals(result.toString())){
            return new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.SUCCESS,
                    SysConstants.BASIC_JDBC_RES_MESSAGE.SAVE_SUCCESS, "数据插入成功",
                    MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
        }
        return new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.FAIL,
                SysConstants.BASIC_JDBC_RES_MESSAGE.SAVE_FAIL, result.toString(),
                MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
                */
              return new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.FAIL,
                        SysConstants.BASIC_JDBC_RES_MESSAGE.SAVE_FAIL, "肯定成功",
                        MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));//TODO 暂时不做 若不要后期删除 
	}

	/* (非 Javadoc)  
	 * <p>Title: seachCwGlBalanceSum</p>  
	 * <p>Description: 计算科目余额(余额控制方向)</p>
	 * @param pkGlorgbook
	 * @param period
	 * @param pkAccsub
	 * @return  
	 * @see com.dhcc.finance.main.service.CwGlBalanceService#seachCwGlBalanceSum(java.lang.String, java.lang.String, java.lang.String)    
	 * @author huangpeng
	 * @date 2019年4月28日 下午7:04:22
	 * @修改日志：
	 */
	
	@Override
	public RestfulResponse<String, CurrencyMeta> seachCwGlBalanceSum(String pkGlorgbook, String period,
			String pkAccsubj,String balanorient) {
		String year=period.substring(0,period.indexOf("-"));
		String sum = cwGlBalanceMapper.seachCwGlBalanceSum(pkGlorgbook,period,pkAccsubj,balanorient,year);
		return  new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.SUCCESS,
                SysConstants.DEFAULT_MESSAGE.OPERATION_SUCCESS,sum,
                MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
	}
	/**
     * 功能描述:期初余额临时表Excel导入
     * @param fileUploadRequestTemp
     * @return RestfulResponse<String,CurrencyMeta>
     *@author baiyc
     *@date 2019年4月29日 下午2:51:37
     *@修改日志:
     */
    
    @Override
    public RestfulResponse<String, CurrencyMeta> uploadCwGlInitbuildTemp(FileUploadRequestTemp fileUploadRequestTemp, String pkGlorgbook,String period) {
               
               //获取文件  
               MultipartFile[] files = fileUploadRequestTemp.getFiles();
               StringBuffer result = new StringBuffer("");
               try {
                     for (MultipartFile multipartFile : files) {
                          String fileRealName = multipartFile.getOriginalFilename();
                          int pointIndex = fileRealName.lastIndexOf('.');
                          String fileSuffix = fileRealName.substring(pointIndex);//截取文件后缀
                          File excelFile = File.createTempFile("cwGlInitbuildTemp", fileSuffix);
                          multipartFile.transferTo(excelFile);
                          SysUserInfo sysUserInfo = CacheDataUtil.<SysUserInfo>getCacheBean(stringRedisTemplate,
                                     SysConstants.REDIS_KEY_PREFIX.SYS_USER_INFO, SysUserInfo.class);
                          Map<String, Object> map =new HashMap<String, Object>();
                          //读取Excel中相关数据
                          List<CwGlInitbuildTemp> cwGlInitbuildTempList = ExcelUtils.readExcelFile(CwGlInitbuildTemp.class, excelFile);
                          //获取账套和期间
                          CwGlInitbuildTemp cwGlInitbuildTemp=new CwGlInitbuildTemp();
                          cwGlInitbuildTemp.setPkGlorgbook(pkGlorgbook);
                          cwGlInitbuildTemp.setPeriod(period);
                          cwGlInitbuildTemp.setUseState("1");  
                          cwGlInitbuildTemp.setPkCurrtype("本币");
                          if(sysUserInfo!=null) {
                                cwGlInitbuildTemp.setCreateUser(sysUserInfo.getUserId());
                          }
                          cwGlInitbuildTemp.setCreateTime(new Date());
                          map.put("cwGlInitbuildTemp", cwGlInitbuildTemp);
                          map.put("cwGlInitbuildTempList", cwGlInitbuildTempList);
                          cwGlInitbuildTempMapper.batchInsertCwGlInitbuildTemp(map);
                     
                     }
               } catch (Exception e) {
                     log.error("数据流操作异常", e);
               }
               if("".equals(result.toString())){
                     return new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.SUCCESS,
                                SysConstants.BASIC_JDBC_RES_MESSAGE.SAVE_SUCCESS, "数据插入成功",
                                MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_SUCCESS));
               }
               return new RestfulResponse<String, CurrencyMeta>(SysConstants.CODE.FAIL,
                       SysConstants.BASIC_JDBC_RES_MESSAGE.SAVE_FAIL, result.toString(),
                       MetaDataUtil.getMeta(tracer, SysStatusCode.OPERATION_FAIL));
 }
}