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

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.requisition.assembler.RequisitionAssembler;
import com.aegis.resource.requisition.assembler.RequisitionAgreementAssembler;
import com.aegis.resource.requisition.assembler.RequisitionCompensationAssembler;
import com.aegis.resource.requisition.domain.Requisition;
import com.aegis.resource.requisition.domain.RequisitionAgreement;
import com.aegis.resource.requisition.domain.RequisitionCompensation;
import com.aegis.resource.requisition.dto.RequisitionDTO;
import com.aegis.resource.requisition.dto.RequisitionAgreementDTO;
import com.aegis.resource.requisition.dto.RequisitionCompensationDTO;
import com.aegis.resource.requisition.service.IResourceRequisitionService;

/**
 * 征用申请Controller
 * 
 * @author aegis
 */
@RestController
@RequestMapping("/resources/requisitions")
public class ResourceRequisitionController extends BaseController {

    @Autowired
    private IResourceRequisitionService requisitionService;

    /**
     * 查询征用申请列表
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:list')")
    @GetMapping("/list")
    public TableDataInfo list(Requisition requisition) {
        startPage();
        List<Requisition> list = requisitionService.listRequisitions(requisition);
        return getDataTable(list);
    }

    /**
     * 根据队伍ID查询征用申请列表
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:list')")
    @GetMapping("/team/{teamId}")
    public AjaxResult listByTeam(@PathVariable Long teamId) {
        List<Requisition> list = requisitionService.listRequisitionsByTeamId(teamId);
        return success(list);
    }

    /**
     * 根据ID获取征用申请详情
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        Requisition requisition = requisitionService.getRequisitionById(id);
        return success(RequisitionAssembler.toDTO(requisition));
    }

    /**
     * 新增征用申请
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:add')")
    @Log(title = "征用管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody RequisitionDTO dto) {
        if (!requisitionService.isRequisitionNoUnique(dto.getRequisitionNo(), null)) {
            return error("新增征用申请失败，征用编号已存在");
        }
        Requisition requisition = RequisitionAssembler.toDomain(dto);
        return toAjax(requisitionService.createRequisition(requisition));
    }

    /**
     * 修改征用申请
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "征用管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody RequisitionDTO dto) {
        if (!requisitionService.isRequisitionNoUnique(dto.getRequisitionNo(), dto.getId())) {
            return error("修改征用申请失败，征用编号已存在");
        }
        Requisition requisition = RequisitionAssembler.toDomain(dto);
        return toAjax(requisitionService.modifyRequisition(requisition));
    }

    /**
     * 删除征用申请
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:remove')")
    @Log(title = "征用管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(requisitionService.removeRequisitions(ids));
    }

    /**
     * 审批通过（draft → approved）
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:approve')")
    @Log(title = "征用管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/approve")
    public AjaxResult approve(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        String comment = StringUtils.isNotNull(params.get("comment")) ? params.get("comment").toString() : null;
        return toAjax(requisitionService.approveRequisition(id, comment));
    }

    /**
     * 审批驳回（draft → rejected）
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:approve')")
    @Log(title = "征用管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/reject")
    public AjaxResult reject(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        String comment = StringUtils.isNotNull(params.get("comment")) ? params.get("comment").toString() : null;
        return toAjax(requisitionService.rejectRequisition(id, comment));
    }

    /**
     * 开始征用（approved → active，置队伍 busy）
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "征用管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/start")
    public AjaxResult start(@PathVariable Long id) {
        return toAjax(requisitionService.startRequisition(id));
    }

    /**
     * 结束征用（active → ended，置队伍 available）
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "征用管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/end")
    public AjaxResult end(@PathVariable Long id) {
        return toAjax(requisitionService.endRequisition(id));
    }

    /**
     * 重新提交（rejected → approved）
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "征用管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/resubmit")
    public AjaxResult resubmit(@PathVariable Long id) {
        return toAjax(requisitionService.resubmitRequisition(id));
    }

    /**
     * 查询征用协议列表
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:query')")
    @GetMapping("/{id}/agreements")
    public TableDataInfo listAgreements(@PathVariable Long id, RequisitionAgreement agreement) {
        agreement.setRequisitionId(id);
        startPage();
        List<RequisitionAgreement> list = requisitionService.listRequisitionAgreements(agreement);
        return getDataTable(list);
    }

    /**
     * 根据ID获取协议详情
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:query')")
    @GetMapping("/agreements/{agreementId}")
    public AjaxResult getAgreementInfo(@PathVariable Long agreementId) {
        RequisitionAgreement agreement = requisitionService.getRequisitionAgreementById(agreementId);
        return success(RequisitionAgreementAssembler.toDTO(agreement));
    }

    /**
     * 新增征用协议
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "征用协议管理", businessType = BusinessType.INSERT)
    @PostMapping("/{id}/agreements")
    public AjaxResult addAgreement(@PathVariable Long id, @Validated @RequestBody RequisitionAgreementDTO dto) {
        dto.setRequisitionId(id);
        RequisitionAgreement agreement = RequisitionAgreementAssembler.toDomain(dto);
        return toAjax(requisitionService.createRequisitionAgreement(agreement));
    }

    /**
     * 修改征用协议
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "征用协议管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/agreements/{agreementId}")
    public AjaxResult editAgreement(@PathVariable Long id, @PathVariable Long agreementId, @Validated @RequestBody RequisitionAgreementDTO dto) {
        dto.setId(agreementId);
        dto.setRequisitionId(id);
        RequisitionAgreement agreement = RequisitionAgreementAssembler.toDomain(dto);
        return toAjax(requisitionService.modifyRequisitionAgreement(agreement));
    }

    /**
     * 删除征用协议
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "征用协议管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}/agreements/{agreementId}")
    public AjaxResult removeAgreement(@PathVariable Long id, @PathVariable Long agreementId) {
        return toAjax(requisitionService.removeRequisitionAgreement(agreementId));
    }

    /**
     * 查询补偿记录列表
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:query')")
    @GetMapping("/{id}/compensations")
    public TableDataInfo listCompensations(@PathVariable Long id, RequisitionCompensation compensation) {
        compensation.setRequisitionId(id);
        startPage();
        List<RequisitionCompensation> list = requisitionService.listRequisitionCompensations(compensation);
        return getDataTable(list);
    }

    /**
     * 根据ID获取补偿记录详情
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:query')")
    @GetMapping("/compensations/{compensationId}")
    public AjaxResult getCompensationInfo(@PathVariable Long compensationId) {
        RequisitionCompensation compensation = requisitionService.getRequisitionCompensationById(compensationId);
        return success(RequisitionCompensationAssembler.toDTO(compensation));
    }

    /**
     * 新增补偿记录
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "补偿管理", businessType = BusinessType.INSERT)
    @PostMapping("/{id}/compensations")
    public AjaxResult addCompensation(@PathVariable Long id, @Validated @RequestBody RequisitionCompensationDTO dto) {
        dto.setRequisitionId(id);
        RequisitionCompensation compensation = RequisitionCompensationAssembler.toDomain(dto);
        return toAjax(requisitionService.createRequisitionCompensation(compensation));
    }

    /**
     * 修改补偿记录
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "补偿管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/compensations/{compensationId}")
    public AjaxResult editCompensation(@PathVariable Long id, @PathVariable Long compensationId, @Validated @RequestBody RequisitionCompensationDTO dto) {
        dto.setId(compensationId);
        dto.setRequisitionId(id);
        RequisitionCompensation compensation = RequisitionCompensationAssembler.toDomain(dto);
        return toAjax(requisitionService.modifyRequisitionCompensation(compensation));
    }

    /**
     * 删除补偿记录
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "补偿管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}/compensations/{compensationId}")
    public AjaxResult removeCompensation(@PathVariable Long id, @PathVariable Long compensationId) {
        return toAjax(requisitionService.removeRequisitionCompensation(compensationId));
    }

    /**
     * 结算补偿（pending → settled）
     */
    @PreAuthorize("@ss.hasPermi('resource:requisition:edit')")
    @Log(title = "补偿管理", businessType = BusinessType.UPDATE)
    @PostMapping("/compensations/{compensationId}/settle")
    public AjaxResult settleCompensation(@PathVariable Long compensationId, @RequestBody Map<String, Object> params) {
        String invoiceNo = StringUtils.isNotNull(params.get("invoiceNo")) ? params.get("invoiceNo").toString() : null;
        java.util.Date paidAt = null;
        if (params.get("paidAt") != null) {
            if (params.get("paidAt") instanceof String) {
                try {
                    paidAt = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) params.get("paidAt"));
                } catch (Exception e) {
                    return error("支付时间格式错误");
                }
            } else if (params.get("paidAt") instanceof Long) {
                paidAt = new java.util.Date((Long) params.get("paidAt"));
            } else if (params.get("paidAt") instanceof java.util.Date) {
                paidAt = (java.util.Date) params.get("paidAt");
            }
        }
        if (paidAt == null) {
            paidAt = new java.util.Date();
        }
        return toAjax(requisitionService.settleCompensation(compensationId, invoiceNo, paidAt));
    }
}