package com.aegis.web.controller.resource.equipment;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
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.common.utils.StringUtils;
import com.aegis.resource.equipment.assembler.EquipmentAssembler;
import com.aegis.resource.equipment.domain.Equipment;
import com.aegis.resource.equipment.domain.EquipmentLog;
import com.aegis.resource.equipment.dto.EquipmentDTO;
import com.aegis.resource.equipment.service.IResourceEquipmentService;

/**
 * 装备Controller
 * 
 * @author aegis
 */
@RestController
@RequestMapping("/resources/equipment")
public class ResourceEquipmentController extends BaseController {

    @Autowired
    private IResourceEquipmentService equipmentService;

    /**
     * 查询装备列表
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:list')")
    @GetMapping("/list")
    public TableDataInfo list(Equipment equipment) {
        startPage();
        List<Equipment> list = equipmentService.selectEquipmentList(equipment);
        return getDataTable(list);
    }

    /**
     * 根据ID获取装备详情
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(equipmentService.selectEquipmentById(id));
    }

    /**
     * 根据队伍ID查询装备列表
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:list')")
    @GetMapping("/team/{teamId}")
    public AjaxResult listByTeam(@PathVariable Long teamId) {
        List<Equipment> list = equipmentService.selectEquipmentListByTeamId(teamId);
        return success(list);
    }

    /**
     * 新增装备
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:add')")
    @Log(title = "装备管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody EquipmentDTO equipmentDTO) {
        Equipment equipment = EquipmentAssembler.toDomain(equipmentDTO);
        if (StringUtils.isNotEmpty(equipment.getEquipmentCode()) && !equipmentService.checkEquipmentCodeUnique(equipment)) {
            return error("新增装备'" + equipment.getEquipmentName() + "'失败，装备编码已存在");
        }
        return toAjax(equipmentService.insertEquipment(equipment));
    }

    /**
     * 修改装备
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:edit')")
    @Log(title = "装备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody EquipmentDTO equipmentDTO) {
        Equipment equipment = EquipmentAssembler.toDomain(equipmentDTO);
        if (StringUtils.isNotEmpty(equipment.getEquipmentCode()) && !equipmentService.checkEquipmentCodeUnique(equipment)) {
            return error("修改装备'" + equipment.getEquipmentName() + "'失败，装备编码已存在");
        }
        return toAjax(equipmentService.updateEquipment(equipment));
    }

    /**
     * 删除装备
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:remove')")
    @Log(title = "装备管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(equipmentService.deleteEquipmentByIds(ids));
    }

    /**
     * 分配占用（available → busy）
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:assign')")
    @Log(title = "装备管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/assign")
    public AjaxResult assign(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        Long dispatchId = params.get("dispatchId") != null ? Long.valueOf(params.get("dispatchId").toString()) : null;
        Long eventId = params.get("eventId") != null ? Long.valueOf(params.get("eventId").toString()) : null;
        String remark = StringUtils.isNotNull(params.get("remark")) ? params.get("remark").toString() : null;
        return toAjax(equipmentService.assignEquipment(id, dispatchId, eventId, remark));
    }

    /**
     * 解除占用（busy → available）
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:release')")
    @Log(title = "装备管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/release")
    public AjaxResult release(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        String remark = StringUtils.isNotNull(params.get("remark")) ? params.get("remark").toString() : null;
        return toAjax(equipmentService.releaseEquipment(id, remark));
    }

    /**
     * 送修（available/busy → repair）
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:edit')")
    @Log(title = "装备管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/send-repair")
    public AjaxResult sendRepair(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        String remark = StringUtils.isNotNull(params.get("remark")) ? params.get("remark").toString() : null;
        return toAjax(equipmentService.sendRepair(id, remark));
    }

    /**
     * 修复完成（repair → available）
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:edit')")
    @Log(title = "装备管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/finish-repair")
    public AjaxResult finishRepair(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        String remark = StringUtils.isNotNull(params.get("remark")) ? params.get("remark").toString() : null;
        return toAjax(equipmentService.finishRepair(id, remark));
    }

    /**
     * 报废（→ scrap，终态）
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:edit')")
    @Log(title = "装备管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/scrap")
    public AjaxResult scrap(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        String remark = StringUtils.isNotNull(params.get("remark")) ? params.get("remark").toString() : null;
        return toAjax(equipmentService.scrapEquipment(id, remark));
    }

    /**
     * 查询操作日志
     */
    @PreAuthorize("@ss.hasPermi('resource:equipment:query')")
    @GetMapping("/{id}/logs")
    public TableDataInfo listLogs(@PathVariable Long id, EquipmentLog log) {
        log.setEquipmentId(id);
        startPage();
        List<EquipmentLog> list = equipmentService.selectEquipmentLogList(log);
        return getDataTable(list);
    }
}