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.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.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);
	}


	/**
	 * 最低工资导出
	 *
	 * @author wzb
	 * @param inputStream
	 * @return {@link R}
	 */
    @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("");

				if (Common.isEmpty(data.getId())) {
					data.setErrorFlag(true);
					errorMessage.append("更新的ID为空;");
				}
				if (Common.isEmpty(data.getLocation())) {
					data.setErrorFlag(true);
					errorMessage.append("所在地为空;");
				}
				if (Common.isEmpty(data.getSalaryBase())) {
					data.setErrorFlag(true);
					errorMessage.append("最低工资标准为空;");
				}
				if (Common.isEmpty(data.getStatus())) {
					data.setErrorFlag(true);
					errorMessage.append("状态为空;");
				}
				if (CommonConstants.ZERO_INT==baseMapper.selectId(data.getId())) {
					data.setErrorFlag(true);
					errorMessage.append("不是系统内的数据;");
				}
				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());
						String location[]=e.getLocation().split("/");
						for (int i=0 ;i<location.length;i++){
							if(i==0){
								int province=baseMapper.selectByAreaName(location[i]);
								selectOne.setProvince(province);
							}
							if (i==1){
								int city=baseMapper.selectByAreaName(location[i]);
								selectOne.setCity(city);
							}
							if (i==2){
								int town=baseMapper.selectByAreaName(location[i]);
								selectOne.setTown(town);;
							}
						}
						if(e.getStatus().equals("启用")){
							selectOne.setStatus(CommonConstants.ONE_INT);
						}
						if(e.getStatus().equals("停用")) {
							selectOne.setStatus(CommonConstants.TWO_INT);
						}
						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);

}








}




