package com.rongwei.bscommon.sys.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.config.EquForkliftRepairRecordListener;
import com.rongwei.bscommon.sys.dao.EquForkliftRepairRecordDao;
import com.rongwei.bscommon.sys.excel.EquForkliftRepairRecordTemplate;
import com.rongwei.bscommon.sys.service.EquForkliftRepairRecordService;
import com.rongwei.bscommon.sys.utils.CommonUtils;
import com.rongwei.bscommon.sys.utils.DateUtils;
import com.rongwei.bsentity.domain.EquForkliftRepairRecordDo;
import com.rongwei.bsentity.enums.MaintenanceTypeEnum;
import com.rongwei.bsentity.enums.PlantEnum;
import com.rongwei.rwadmincommon.system.domain.SysDictDo;
import com.rongwei.rwadmincommon.system.domain.SysOrganizationDo;
import com.rongwei.rwadmincommon.system.service.SysDictService;
import com.rongwei.rwadmincommon.system.service.SysOrganizationService;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommonentity.commonservers.vo.SysSerialVo;
import com.rongwei.safecommon.utils.CXCommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.rongwei.safecommon.utils.SaveConstans.DatePattern.DATE_PATTERN_YMD;

@Service
public class EquForkliftRepairRecordServiceImpl extends ServiceImpl<EquForkliftRepairRecordDao, EquForkliftRepairRecordDo> implements EquForkliftRepairRecordService {


    @Autowired
    EquForkliftRepairRecordService equForkliftRepairRecordService;

    @Autowired
    EquForkliftRepairRecordDao equForkliftRepairRecordDao;

    @Autowired
    private SysDictService dictService;

    @Autowired
    private SysOrganizationService sysOrganizationService;

    @Override
    public R equForkliftRepairRecordService(MultipartFile multipartFile) throws IOException {
        Date date = new Date();
        EquForkliftRepairRecordListener forkliftRepairRecordListener = new EquForkliftRepairRecordListener();
        // 解析Excel
        EasyExcel.read(multipartFile.getInputStream(), EquForkliftRepairRecordTemplate.class, forkliftRepairRecordListener).sheet().headRowNumber(3).doRead();
        // 解析有误信息
        List<String> errorData = forkliftRepairRecordListener.getErrorData();
        // 解析数据
        List<EquForkliftRepairRecordDo> newForkliftRepairRecord = forkliftRepairRecordListener.getForkliftRepairRecordDoList();
        // 唯一性数据
    //    List<EquForkliftRepairRecordDo> oldForkliftRepairRecord = equForkliftRepairRecordService.getUniqueDateByAll();
        // 将新旧两组数据拼接为一个stream，再对stream进行分组，找到分组数量大于1的(说明又重复)，将重复的数据拿到原始数据中找到源数据返回回来
//        List<EquForkliftRepairRecordDo> forkliftRepairRecordDoList = Stream.concat(newForkliftRepairRecord.stream(), oldForkliftRepairRecord.stream()).collect(Collectors.groupingBy(info ->
//                        info.getEquipmentnumber() + info.getRapairdate() + info.getRapairdetail() , Collectors.counting()))
//                .entrySet().stream()
//                .filter(info -> info.getValue() > 1)
//                .map(Map.Entry::getKey)
//                .map(info -> newForkliftRepairRecord.stream()
//                        .filter(item -> ( item.getEquipmentnumber() + item.getRapairdate() + item.getRapairdetail()).equals(info))
//                        .findFirst().orElse(null))
//                .filter(Objects::nonNull)
//                .collect(Collectors.toList());
        // 拼接返回错误数据
//        if (forkliftRepairRecordDoList.size() != 0) {
//            jointErrorData(forkliftRepairRecordDoList, errorData);
//        }
        // 判断是否又错误数据
        if (errorData.size() != 0) {
            return R.error(JSON.toJSONString(errorData));
        }
        SysUserVo currentUser = CommonUtils.getCurrentUser();

        List<SysDictDo> repairPersonType = dictService.getByRedis("equ_cxwxbyr");
        Map<String, String> dictMap = repairPersonType.stream().collect(Collectors.toMap(SysDictDo::getName, SysDictDo::getValue));

        String rapairname ="";
        String rapairid ="";
        // 使用 StringBuilder 来构建新的字符串
        StringBuilder newStr = new StringBuilder();
        // 生成流水号
        for (EquForkliftRepairRecordDo forkliftRepairRecord : newForkliftRepairRecord) {
            rapairname = forkliftRepairRecord.getRapairname()==null?"":forkliftRepairRecord.getRapairname();
            String[] parts = rapairname.split(",");
            newStr = new StringBuilder();
            // 遍历分割后的数组，并根据数据字典进行替换
            for (String part : parts) {
                String replacement = dictMap.getOrDefault(part, part); // 如果找不到对应的值，则使用原值
                newStr.append(replacement).append(",");
            }
            // 移除最后一个多余的逗号，并转换为字符串
             rapairid = newStr.length() > 0 ? newStr.substring(0, newStr.length() - 1) : "";

            forkliftRepairRecord.setTenantid(CXCommonUtils.getCurrentUserFactoryId(currentUser))
                    .setCreatedate(date)
                    .setModifydate(date)
                    .setCreateuserid(currentUser.getId())
                    .setCreateusername(currentUser.getName())
                    .setModifyusername(currentUser.getName())
                    .setRapairid(rapairid)
                    .setModifyuserid(currentUser.getId());
        }
        equForkliftRepairRecordService.saveBatch(newForkliftRepairRecord, 200);
        return R.ok("导入成功");
    }

    @Override
    public List<EquForkliftRepairRecordDo> getUniqueDateByAll() {
        LambdaQueryWrapper<EquForkliftRepairRecordDo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(EquForkliftRepairRecordDo::getEquipmentnumber,
                EquForkliftRepairRecordDo::getRapairdetail,
                EquForkliftRepairRecordDo::getRapairdate
              ).eq(EquForkliftRepairRecordDo::getDeleted,"0");

        return equForkliftRepairRecordDao.selectList(queryWrapper);

    }

    public void jointErrorData(List<EquForkliftRepairRecordDo> forkliftRepairRecordDoList, List<String> errorData) {
        forkliftRepairRecordDoList.forEach(info -> {
            errorData.add(PlantEnum.nameOf(info.getTenantid()) + ",已存在了叉车编号" + ":" + info.getEquipmentnumber()+" 维修/保养日期:" +  DateUtil.format(info.getRapairdate(),DATE_PATTERN_YMD) +" 维修/保养内容:" + info.getRapairdetail() + "的数据，不可重复导入，请检查");
        });

    }
}
