package org.jeecg.modules.api.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.api.model.HandleDeviceData;
import org.jeecg.modules.regular.entity.RegularInput;
import org.jeecg.modules.workOrder.entity.OperationRecord;
import org.jeecg.modules.workOrder.entity.WorkRecord;
import org.jeecg.modules.workOrder.mapper.OperationRecordMapper;
import org.jeecg.modules.workOrder.mapper.WorkRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * 手持机上传测量数据解析处理
 */
@Slf4j
@Service
public class HandleDeviceDataConvertService {

    @Autowired
    private WorkRecordMapper workRecordMapper;
    @Autowired
    private OperationRecordMapper operationRecordMapper;

    @Transactional(rollbackFor = Exception.class)
    public Boolean handleDataMessage(List<HandleDeviceData> handleDeviceDataList) throws Exception {
        if (handleDeviceDataList.isEmpty())
            return false;
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        for (HandleDeviceData handleDeviceData:handleDeviceDataList) {
            if (StringUtils.isBlank(handleDeviceData.getData())) { // 空数据直接跳过
                throw new Exception(handleDeviceData.getRecordId()+"测量数据为空！");
            }
            //查找workRecord
            WorkRecord workRecord = workRecordMapper.selectById(handleDeviceData.getRecordId());
            if (workRecord == null) {
                throw new Exception(handleDeviceData.getRecordId()+"未找到工单测量项！");
            }

            // ⭐ 如果已有 numericValue，自动 again
            if (workRecord.getNowWay() == 1 &&
                    workRecord.getNumericValue() != null && !workRecord.getNumericValue().isEmpty()) {

                // 旧记录置为历史
                workRecord.setNowWay(0);
                workRecordMapper.updateById(workRecord);

                // 复制生成新记录
                WorkRecord newRecord = new WorkRecord();
                BeanUtil.copyProperties(workRecord, newRecord);

                newRecord.setId(null);
                newRecord.setCollectNum(workRecord.getCollectNum() + 1);
                newRecord.setNowWay(1);
                newRecord.setNumericValue(null);

                workRecordMapper.insert(newRecord);

                // ⭐ 使用新记录继续下面更新逻辑
                workRecord = newRecord;
            }else {
                // 第一次测量时同时将作业详情的自检人赋值
                OperationRecord pop = operationRecordMapper.findByOrderAndInputId(workRecord.getWorkOrder(), workRecord.getRegularInputId());
                if (pop != null) {
                    pop.setSelfInspection(loginUser.getRealname());
                }
                operationRecordMapper.updateById(pop);
            }

            workRecord.setInspector(loginUser.getRealname());
            workRecord.setNumericValue(new BigDecimal(handleDeviceData.getData()).setScale(2, RoundingMode.HALF_UP).toString());
            workRecord.setUnit(handleDeviceData.getUnit());
            workRecord.setInspecTime(DateUtils.parseDate(handleDeviceData.getDateTime(), "yyyy-MM-dd HH:mm:ss"));
            workRecordMapper.updateById(workRecord);
        }
        return true;
    }
}
