package com.aucma.report.service.impl;

import java.util.HashMap;
import java.util.List;

import com.aucma.base.domain.BaseQualityInspectionItem;
import com.aucma.base.service.IBaseQualityInspectionItemService;
import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.uuid.UUID;
import com.aucma.report.domain.ReportQualityInspection;
import com.aucma.report.service.IMaterialCompletionService;
import com.aucma.report.service.IReportQualityInspectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;

import com.aucma.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.aucma.report.domain.DetailElectricalinspection;
import com.aucma.report.mapper.RecordElectricalInspectionMapper;
import com.aucma.report.domain.RecordElectricalInspection;
import com.aucma.report.service.IRecordElectricalInspectionService;

/**
 * 电检数据记录Service业务层处理
 *
 * @author Yinq
 * @date 2023-11-09
 */
@Service
public class RecordElectricalInspectionServiceImpl implements IRecordElectricalInspectionService {
    private static final Logger logger = LoggerFactory.getLogger(RecordElectricalInspectionServiceImpl.class);

    @Autowired
    private RecordElectricalInspectionMapper recordElectricalInspectionMapper;

    @Autowired
    private IReportQualityInspectionService qualityInspectionService;

    @Autowired
    private IBaseQualityInspectionItemService itemService;

    @Autowired
    private IMaterialCompletionService materialCompletionService;

    /**
     * 查询电检数据记录
     *
     * @param uuid 电检数据记录主键
     * @return 电检数据记录
     */
    @Override
    public RecordElectricalInspection selectRecordElectricalInspectionByUuid(String uuid) {
        return recordElectricalInspectionMapper.selectRecordElectricalInspectionByUuid(uuid);
    }

    /**
     * 查询电检数据记录列表
     *
     * @param recordElectricalInspection 电检数据记录
     * @return 电检数据记录
     */
    @Override
    public List<RecordElectricalInspection> selectRecordElectricalInspectionList(RecordElectricalInspection recordElectricalInspection) {
        return recordElectricalInspectionMapper.selectRecordElectricalInspectionList(recordElectricalInspection);
    }

    /**
     * 新增电检数据记录
     *
     * @param recordElectricalInspection 电检数据记录
     * @return 结果
     */
    @Transactional
    @Override
    public int insertRecordElectricalInspection(RecordElectricalInspection recordElectricalInspection) {
        int rows = recordElectricalInspectionMapper.insertRecordElectricalInspection(recordElectricalInspection);
        insertDetailElectricalinspection(recordElectricalInspection);
        return rows;
    }

    /**
     * 修改电检数据记录
     *
     * @param recordElectricalInspection 电检数据记录
     * @return 结果
     */
    @Transactional
    @Override
    public int updateRecordElectricalInspection(RecordElectricalInspection recordElectricalInspection) {
        recordElectricalInspectionMapper.deleteDetailElectricalinspectionByUuid(recordElectricalInspection.getUuid());
        insertDetailElectricalinspection(recordElectricalInspection);
        return recordElectricalInspectionMapper.updateRecordElectricalInspection(recordElectricalInspection);
    }

    /**
     * 批量删除电检数据记录
     *
     * @param uuids 需要删除的电检数据记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteRecordElectricalInspectionByUuids(String[] uuids) {
        recordElectricalInspectionMapper.deleteDetailElectricalinspectionByUuids(uuids);
        return recordElectricalInspectionMapper.deleteRecordElectricalInspectionByUuids(uuids);
    }

    /**
     * 删除电检数据记录信息
     *
     * @param uuid 电检数据记录主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteRecordElectricalInspectionByUuid(String uuid) {
        recordElectricalInspectionMapper.deleteDetailElectricalinspectionByUuid(uuid);
        return recordElectricalInspectionMapper.deleteRecordElectricalInspectionByUuid(uuid);
    }


    /**
     * 新增电检数据明细信息
     *
     * @param recordElectricalInspection 电检数据记录对象
     */
    public void insertDetailElectricalinspection(RecordElectricalInspection recordElectricalInspection) {
        List<DetailElectricalinspection> detailElectricalinspectionList = recordElectricalInspection.getDetailElectricalinspectionList();
        String uuid = recordElectricalInspection.getUuid();
        if (StringUtils.isNotNull(detailElectricalinspectionList)) {
            List<DetailElectricalinspection> list = new ArrayList<DetailElectricalinspection>();
            for (DetailElectricalinspection detailElectricalinspection : detailElectricalinspectionList) {
                detailElectricalinspection.setUuid(uuid);
                list.add(detailElectricalinspection);
            }
            if (list.size() > 0) {
                recordElectricalInspectionMapper.batchDetailElectricalinspection(list);
            }
        }
    }


    /**
     * 解析电检数据接口
     *
     * @param paramMap
     * @param productLineCode
     * @return
     */
    @Override
    public HashMap<String, String> analysisElectricalInspectionData(Map paramMap, String productLineCode) {
        HashMap<String, String> resultData = new HashMap<>();
        RecordElectricalInspection inspection = new RecordElectricalInspection();
        ArrayList<DetailElectricalinspection> detailList = new ArrayList<>();
        String uuid = String.valueOf(paramMap.get("uuid"));
        try {
            String result = String.valueOf(paramMap.get("result"));
            String barcode = String.valueOf(paramMap.get("barcode"));
            String testdata = String.valueOf(paramMap.get("testdata"));
            String testtime = String.valueOf(paramMap.get("testtime"));
            inspection.setUuid(UUID.randomUUID().toString());
            inspection.setResult(result);
            inspection.setBarcode(barcode);
            if (StringUtils.isNull(testtime)) {
                testtime = DateUtils.dateTime();
            }
            inspection.setTestTime(testtime);
            inspection.setTestData(uuid);
            inspection.setRecordTime(DateUtils.getNowDate());
            inspection.setProductLineCode(productLineCode);
            recordElectricalInspectionMapper.insertRecordElectricalInspection(inspection);
            String[] testDataEntries = testdata.split(";");
            for (String testDataEntry : testDataEntries) {
                String[] testDataParts = testDataEntry.split("\\|");
                if (testDataParts.length == 5) {
                    DetailElectricalinspection testData = new DetailElectricalinspection();
                    testData.setUuid(uuid);
                    testData.setSerialnumber(Long.parseLong(testDataParts[0]));
                    testData.setProjectname(testDataParts[1]);
                    testData.setTestcondition(testDataParts[2]);
                    testData.setTestvalue(testDataParts[3]);
                    testData.setTestresult(testDataParts[4]);
                    testData.setRecordtime(DateUtils.getNowDate());
                    recordElectricalInspectionMapper.insertDetailElectricalinspection(testData);
                    detailList.add(testData);
                }
            }
            this.insertQualityInspectionByElectrical(inspection, detailList, productLineCode);
        } catch (Exception e) {
            logger.error("解析电检数据接口数据:" + paramMap.toString() + ";异常：" + e);
        }
        resultData.put("uuid", uuid);
        resultData.put("answer", "OK");
        return resultData;
    }

    /**
     * 电检结果存入质检数据
     *  @param inspectionInfo
     * @param detailList
     * @param productLineCode
     */
    private void insertQualityInspectionByElectrical(RecordElectricalInspection inspectionInfo, ArrayList<DetailElectricalinspection> detailList, String productLineCode) {
        if (StringUtils.isNull(inspectionInfo.getBarcode()) || StringUtils.isNull(detailList)) {
            return;
        }
        String barcode = inspectionInfo.getBarcode();
        ReportQualityInspection qualityInspection = qualityInspectionService.selectReportQualityInspectionByBarcode(barcode, productLineCode);
        if (StringUtils.isNull(qualityInspection)) {
            return;
        }
        //质检合格存入质检数据
        if (StringUtils.isNotEmpty(inspectionInfo.getResult()) && inspectionInfo.getResult().equals("OK")) {
            qualityInspection.setTreatmentMeasure("3");
            qualityInspection.setProductLineName(inspectionInfo.getProductLineCode());
            qualityInspectionService.insertReportQualityInspection(qualityInspection);
            materialCompletionService.inspectionProcessing(qualityInspection);
            return;
        }
        //质检不合格存入质检数据
        for (DetailElectricalinspection detail : detailList) {
            if (StringUtils.isEmpty(detail.getTestresult()) || detail.getTestresult().equals("OK")) {
                continue;
            }
            String projectName = detail.getProjectname();
            BaseQualityInspectionItem item = new BaseQualityInspectionItem();
            String qualityDefectCode = null;
            String qualityDefectName = null;
            qualityInspection.setTestItemCode(qualityInspection.getStationCode());
            if (projectName.equals("gnd")) {
                item.setQualityDefectCode("5002");
                List<BaseQualityInspectionItem> itemList = itemService.selectBaseQualityInspectionItemList(item);
                qualityDefectCode = itemList.get(0).getQualityDefectCode();
                qualityDefectName = itemList.get(0).getQualityDefectName();
            }else if (projectName.equals("acw")){
                item.setQualityDefectCode("5004");
                List<BaseQualityInspectionItem> itemList = itemService.selectBaseQualityInspectionItemList(item);
                qualityDefectCode = itemList.get(0).getQualityDefectCode();
                qualityDefectName = itemList.get(0).getQualityDefectName();
            }else if (projectName.equals("lvs")){
                item.setQualityDefectCode("5001");
                List<BaseQualityInspectionItem> itemList = itemService.selectBaseQualityInspectionItemList(item);
                qualityDefectCode = itemList.get(0).getQualityDefectCode();
                qualityDefectName = itemList.get(0).getQualityDefectName();
            }else if (projectName.equals("ttl")){
                item.setQualityDefectCode("5003");
                List<BaseQualityInspectionItem> itemList = itemService.selectBaseQualityInspectionItemList(item);
                qualityDefectCode = itemList.get(0).getQualityDefectCode();
                qualityDefectName = itemList.get(0).getQualityDefectName();
            }
            qualityInspection.setQualityDefectCode(qualityDefectCode);
            qualityInspection.setQualityDefectName(qualityDefectName);
            qualityInspection.setTreatmentMeasure("1");
            qualityInspection.setProcessResult("返修合格");
            qualityInspection.setReworkNumber(1L);
            qualityInspection.setFinishTime(DateUtils.getNowDate());
            qualityInspection.setUpdatedBy(qualityInspection.getInspectorCode());
            qualityInspection.setUpdatedTime(DateUtils.getNowDate());
            qualityInspectionService.insertReportQualityInspection(qualityInspection);
        }
    }

}
