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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.CacheConstants;
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.insurances.constants.InsurancesConstants;
import com.yifu.cloud.plus.v1.yifu.insurances.util.ValidityUtil;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.InsuranceAddParam;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TMinSalary;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryEmployee;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TMinSalaryMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.TMinSalaryService;
import com.yifu.cloud.plus.v1.yifu.salary.vo.*;
import com.yifu.cloud.plus.v1.yifu.social.vo.TPaymentInfoBatchVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TPaymentInfoSearchVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TPreDispatchExportVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialInfoVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
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:17 2022/8/6
 * @Param
 * @return
 **/
@Service("tMinSalaryService")
public class TMinSalaryServiceImpl extends ServiceImpl<TMinSalaryMapper, TMinSalary> implements TMinSalaryService {

	/**
	 * 各地市最低工资标准简单分页查询
	 *
	 * @param tMinSalary 各地市最低工资标准
	 * @return
	 */


	@Override
	public IPage<TMinSalary> getTMinSalaryPage(Page<TMinSalary> page, TMinSalarySearchVo tMinSalary) {
		return baseMapper.getTMinSalaryPage(page, tMinSalary);
	}

	@Override
	public R<Boolean> saveDiy(TMinSalary tMinSalary) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user || null == user.getId()) {
			return R.failed("获取登录用户信息失败！");
		}
		tMinSalary.setCreateTime(LocalDateTime.now());
		tMinSalary.setCreateBy(String.valueOf(user.getId()));
		LambdaQueryWrapper<TMinSalary> query = new LambdaQueryWrapper<>();
		if (Common.isNotNull(tMinSalary.getProvince())) {
			query.eq(TMinSalary::getProvince, tMinSalary.getProvince());
		}
		if (Common.isNotNull(tMinSalary.getCity())) {
			query.eq(TMinSalary::getCity, tMinSalary.getCity());
		}
		if (Common.isNotNull(tMinSalary.getTown())) {
			query.eq(TMinSalary::getTown, tMinSalary.getTown());
		}
		if (Common.isEmpty(tMinSalary.getTown())) {
			query.isNull(TMinSalary::getTown);
		}
		long res = baseMapper.selectCount(query);
		if (res > CommonConstants.ZERO_INT) {
			return R.failed("已存在对应区域在用的配置信息");
		}
		baseMapper.insert(tMinSalary);
		return R.ok(true, CommonConstants.SAVE_SUCCESS);
	}

	@Override
	public R<Boolean> updateByIdDIy(TMinSalary tMinSalary) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user || null == user.getId()) {
			return R.failed("获取登录用户信息失败！");
		}
		TMinSalary entity = baseMapper.selectById(tMinSalary.getId());
		if (Common.isNotNull(entity)) {
			LambdaQueryWrapper<TMinSalary> query = new LambdaQueryWrapper<>();
			if (Common.isNotNull(tMinSalary.getProvince())) {
				query.eq(TMinSalary::getProvince, tMinSalary.getProvince());
			}
			if (Common.isNotNull(tMinSalary.getCity())) {
				query.eq(TMinSalary::getCity, tMinSalary.getCity());
			}
			if (Common.isNotNull(tMinSalary.getTown())) {
				query.eq(TMinSalary::getTown, tMinSalary.getTown());
			}
			if (Common.isEmpty(tMinSalary.getTown())) {
				query.isNull(TMinSalary::getTown);
			}
			query.ne(TMinSalary::getId, tMinSalary.getId());
			long res = baseMapper.selectCount(query);
			if (res > CommonConstants.ZERO_INT) {
				return R.failed("已存在对应区域在用的配置信息");
			}
			baseMapper.updateById(tMinSalary);
			return R.ok(true, CommonConstants.UPDATE_SUCCESS);
		} else {
			return R.failed(false, CommonConstants.SAVE_FAILED);
		}
	}


	@Override
	public List<TMinSalaryExportVo> exportList(TMinSalarySearchVo tMinSalary) {
		return baseMapper.getTMinSalaryNoPage(tMinSalary);
	}


	/**
	 * 批量更新
	 *
	 * @param inputStream
	 * @return {@link R}
	 * @author wzb
	 */
	@Override
	public R importList(InputStream inputStream) {
		List<TMinSalaryImportVo> tMinSalaryImportVoList = new ArrayList<>();
		try {
			EasyExcel.read(inputStream, TMinSalaryImportVo.class, new ReadListener<TMinSalaryImportVo>() {
				@Override
				public void invoke(TMinSalaryImportVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					StringBuilder errorMessage = new StringBuilder("");
					extracted(data, errorMessage);
					if(data.isErrorFlag()){
						data.setErrorMessage(errorMessage.toString());
					}
					tMinSalaryImportVoList.add(data);
			}


			@Override
			public void doAfterAllAnalysed (AnalysisContext context){
				saveData();
			}

			private void saveData () {
				List<TMinSalaryImportVo> salaryImportsSuccessList = tMinSalaryImportVoList.stream().filter(e -> e.isErrorFlag() != true).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(salaryImportsSuccessList)) {

					//将成功的数据转换成需要入库的格式
					salaryImportsSuccessList.stream().forEach(e -> {
								TMinSalary selectOne = new TMinSalary();
								selectOne.setId(e.getId());
								if (null != e.getLocation()) {
										String location[] = e.getLocation().split("/");
										if (location.length >1) {
											for (int i = 0; i < location.length; i++) {
												if (i == CommonConstants.ZERO_INT) {
													int province = baseMapper.selectByAreaName(location[i]);
													selectOne.setProvince(province);
												}
												if (i == CommonConstants.ONE_INT) {
													int city = baseMapper.selectByAreaName(location[i]);
													selectOne.setCity(city);
												}
												if (i == CommonConstants.TWO_INT) {
													int town = baseMapper.selectByAreaName(location[i]);
													selectOne.setTown(town);
												}
											}
										}
								}
								if(null==e.getLocation()){
								TMinSalary tMinSalary=baseMapper.selectById(e.getId());
								    selectOne.setProvince(tMinSalary.getProvince());
									selectOne.setCity(tMinSalary.getCity());
									selectOne.setTown(tMinSalary.getTown());


								}
								if(null!=e.getStatus()) {
									if (CommonConstants.START.equals(e.getStatus())) {
										selectOne.setStatus(CommonConstants.ONE_INT);
									}
									if (CommonConstants.STOP.equals(e.getStatus())) {
										selectOne.setStatus(CommonConstants.TWO_INT);
									}
								}
								if(null!=e.getSalaryBase()) {
									selectOne.setSalaryBase(e.getSalaryBase());
								}
								selectOne.setUpdateTime(LocalDateTime.now());
								baseMapper.updateById(selectOne);

							}
					);
				}
			}

		}).sheet().doRead();
	} catch(
	Exception e)

	{
		log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
		return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
	}

	//返回给前端的错误数据
	List<TMinSalaryImportVo> errorImportErrorList = tMinSalaryImportVoList.stream().filter(e -> e.isErrorFlag() == true).collect(Collectors.toList());
		return R.ok(errorImportErrorList);

}

	private void extracted(TMinSalaryImportVo data, StringBuilder errorMessage) {
		if (Common.isEmpty(data.getId())) {
			data.setErrorFlag(true);
			errorMessage.append("ID为空;");
			return;
		} else {
			if (Common.isEmpty(baseMapper.selectById(data.getId()))) {
				data.setErrorFlag(true);
				errorMessage.append("ID不存在无法更新，请核实后再操作!;");
				return;
			}
			if (Common.isEmpty(data.getLocation()) && Common.isEmpty(data.getSalaryBase()) && Common.isEmpty(data.getStatus())) {
				data.setErrorFlag(true);
				errorMessage.append("所在地、最低工资(元)、状态为空;");
				return;
			}
			if(null!= data.getLocation()) {
				if (data.getLocation().contains("-")) {
					data.setErrorFlag(true);
					errorMessage.append("所在地格式与列表保持一致;");
					return;
				}
			}

			if (null != data.getLocation()) {
				String location[] = data.getLocation().split("/");
				if (!data.getLocation().isEmpty()) {
					if (location.length == 1) {
						data.setErrorFlag(true);
						errorMessage.append("所在地”请精确到市或县/区;");
						return;
					}
					String redisProvinceName = getRedisAreaValue(location[CommonConstants.ZERO_INT]);
					if (Common.isEmpty(redisProvinceName)) {
						data.setErrorFlag(true);
						errorMessage.append("对应区域不存在;");
						return;
					}
				}
				if (location.length == 2) {
					String redisProvinceName = getRedisAreaValue(location[CommonConstants.ZERO_INT]);
					if (Common.isEmpty(redisProvinceName)) {
						data.setErrorFlag(true);
						errorMessage.append("对应区域不存在;");
						return;
					}
					String redisCityName = getRedisAreaValue(location[CommonConstants.ONE_INT] + "_" + location[CommonConstants.ZERO_INT]);
					if (Common.isEmpty(redisCityName)) {
						data.setErrorFlag(true);
						errorMessage.append("对应区域不存在;");
						return;
					} else {
						TMinSalary entity = baseMapper.selectById(data.getId());
						if (Common.isNotNull(entity)) {
							LambdaQueryWrapper<TMinSalary> query = new LambdaQueryWrapper<>();

							if (Common.isNotNull(redisProvinceName)) {
								query.eq(TMinSalary::getProvince, redisProvinceName);
							}
							if (Common.isNotNull(redisCityName)) {
								query.eq(TMinSalary::getCity, redisCityName);
							}
							query.isNull(TMinSalary::getTown);
							query.ne(TMinSalary::getId, data.getId());
							long res = baseMapper.selectCount(query);

							if (res > CommonConstants.ZERO_INT) {
								data.setErrorFlag(true);
								errorMessage.append("已存在对应区域在用的配置信息;");
								return;
							}
						}
					}
				}
				if (location.length > 2) {
					String redisProvinceName = getRedisAreaValue(location[CommonConstants.ZERO_INT]);
					String redisCityName = getRedisAreaValue(location[CommonConstants.ONE_INT] + "_" + location[CommonConstants.ZERO_INT]);
					if (Common.isEmpty(redisCityName)) {
						data.setErrorFlag(true);
						errorMessage.append("对应区域不存在;");
						return;
					}
					String redisTownName = getRedisAreaValue(location[CommonConstants.TWO_INT] + "_" + location[CommonConstants.ONE_INT]);
					if (Common.isEmpty(redisTownName)) {
						data.setErrorFlag(true);
						errorMessage.append("对应区域不存在;");
						return;
					}
					else {
						TMinSalary entity = baseMapper.selectById(data.getId());
						if (Common.isNotNull(entity)) {
							LambdaQueryWrapper<TMinSalary> query = new LambdaQueryWrapper<>();
							if (Common.isNotNull(redisProvinceName)) {
								query.eq(TMinSalary::getProvince, redisProvinceName);
							}
							if (Common.isNotNull(redisCityName)) {
								query.eq(TMinSalary::getCity, redisCityName);
							}
							if (Common.isNotNull(redisTownName)) {
								query.eq(TMinSalary::getTown, redisTownName);
							}
							query.ne(TMinSalary::getId, data.getId());
							long res = baseMapper.selectCount(query);
							if (res > CommonConstants.ZERO_INT) {
								data.setErrorFlag(true);
								errorMessage.append("已存在对应区域在用的配置信息;");
								return;
							}
						}
					}
				}
			}

		}
		if (Common.isNotNull(data)){
			if (null != data.getSalaryBase()) {
				if (!ValidityUtil.validateStandard(data.getSalaryBase())) {
					data.setErrorFlag(true);
					errorMessage.append("最低工资，请填写>0的两位小数;");
				}
			}
			if (null != data.getStatus()) {
				if (!(CommonConstants.START.equals(data.getStatus()) || CommonConstants.STOP.equals(data.getStatus()))) {
					data.setErrorFlag(true);
					errorMessage.append("填写的状态不是启用或停用");
				}
			}
		}
	}


	private String getRedisAreaValue(String areaString) {
		return String.valueOf(RedisUtil.redis.opsForValue().get(CacheConstants.AREA_VALUE + areaString));
	}


}




