package com.aegis.web.controller.emergency.duty;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aegis.common.annotation.Log;
import com.aegis.common.core.controller.BaseController;
import com.aegis.common.core.domain.AjaxResult;
import com.aegis.common.core.page.TableDataInfo;
import com.aegis.common.enums.BusinessType;
import com.aegis.emergency.alert.domain.DutyAlert;
import com.aegis.emergency.alert.domain.DutyAlertTransfer;
import com.aegis.emergency.alert.domain.DutyAlertConvert;
import com.aegis.emergency.alert.service.DutyAlertService;
import com.aegis.emergency.alert.service.DutyAlertLogService;
import com.aegis.emergency.alert.service.DutyAlertTransferService;
import com.aegis.emergency.alert.service.DutyAlertConvertService;
import com.aegis.emergency.alert.domain.DutyAlertLog;

/**
 * 警情Controller
 * 
 * @author aegis
 */
@RestController
@RequestMapping("/duty/alerts")
public class DutyAlertController extends BaseController {

    @Autowired
    private DutyAlertService dutyAlertService;

    @Autowired
    private DutyAlertLogService dutyAlertLogService;

    @Autowired
    private DutyAlertTransferService dutyAlertTransferService;

    @Autowired
    private DutyAlertConvertService dutyAlertConvertService;

    /**
     * 查询警情列表
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:list')")
    @GetMapping("/list")
    public TableDataInfo list(DutyAlert condition) {
        startPage();
        List<DutyAlert> list = dutyAlertService.listByCondition(condition);
        
        // 如果列表为空，直接返回
        if (list.isEmpty()) {
            return getDataTable(list);
        }
        
        // 提取所有警情ID
        List<Long> alertIds = list.stream()
            .map(DutyAlert::getId)
            .collect(Collectors.toList());
        
        // 批量查询转警记录（一次查询，无循环）
        Map<Long, DutyAlertTransfer> transferMap = 
            dutyAlertTransferService.getLatestByAlertIds(alertIds);
        
        // 批量查询转事件记录（一次查询，无循环）
        Map<Long, DutyAlertConvert> convertMap = 
            dutyAlertConvertService.getLatestByAlertIds(alertIds);
        
        // 在内存中组装数据
        for (DutyAlert alert : list) {
            alert.setTransferRecord(transferMap.get(alert.getId()));
            alert.setConvertRecord(convertMap.get(alert.getId()));
        }
        
        return getDataTable(list);
    }

    /**
     * 根据ID查询警情
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        DutyAlert alert = dutyAlertService.getById(id);
        if (alert == null) {
            return error("警情不存在或已删除");
        }
        return success(alert);
    }

    /**
     * 根据警情编号查询警情
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:query')")
    @GetMapping("/no/{alertNo}")
    public AjaxResult getByAlertNo(@PathVariable String alertNo) {
        DutyAlert alert = dutyAlertService.getByAlertNo(alertNo);
        if (alert == null) {
            return error("警情不存在或已删除");
        }
        return success(alert);
    }

    /**
     * 新增警情
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:add')")
    @Log(title = "警情管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DutyAlert alert) {
        return toAjax(dutyAlertService.save(alert));
    }

    /**
     * 修改警情
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:edit')")
    @Log(title = "警情管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DutyAlert alert) {
        return toAjax(dutyAlertService.updateById(alert));
    }

    /**
     * 删除警情（支持批量）
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:remove')")
    @Log(title = "警情管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        boolean allSuccess = true;
        for (Long id : ids) {
            allSuccess &= dutyAlertService.removeById(id);
        }
        return toAjax(allSuccess);
    }

    /**
     * 根据警情ID查询操作日志
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:query')")
    @GetMapping("/{id}/logs")
    public AjaxResult getLogs(@PathVariable Long id) {
        List<DutyAlertLog> logs = dutyAlertLogService.listByAlertId(id);
        return success(logs);
    }

    /**
     * 提交警情（从草稿状态变为已接警状态）
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:edit')")
    @Log(title = "警情管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/submit")
    public AjaxResult submit(@PathVariable Long id, @RequestBody(required = false) DutyAlert alert) {
        return toAjax(dutyAlertService.submitAlert(id, alert));
    }

    /**
     * 关闭警情（将状态变为已关闭）
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:edit')")
    @Log(title = "警情管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/close")
    public AjaxResult close(@PathVariable Long id) {
        return toAjax(dutyAlertService.closeAlert(id));
    }

    /**
     * 转警（提交转警申请）
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:transfer')")
    @Log(title = "警情管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/transfer")
    public AjaxResult transfer(@PathVariable Long id, @RequestBody DutyAlertTransfer transfer) {
        if (transfer == null) {
            return error("转警信息不能为空");
        }
        transfer.setAlertId(id);
        boolean success = dutyAlertTransferService.applyTransfer(transfer);
        if (success) {
            return success("转警申请已提交，等待审核");
        } else {
            return error("转警申请提交失败");
        }
    }

    /**
     * 转事件（提交转事件申请）
     */
    @PreAuthorize("@ss.hasPermi('duty:alert:convert')")
    @Log(title = "警情管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/convert")
    public AjaxResult convert(@PathVariable Long id, @RequestBody DutyAlertConvert convert) {
        if (convert == null) {
            return error("转事件信息不能为空");
        }
        convert.setAlertId(id);
        boolean success = dutyAlertConvertService.applyConvert(convert);
        if (success) {
            // 判断是否需要审核
            DutyAlert alert = dutyAlertService.getById(id);
            if (alert != null && Boolean.TRUE.equals(convert.getReviewRequired())) {
                return success("转事件申请已提交，等待审核");
            } else {
                return success("转事件申请已提交");
            }
        } else {
            return error("转事件申请提交失败");
        }
    }
}