package org.jeecg.modules.regular.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.device.entity.BuDeviceType;
import org.jeecg.modules.device.mapper.BuDeviceTypeMapper;
import org.jeecg.modules.regular.entity.Regular;
import org.jeecg.modules.regular.entity.RegularDetail;
import org.jeecg.modules.regular.entity.RegularDetailImport;
import org.jeecg.modules.regular.mapper.RegularDetailMapper;
import org.jeecg.modules.regular.mapper.RegularMapper;
import org.jeecg.modules.regular.service.IRegularDetailService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 检修规程详情
 * @Author: jeecg-boot
 * @Date:   2025-01-16
 * @Version: V1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RegularDetailServiceImpl extends ServiceImpl<RegularDetailMapper, RegularDetail> implements IRegularDetailService {

    private final RegularMapper regularMapper;
    private final BuDeviceTypeMapper deviceTypeMapper;
    private final ISysDictService dictService;
    @Override
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        String pid = request.getParameter("pid");
        Regular regular = regularMapper.selectById(pid);
        if(regular == null){
            return Result.error("检修规程不存在");
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<RegularDetailImport> list = ExcelImportUtil.importExcel(file.getInputStream(), RegularDetailImport.class, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                List<RegularDetail> data = list.stream().map(item -> {
                    if(StringUtils.isEmpty(item.getPart()) || StringUtils.isEmpty(item.getCheckType())){
                        return null;
                    }
                    RegularDetail detail = new RegularDetail();
                    detail.setDispOrder(item.getDispOrder());
                    detail.setRegularId(pid);
                    detail.setSkillLevel("0");
                    detail.setDeviceTypeId(regular.getDeviceTypeId());
                    detail.setRepairRange(String.valueOf(regular.getRapairRange()));
                    detail.setContent(item.getContent());
                    detail.setMeasure(item.getMeasure());
                    detail.setSkillLevel("1");
                    //part需要查询
                    String[] parts = item.getPart().split(":");
                    BuDeviceType deviceType = new BuDeviceType();
                    if(parts.length == 1){
                        deviceType = deviceTypeMapper.selectOne(new LambdaQueryWrapper<BuDeviceType>()
                                .eq(BuDeviceType::getPid,regular.getDeviceTypeId()).eq(BuDeviceType::getTypeName, item.getPart()));
                        if(deviceType == null){
                            deviceType = new BuDeviceType();
                            deviceType.setPid(regular.getDeviceTypeId());
                            deviceType.setTypeName(item.getPart());
                            deviceType.setTypeCode(PinyinUtil.getFirstLetter(item.getPart(), "").toUpperCase());
                            deviceTypeMapper.insert(deviceType);
                        }
                    }else{
                        String _pid = regular.getDeviceTypeId();
                        for(int i = 0; i < parts.length; i++)
                        {
                            deviceType = deviceTypeMapper.selectOne(new LambdaQueryWrapper<BuDeviceType>()
                                    .eq(BuDeviceType::getPid,_pid).eq(BuDeviceType::getTypeName, parts[i]));
                            if(deviceType == null){
                                deviceType = new BuDeviceType();
                                deviceType.setPid(_pid);
                                deviceType.setTypeName(parts[i]);
                                String pinyin = PinyinUtil.getFirstLetter(parts[i], "");
                                deviceType.setTypeCode(pinyin.toUpperCase());
                                deviceTypeMapper.insert(deviceType);
                            }
                            _pid = deviceType.getId();
                        }
                    }
                    detail.setDepard(deviceType.getId());
                    if(item.getCheckType()!=null){
                        detail.setCheckType(Integer.valueOf(item.getCheckType()));
                    }else{
                        deviceType.setSubTypes(null);
                    }

                    //checkType 需要从字典翻译
//                    if(!StringUtils.isEmpty(item.getCheckType())){
//                        List<DictModel> dicts =  dictService.getDictItems("regular_check_type");
//                        DictModel _dict = dicts.stream().filter(x -> x.getLabel().equals(item.getCheckType())).collect(Collectors.toList()).get(0);
//                        if(_dict!=null){
//                            detail.setCheckType(Integer.valueOf(_dict.getValue()));
//                        }
//                    }
                    detail.setMutualInspection(item.getMutualInspection());
                    detail.setPersonalizedInspection(item.getPersonalizedInspection());
                    return detail;
                }).collect(Collectors.toList());
                long start = System.currentTimeMillis();
                List<RegularDetail> details = data.stream().filter(item -> item!=null).toList();
                super.saveBatch(details);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if(msg!=null && msg.indexOf("Duplicate entry")>=0){
                    return Result.error("文件导入失败:有重复数据！");
                }else{
                    return Result.error("文件导入失败:" + e.getMessage());
                }
                //update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }
}
