package com.yeejoin.equipmanage.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.SaveOutputParameters;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.entity.EquipQrcodeRecord;
import com.yeejoin.equipmanage.common.enums.CheckStatusEnum;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.fegin.IdxFeign;
import com.yeejoin.equipmanage.fegin.McbFeign;
import com.yeejoin.equipmanage.mapper.EquipQrcodeRecordMapper;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificAlarmLogMapper;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api(tags = "设备信息卡Api")
@RequestMapping(value = "/equipInformationCard")
public class EquipInformationCardController {


    @Autowired
    EquipmentSpecificAlarmLogMapper equipmentSpecificAlarmLogMapper;
    @Autowired
    EquipmentSpecificMapper equipmentSpecificMapper;
    @Autowired
    EquipQrcodeRecordMapper equipQrcodeRecordMapper;
    @Autowired
    IdxFeign idxFeign;
    @Autowired
    McbFeign mcbFeign;

    @RequestMapping(value = "/equipOrPatrol",method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "运维信息-设备告警/巡检", notes = "运维信息-设备告警/巡检")
    public ResponseModel getEquipAlarmList(String equipmentId,String type, @RequestParam(value = "current") int pageNum,
                                           @RequestParam(value = "size") int pageSize) {
        HashMap<String, Object> map = new HashMap<>(2);

        List<Map<String, Object>> list = new ArrayList<>();
        Page<Map<String, Object>> page = new Page<Map<String, Object>>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        List<String> idList = new ArrayList<>();
        if (type.equals("alarm")){
            page = equipmentSpecificAlarmLogMapper.getEquipAlarmList(page, equipmentId);
            list = page.getRecords();
        } else if(type.equals("check")){
            page = equipmentSpecificMapper.selectListByPatrolCheck(page, equipmentId);
            list.stream().forEach(e->e.put("is_ok", CheckStatusEnum.getNameByCode(e.get("is_ok").toString())));
        }
        String ids = list.stream().map(map1 -> map1.get("id").toString()).collect(Collectors.joining(","));
        JSONObject  obj= idxFeign.queryDefectByCodes(idList, ids);
        List<JSONObject> jsonObjects = JSONArray.parseArray(JSON.toJSONString(obj.get("result")), JSONObject.class);
        //缺陷对应记录 是否存在上报问题
        if (!ValidationUtil.isEmpty(jsonObjects)){
            list.forEach(e->{
                jsonObjects.forEach(j->{
                    if (e.get("id").toString().equals(j.getString("checkId"))){
                        e.put("reportProblem",j.getString("defectDescribe"));
                        e.put("defectId", j.getString("id"));
                        e.put("defectStatus",j.getString("defectStatus").equals("0")?"未处理":"已处理");
                    }
                });
            });
        }
        map.put("data", list);
        map.put("total", page.getTotal());
        return CommonResponseUtil.success(map);
    }

    @RequestMapping(value = "/mcb",method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "预警记录", notes = "预警记录")
    public ResponseModel getMcbDataList(String equipmentId,int current,int size) {

        JSONObject result = mcbFeign.list(current, size, equipmentId);
        JSONObject jsonObject = result.getJSONObject("result");
        List<JSONObject> records = JSONArray.parseArray(JSON.toJSONString(jsonObject.get("records")), JSONObject.class);


        LambdaQueryWrapper<EquipQrcodeRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipQrcodeRecord::getEquipid,equipmentId);
        List<EquipQrcodeRecord> qrList = equipQrcodeRecordMapper.selectList(wrapper);

        records.forEach(record->{
            qrList.forEach(q->{
                if (q.getSourceId().equals(record.getString("traceId"))){
                    record.put("cleanStatus",q.getCleanTime() == null?"未消除":"已消除");
                    record.put("cleanTime",q.getCleanTime());
                    record.put("cleanReason",q.getCleanReason());
                }
            });
            String cs = "";
            JSONArray list = record.getJSONArray("rectificationProposal");
            for (int i = 0; i < list.size(); i++) {
                if (i != (list.size() - 1)){
                    cs += list.getJSONObject(i).getString("measuresDesc")+",";
                } else {
                    cs += list.getJSONObject(i).getString("measuresDesc");
                }
            }
            record.put("measure",cs);

        });

        HashMap<String, Object> map = new HashMap<>();
        map.put("data", records);
        map.put("total", jsonObject.get("total"));
        return CommonResponseUtil.success(map);
    }




}
