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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.dao.EquFrockTestRecordDao;
import com.rongwei.bscommon.sys.service.EquFrockTestRecordService;
import com.rongwei.bscommon.sys.utils.CommonUtils;
import com.rongwei.bscommon.sys.utils.DateUtils;
import com.rongwei.bscommon.sys.utils.ExcelUtils;
import com.rongwei.bscommon.sys.utils.StringUtil;
import com.rongwei.bsentity.domain.EquFrockListDo;
import com.rongwei.bsentity.domain.EquFrockTestRecordDo;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommon.utils.StringUtils;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class EquFrockTestRecordServiceImpl extends ServiceImpl<EquFrockTestRecordDao, EquFrockTestRecordDo> implements EquFrockTestRecordService {

    @Autowired
    private EquFrockTestRecordDao equFrockTestRecordDao;

    @Autowired
    private EquFrockTestRecordService equFrockTestRecordService;

    @Override
    @Transactional
    public R importEquFrockTestRecord(MultipartFile file) {
        StringBuilder allStrBuilder = new StringBuilder();
        List<EquFrockTestRecordDo> equFrockTestRecordDos = new ArrayList<>();
        try {
            Sheet sheet = new XSSFWorkbook(file.getInputStream()).getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();

            //获取系统所有的工装编号
            List<EquFrockListDo> equFrockListDoList = equFrockTestRecordDao.getAllFrocknum();

            //获取已检测的工装编号
            List<EquFrockTestRecordDo> equFrockTestRecordDoList = equFrockTestRecordDao.getFrockRecord();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SysUserVo currentUser = CommonUtils.getCurrentUser();
            Date date = new Date();
            String regex = "^(\\-|\\+)?\\d+(\\.\\d+)?$";//只能是数字
            Pattern pattern = Pattern.compile(regex);
            DataFormatter dataFormatter = new DataFormatter();

            for (int i = 2; i <= lastRowNum; i++) {
                StringBuilder stringBuilder = new StringBuilder();
                EquFrockTestRecordDo equFrockTestRecordDo = new EquFrockTestRecordDo();
                Row row = sheet.getRow(i);
                if (ExcelUtils.isRowEmpty(row)) {
                    continue;
                }
                String mainid = "";
                String ownedfactory = row.getCell(1) == null ? "" : dataFormatter.formatCellValue(row.getCell(1));
                String frockname = row.getCell(2) == null ? "" : dataFormatter.formatCellValue(row.getCell(2));
                String usedept = row.getCell(3) == null ? "" : dataFormatter.formatCellValue(row.getCell(3));
                String frocknum = row.getCell(4) == null ? "" : dataFormatter.formatCellValue(row.getCell(4));
                String belongequname = row.getCell(5) == null ? "" : dataFormatter.formatCellValue(row.getCell(5));
                String exctestdate = row.getCell(6) == null ? "" : String.valueOf(DateUtils.importExcelFormatExcel((XSSFCell) row.getCell(6)));
                String diameter = row.getCell(7) == null ? "" : dataFormatter.formatCellValue(row.getCell(7));
                String hs1 = row.getCell(8) == null ? "" : dataFormatter.formatCellValue(row.getCell(8));
                String hs2 = row.getCell(9) == null ? "" : dataFormatter.formatCellValue(row.getCell(9));
                String hs3 = row.getCell(10) == null ? "" : dataFormatter.formatCellValue(row.getCell(10));
                String hs4 = row.getCell(11) == null ? "" : dataFormatter.formatCellValue(row.getCell(11));
                String hs5 = row.getCell(12) == null ? "" : dataFormatter.formatCellValue(row.getCell(12));
                String hs6 = row.getCell(13) == null ? "" : dataFormatter.formatCellValue(row.getCell(13));
                String hs7 = row.getCell(14) == null ? "" : dataFormatter.formatCellValue(row.getCell(14));
                String hs8 = row.getCell(15) == null ? "" : dataFormatter.formatCellValue(row.getCell(15));
                String hs9 = row.getCell(16) == null ? "" : dataFormatter.formatCellValue(row.getCell(16));
                String state = row.getCell(17) == null ? "" : dataFormatter.formatCellValue(row.getCell(17));
                String remark = row.getCell(18) == null ? "" : dataFormatter.formatCellValue(row.getCell(18));
                if (StringUtils.isBlank(ownedfactory)) {
                    stringBuilder.append("所属工厂必填 ");
                }
                if (StringUtils.isBlank(frockname)) {
                    stringBuilder.append("工装名称必填 ");
                }
                if (StringUtils.isBlank(usedept)) {
                    stringBuilder.append("使用车间必填 ");
                }
                String testdate = "";
                if (StringUtils.isBlank(exctestdate) || exctestdate.equals("null")) {
                    stringBuilder.append("检定日期必填 ");
                } else {
                    testdate = dateFormat.format(DateUtils.importExcelFormatExcel((XSSFCell) row.getCell(6))).split(" ")[0];
                }
                if (StringUtils.isBlank(frocknum)) {
                    stringBuilder.append("工装编号必填 ");
                } else {
                    List<EquFrockListDo> efls = equFrockListDoList.stream().filter(item -> item.getFrocknum().equals(frocknum)).collect(Collectors.toList());
                    if (efls.isEmpty()) {
                        stringBuilder.append("工装编号" + frocknum + "在系统中不存在 ");
                    } else {
                        mainid = efls.get(0).getId();
                        String finalTestdate = testdate;
                        if (equFrockTestRecordDoList.stream().anyMatch(item -> item.getFrocknum().equals(frocknum) && dateFormat.format(item.getTestdate()).split(" ")[0].equals(finalTestdate))) {
                            stringBuilder.append(frockname + "（" + frocknum + "）已存在" + testdate + "的检测记录，不可重复导入 ");
                        }
                    }
                }
                if (StringUtils.isBlank(belongequname)) {
                    stringBuilder.append("工装所属必填 ");
                }
                if (StringUtils.isBlank(state)) {
                    stringBuilder.append("状态必填 ");
                }
                if (StringUtils.isBlank(diameter) || !pattern.matcher(diameter).matches()) {
                    stringBuilder.append("直径mm必填且只能为数字 ");
                }
                if (StringUtils.isBlank(hs1) || !pattern.matcher(hs1).matches()) {
                    stringBuilder.append("检测硬度值（HS1）必填且只能为数字 ");
                }
                if (StringUtils.isBlank(hs2) || !pattern.matcher(hs2).matches()) {
                    stringBuilder.append("检测硬度值（HS2）必填且只能为数字 ");
                }
                if (StringUtils.isBlank(hs3) || !pattern.matcher(hs3).matches()) {
                    stringBuilder.append("检测硬度值（HS3）必填且只能为数字 ");
                }
                if (StringUtils.isBlank(hs4) || !pattern.matcher(hs4).matches()) {
                    stringBuilder.append("检测硬度值（HS4）必填且只能为数字 ");
                }
                if (StringUtils.isBlank(hs5) || !pattern.matcher(hs5).matches()) {
                    stringBuilder.append("检测硬度值（HS5）必填且只能为数字 ");
                }
                if (StringUtils.isBlank(hs6) || !pattern.matcher(hs6).matches()) {
                    stringBuilder.append("检测硬度值（HS6）必填且只能为数字 ");
                }
                if (StringUtils.isBlank(hs7) || !pattern.matcher(hs7).matches()) {
                    stringBuilder.append("检测硬度值（HS7）必填且只能为数字 ");
                }
                if (StringUtils.isBlank(hs8) || !pattern.matcher(hs8).matches()) {
                    stringBuilder.append("检测硬度值（HS8）必填且只能为数字 ");
                }
                if (StringUtils.isBlank(hs9) || !pattern.matcher(hs9).matches()) {
                    stringBuilder.append("检测硬度值（HS9）必填且只能为数字 ");
                }
                String finalTestdate1 = testdate;
                if (equFrockTestRecordDos.stream().anyMatch(item -> item.getFrocknum().equals(frocknum) && dateFormat.format(item.getTestdate()).split(" ")[0].equals(finalTestdate1))) {
                    stringBuilder.append("工装编号" + frocknum + "、检定日期" + testdate + "数据重复");
                }

                if (StringUtil.isNotBlank(stringBuilder)) {
                    allStrBuilder.append("第").append(i + 1).append("行").append(stringBuilder).append("<br>");
                } else {
                    equFrockTestRecordDo.setId(SecurityUtil.getUUID())
                            .setTenantid(currentUser.getOrganizationDoList().get(0).getFullpid().split(",")[1])
                            .setCreatedate(date)
                            .setModifydate(date)
                            .setCreateusername(currentUser.getName())
                            .setCreateuserid(currentUser.getId())
                            .setModifyusername(currentUser.getName())
                            .setModifyuserid(currentUser.getId())
                            .setFrockid(mainid)
                            .setOwnedfactory(ownedfactory)
                            .setFrockname(frockname)
                            .setUsedept(usedept)
                            .setFrocknum(frocknum)
                            .setBelongequname(belongequname)
                            .setTestdate(dateFormat.parse(testdate + " 08:00:00"))
                            .setDiameter(new BigDecimal(diameter))
                            .setHs1(BigDecimal.valueOf(Double.parseDouble(hs1)))
                            .setHs2(BigDecimal.valueOf(Double.parseDouble(hs2)))
                            .setHs3(BigDecimal.valueOf(Double.parseDouble(hs3)))
                            .setHs4(BigDecimal.valueOf(Double.parseDouble(hs4)))
                            .setHs5(BigDecimal.valueOf(Double.parseDouble(hs5)))
                            .setHs6(BigDecimal.valueOf(Double.parseDouble(hs6)))
                            .setHs7(BigDecimal.valueOf(Double.parseDouble(hs7)))
                            .setHs8(BigDecimal.valueOf(Double.parseDouble(hs8)))
                            .setHs9(BigDecimal.valueOf(Double.parseDouble(hs9)))
                            .setState(state)
                            .setRemark(remark);
                    equFrockTestRecordDos.add(equFrockTestRecordDo);
                }
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }

        String errMsg = allStrBuilder.toString();
        if (StringUtils.isNotBlank(errMsg)) {
            return R.error(errMsg);
        } else {
            if (equFrockTestRecordDos.size() > 0) {
                if (equFrockTestRecordService.saveOrUpdateBatch(equFrockTestRecordDos)) {
                    return R.ok("上传成功");
                } else {
                    return R.error("上传失败");
                }
            } else {
                return R.ok("没有可上传的数据");
            }
        }
    }
}
