package com.yifu.cloud.plus.v1.yifu.salary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSpecialDeducationSum;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TSpecialDeducationSumMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSpecialDeducationSumService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author fxj
 * @Description 专项扣除
 * @Date 13:19 2022/8/6
 * @Param
 * @return
**/
@Service("tSpecialDeducationSumService")
public class TSpecialDeducationSumServiceImpl extends ServiceImpl<TSpecialDeducationSumMapper, TSpecialDeducationSum> implements TSpecialDeducationSumService {

     /**
      * 简单分页查询
      *
      * @param tSpecialDeducationSum
      * @return
      */
     @Override
     public IPage<TSpecialDeducationSum> getTSpecialDeducationSumPage(Page<TSpecialDeducationSum> page, TSpecialDeducationSum tSpecialDeducationSum) {
          return baseMapper.getTSpecialDeducationSumPage(page, tSpecialDeducationSum);
     }

     /**
      * @param tSpecialDeducationSum
      * @Description: 查找专项信息
      * @Author: hgw
      * @Date: 2019/9/30 16:19
      * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.yifu.cloud.v1.hrms.api.entity.TSpecialDeducationSum>
      **/
     @Override
     public List<TSpecialDeducationSum> getTSpecialDeducationSumList(TSpecialDeducationSum tSpecialDeducationSum) {
          return baseMapper.getTSpecialDeducationSumList(tSpecialDeducationSum);
     }

     /**
      * @Description: 查找专项信息
      * @Author: hgw
      * @Date: 2019/9/30 16:19
      * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.yifu.cloud.v1.hrms.api.entity.TSpecialDeducationSum>
      **/
     @Override
     public TSpecialDeducationSum getTSpecialDeducationSum(String yearMonth, String idNumber, String invoiceTitle) {
          return baseMapper.getTSpecialDeducationSum(yearMonth, idNumber, invoiceTitle);
     }

     /**
      * @param yearMonth
      * @param idCardList
      * @Description: 工资查询所需的全部list，组装Map来使用
      * @Author: hgw
      * @Date: 2022/1/26 16:45
      * @return: java.util.Map<java.lang.String, com.yifu.cloud.v1.hrms.api.entity.TSpecialDeducationSum>
      **/
     @Override
     public Map<String, TSpecialDeducationSum> getTSpecialDeducationSumMap(String yearMonth, List<String> idCardList) {
          Map<String, TSpecialDeducationSum> sdsMap = new HashMap<>();
          if (Common.isNotNull(yearMonth) && idCardList != null && !idCardList.isEmpty()) {
               List<TSpecialDeducationSum> sdsList = baseMapper.getListByIdCardList(yearMonth, idCardList);
               if (sdsList != null && !sdsList.isEmpty()) {
                    for (TSpecialDeducationSum sds : sdsList) {
                         sdsMap.put(sds.getIdNumber() + CommonConstants.DOWN_LINE_STRING + sds.getDeclareTitle(), sds);
                    }
               }
          }
          return sdsMap;
     }

     /**
      * @param yearMonth 年月
      * @param invoiceTitle 申报单位
      * @Description: 删除专项扣除
      * @Author: hgw
      * @Date: 2020/4/1 15:11
      * @return: int
      **/
     @Override
     public int deleteByUnitAndMonth(String yearMonth, String invoiceTitle) {
          return baseMapper.deleteByUnitAndMonth(yearMonth, invoiceTitle);
     }

     /**
      * @Author fxj
      * @Description 保存专项
      * @Date 10:05 2022/8/23
     **/
	 @Transactional
     @Override
     public R<List<ErrorMessage>> uploadSds(List<TSpecialDeducationSum> sdsList) {
          if (Common.isNotNull(sdsList)) {
			  List<ErrorMessage> errorMessages = new ArrayList<>();
			  errorMessages = checkImport(sdsList,errorMessages);
			  if (Common.isNotNull(errorMessages)) {
				  return R.ok(errorMessages);
			  }
               String nowYearMonth = DateUtil.getCurrentDateString("yyyyMM");
               String yearMonth = DateUtil.getYearMonth(sdsList.get(0).getCreateStart()
					   .replace("/","")
					   .replace("-",""));
               if (Common.isNotNull(yearMonth)) {
				    if (!Common.isNumber(yearMonth) || yearMonth.length() != CommonConstants.SIX_INT){
						return R.failed("日期格式有误:" + yearMonth + "，不允许导入");
					}
                    if (!yearMonth.equals(nowYearMonth)) {
                         return R.failed("所得期间-不是当前年月:" + nowYearMonth + "，不允许导入");
                    }
               } else {
                    return R.failed("请检查‘所得期间起’单元格格式是文本格式，且满足日期格式yyyy-MM-dd或yyyyMMdd");
               }
               String declareTitle = sdsList.get(0).getDeclareTitle();
               if (Common.isEmpty(declareTitle)) {
                    return R.failed("申报单位不能为空");
               }
			   List<String>  uc = sdsList.stream().map(TSpecialDeducationSum::getDeclareTitle).collect(Collectors.toList());
			   if (Common.isNotNull(uc) && uc.size() > CommonConstants.ONE_INT){
				   return R.failed("一次只允许导入一个申报单位");
			   }
               TSpecialDeducationSum sdsCheck = new TSpecialDeducationSum();
               sdsCheck.setCreateMonth(yearMonth);
               sdsCheck.setDeclareTitle(declareTitle);
               QueryWrapper<TSpecialDeducationSum> queryWrapperSc = new QueryWrapper<>();
               queryWrapperSc.setEntity(sdsCheck);
               List<TSpecialDeducationSum> scList = this.list(queryWrapperSc);
               if (scList != null && scList.size() > CommonConstants.ZERO_INT) {
                    return R.failed("当前月同一申报单位已存在数据，请先删除");
               }
               YifuUser user = SecurityUtils.getUser();
               if (null == user || null == user.getId()) {
                    return R.failed("新建失败-获取登录人信息为空");
               }
               LocalDateTime nowDate = LocalDateTime.now();
               for (TSpecialDeducationSum s : sdsList) {
                    s.setCreateMonth(yearMonth);
                    s.setCreateTime(nowDate);
                    s.setCreateBy(String.valueOf(user.getId()));
               }
               if (this.saveBatch(sdsList)){
				   return R.ok(null,CommonConstants.SAVE_SUCCESS);
			   }else {
				   return R.failed(CommonConstants.SAVE_FAILED);
			   }
          }
          return R.failed("数据不可为空");
     }

	private List<ErrorMessage> checkImport(List<TSpecialDeducationSum> sdsList,List<ErrorMessage> errorMessages) {
		ErrorMessage errorMessage;
		ExcelUtil<TSpecialDeducationSum> util1 = new ExcelUtil<>(TSpecialDeducationSum.class);
		int i =0;
		for (TSpecialDeducationSum data: sdsList) {
			i++;
			errorMessage = util1.checkEntity(data, i);
			if (Common.isNotNull(errorMessage)) {
				errorMessages.add(errorMessage);
			}else {
				continue;
			}
		}
		if (Common.isNotNull(errorMessages)){
			return errorMessages;
		}
		return null;
	}

}
