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

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.cabinet.entity.Cabinet;
import org.jeecg.modules.cabinet.mapper.CabinetMapper;
import org.jeecg.modules.regular.entity.RegularDetail;
import org.jeecg.modules.regular.entity.RegularInput;
import org.jeecg.modules.regular.mapper.RegularDetailMapper;
import org.jeecg.modules.regular.mapper.RegularInputMapper;
import org.jeecg.modules.toolBorrowingRecord.entity.ToolBorrowingRecord;
import org.jeecg.modules.toolBorrowingRecord.mapper.ToolBorrowingRecordMapper;
import org.jeecg.modules.toolBorrowingRecord.service.IToolBorrowingRecordService;
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.jeecg.modules.workOrder.model.WorkOrderDetailModel;
import org.jeecg.modules.workOrder.service.IOperationRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Description: 工单作业记录
 * @Author: jeecg-boot
 * @Date:   2025-02-20
 * @Version: V1.0
 */
@Service
public class OperationRecordServiceImpl extends ServiceImpl<OperationRecordMapper, OperationRecord> implements IOperationRecordService {

    @Autowired
    private ToolBorrowingRecordMapper toolBorrowingRecordMapper;
    @Autowired
    private CabinetMapper cabinetMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeRecords(Map<Object, Object> records) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        records.forEach((id, state) -> {
            OperationRecord record = baseMapper.selectById(id.toString());
            if(record!=null){
                record.setCheckResult(state.toString());
                record.setSelfInspection(user.getRealname());
                baseMapper.updateById(record);
            }
        });
        return true;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeMutualRecord(Map<Object, Object> records) {
        records.forEach((id, mutual) -> {
            OperationRecord record = baseMapper.selectById(id.toString());
            if(record!=null){
                record.setMutualInspection(mutual.toString());
                baseMapper.updateById(record);
            }
        });
        return true;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeSpecialRecord(Map<Object, Object> records) {
        records.forEach((id, special) -> {
            OperationRecord record = baseMapper.selectById(id.toString());
            if(record!=null){
                record.setSpecialInspection(special.toString());
                baseMapper.updateById(record);
            }
        });
        return true;
    }

    @Autowired
    private OperationRecordMapper operationRecordMapper;
    @Autowired
    private RegularDetailMapper regularDetailMapper;
    @Autowired
    private RegularInputMapper regularInputMapper;
    @Autowired
    private WorkRecordMapper workRecordMapper;
    @Override
    public long queryUncompleteCount(String id) {
        List<WorkOrderDetailModel> detailModels = operationRecordMapper.findByWorkOrderId(id);
        detailModels.forEach(item -> {
            if(item.getMeasure().equals("1")){
                //todo 查询测量项
                String result = "";
                RegularDetail detail = regularDetailMapper.selectById(item.getItemId());
                if(detail != null){
                    List<RegularInput> inputs = regularInputMapper.selectList(new LambdaQueryWrapper<RegularInput>().eq(RegularInput::getDetailId, detail.getId()).isNotNull(RegularInput::getToolId));
                    for(RegularInput input : inputs){
                        WorkRecord record = workRecordMapper.selectOne(new LambdaQueryWrapper<WorkRecord>().eq(WorkRecord::getRegularInputId, input.getId()).eq(WorkRecord::getWorkOrder, id)
                                .orderByDesc(WorkRecord::getCollectNum).last("limit 1"));
                        if(record!=null){
//                            List<Double> values = records.parallelStream().map(record -> Double.parseDouble(record.getNumericValue())).toList();
//                            if(values.size() == 0){
//                                return;
//                            }
//                            Double avg = values.stream().mapToDouble(a -> a).average().getAsDouble();
                            String temp = input.getDataPot() + ":" + record.getNumericValue() + record.getUnit() + "\r\n";
                            result += temp;
                            if (StringUtils.isNotBlank(record.getNumericValue())) {
                                // 是否多次采集
                                item.setCollectNum(record.getCollectNum());
                                item.setRegularInputId(record.getRegularInputId());
                                double value = Double.parseDouble(record.getNumericValue());
                                Double min = input.getMinValue();
                                Double max = input.getMaxValue();
                                item.setResultOverGauge((min == null || value >= min) && (max == null || value <= max));
                            } else {
                                item.setSelfInspection("未测量");
                            }
                        }
                    }
                }
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(result)){
                    item.setCheckResult(result);
                }
            }
        });
        return detailModels.stream().filter(item -> StringUtils.isBlank(item.getCheckResult())).count();
    }

    @Autowired
    private IToolBorrowingRecordService borrowingRecordService;
    @Override
    public long queryUnreturnCount(String id) {
        return toolBorrowingRecordMapper.selectCount(new LambdaQueryWrapper<ToolBorrowingRecord>()
                .eq(ToolBorrowingRecord::getWorkOrder, id).eq(ToolBorrowingRecord::getStatus, 0));
        // 通过工具柜查询方案，现已放弃
        /*long count = 0;
        List<ToolBorrowingRecord> records = toolBorrowingRecordMapper.selectList(new LambdaQueryWrapper<ToolBorrowingRecord>()
                .eq(ToolBorrowingRecord::getWorkOrder, id));
        Cabinet cabinet = cabinetMapper.selectList(new LambdaQueryWrapper<>()).get(0);
        for (ToolBorrowingRecord record : records){
            if(record.getStatus() == 0){
                try{
                    //判断工具是否归还
                    HttpResponse<String> response = Unirest.get("http://" + cabinet.getIpAddress() + ":" + cabinet.getPort() + "/api/Cabinet/isInStock")
                            .header("Content-Type", "application/json")
                            .queryString("toolId", record.getToolId())
                            .asString();
                    String data = response.getBody();
                    JSONObject jsonObject = JSONObject.parseObject(data);
                    if(jsonObject.getInteger("code") == 200){
                        if(jsonObject.getBoolean("data")){
                            borrowingRecordService.returnTool(record.getId());
                        }else{
                            count+=1;
                        }
                    }else{
                        continue;
                    }
                }catch (Exception e){
                    continue;
                }
            }
        }
        return count;*/
    }
}
