package com.zksy.web.controller.gasbasic;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.base.domain.PipeRepairRecord;
import com.zksy.base.dto.RepairRecordPageInDTO;
import com.zksy.base.service.PipeRepairRecordService;
import com.zksy.common.annotation.Anonymous;
import com.zksy.common.annotation.Log;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/api/repair-record")
@Api(tags = "燃气管网维修记录")
public class GasRepairRecordController {

    @Autowired
    private PipeRepairRecordService service;

    @Autowired
    private com.zksy.base.mapper.PipeNetworkBaseMapper pipeNetworkBaseMapper;

    @GetMapping("/stats")
    @ApiOperation("维修统计+趋势")
    @Anonymous
    public AjaxResult stats() {
        java.util.List<com.zksy.base.domain.PipeRepairRecord> all = service.list();
        java.util.Map<String, Object> result = new java.util.LinkedHashMap<>();

        // 维修统计 (按类型)
        String[] typeNames = {"抢修","计划维修","防腐层修复","管件更换","焊缝修补","阀门维修"};
        String[] colors = {"#e63946","#457b9d","#f77f00","#2a9d8f","#6c757d","#b08968"};
        java.util.List<java.util.Map<String, Object>> typeStats = new java.util.ArrayList<>();
        for (int i = 0; i < typeNames.length; i++) {
            int idx = i + 1;
            long cnt = all.stream().filter(r -> r.getRepairType() != null && String.valueOf(idx).equals(r.getRepairType())).count();
            java.util.Map<String, Object> m = new java.util.LinkedHashMap<>();
            m.put("name", typeNames[i]); m.put("value", cnt); m.put("color", colors[i]);
            typeStats.add(m);
        }
        result.put("typeStats", typeStats);

        // 维修趋势 (近6月, 按压力等级)
        java.time.LocalDate today = java.time.LocalDate.now();
        String[] months = new String[6];
        int[] highData = new int[6], mediumData = new int[6], lowData = new int[6];
        for (int i = 0; i < 6; i++) {
            java.time.LocalDate m = today.minusMonths(5 - i);
            months[i] = m.getMonthValue() + "月";
        }
        java.util.Map<String, String> levelMap = new java.util.LinkedHashMap<>();
        pipeNetworkBaseMapper.selectList(null).forEach(n -> levelMap.put(n.getNetworkId(), n.getNetworkLevel()));
        for (com.zksy.base.domain.PipeRepairRecord r : all) {
            if (r.getRepairDate() == null) continue;
            int mDiff = (today.getYear() - r.getRepairDate().getYear()) * 12 + today.getMonthValue() - r.getRepairDate().getMonthValue();
            int idx = 5 - mDiff;
            if (idx < 0 || idx >= 6) continue;
            String lv = levelMap.getOrDefault(r.getNetworkId(), "medium");
            if ("high".equals(lv)) highData[idx]++;
            else if ("low".equals(lv)) lowData[idx]++;
            else mediumData[idx]++;
        }
        java.util.Map<String, Object> trend = new java.util.LinkedHashMap<>();
        trend.put("months", months); trend.put("high", highData);
        trend.put("medium", mediumData); trend.put("low", lowData);
        result.put("trend", trend);

        return AjaxResult.success(result);
    }

    @GetMapping("/findByPage")
    @ApiOperation("维修记录分页查询")
    @Anonymous
    public AjaxResult findByPage(RepairRecordPageInDTO dto) {
        Page<PipeRepairRecord> page = service.findByPage(dto);
        return AjaxResult.success(page);
    }

    @GetMapping("/getById/{id}")
    @ApiOperation("根据ID查询维修记录")
    @Anonymous
    public AjaxResult getById(@PathVariable String id) {
        PipeRepairRecord entity = service.getById(id);
        return entity != null ? AjaxResult.success(entity) : AjaxResult.error("维修记录不存在");
    }

    @GetMapping("/list-by-network/{networkId}")
    @ApiOperation("按管网ID查询历史维修记录")
    @Anonymous
    public AjaxResult listByNetworkId(@PathVariable String networkId) {
        return AjaxResult.success(service.listByNetworkId(networkId));
    }

    @PostMapping("/save")
    @ApiOperation("新增维修记录")
    @Log(title = "新增维修记录", businessType = BusinessType.INSERT)
    public AjaxResult save(@RequestBody PipeRepairRecord entity) {
        entity.setCreateTime(LocalDateTime.now());
        boolean saved = service.save(entity);
        return saved ? AjaxResult.success("新增成功", saved) : AjaxResult.error("新增失败");
    }

    @PutMapping("/updateById")
    @ApiOperation("修改维修记录")
    @Log(title = "修改维修记录", businessType = BusinessType.UPDATE)
    public AjaxResult updateById(@RequestBody PipeRepairRecord entity) {
        boolean updated = service.updateById(entity);
        return updated ? AjaxResult.success("修改成功", updated) : AjaxResult.error("修改失败");
    }

    @DeleteMapping("/deleteById")
    @ApiOperation("删除维修记录")
    @Log(title = "删除维修记录", businessType = BusinessType.DELETE)
    public AjaxResult deleteById(@RequestParam String id) {
        boolean deleted = service.removeById(id);
        return deleted ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }
}
