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

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.procurement.assembler.ProcurementAssembler;
import com.aegis.resource.procurement.assembler.ProcurementItemAssembler;
import com.aegis.resource.procurement.assembler.ProcurementQuoteAssembler;
import com.aegis.resource.procurement.domain.Procurement;
import com.aegis.resource.procurement.domain.ProcurementItem;
import com.aegis.resource.procurement.domain.ProcurementQuote;
import com.aegis.resource.procurement.dto.ProcurementDTO;
import com.aegis.resource.procurement.dto.ProcurementItemDTO;
import com.aegis.resource.procurement.dto.ProcurementQuoteDTO;
import com.aegis.resource.procurement.service.IResourceProcurementService;

/**
 * 采购申请Controller
 * 
 * @author aegis
 */
@RestController
@RequestMapping("/resources/procurement")
public class ResourceProcurementController extends BaseController {

    @Autowired
    private IResourceProcurementService procurementService;

    /**
     * 查询采购申请列表
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:list')")
    @GetMapping("/list")
    public TableDataInfo list(Procurement procurement) {
        startPage();
        List<Procurement> list = procurementService.listProcurements(procurement);
        return getDataTable(list);
    }

    /**
     * 根据ID获取采购申请详情
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        Procurement procurement = procurementService.getProcurementById(id);
        return success(ProcurementAssembler.toDTO(procurement));
    }

    /**
     * 新增采购申请
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:add')")
    @Log(title = "采购管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ProcurementDTO dto) {
        if (!procurementService.isProcurementNoUnique(dto.getProcurementNo(), null)) {
            return error("新增采购申请'" + dto.getTitle() + "'失败，采购编号已存在");
        }
        Procurement procurement = ProcurementAssembler.toDomain(dto);
        return toAjax(procurementService.createProcurement(procurement));
    }

    /**
     * 修改采购申请
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:edit')")
    @Log(title = "采购管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ProcurementDTO dto) {
        if (!procurementService.isProcurementNoUnique(dto.getProcurementNo(), dto.getId())) {
            return error("修改采购申请'" + dto.getTitle() + "'失败，采购编号已存在");
        }
        Procurement procurement = ProcurementAssembler.toDomain(dto);
        return toAjax(procurementService.modifyProcurement(procurement));
    }

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

    /**
     * 提交采购申请（draft → submitted）
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:edit')")
    @Log(title = "采购管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/submit")
    public AjaxResult submit(@PathVariable Long id) {
        return toAjax(procurementService.submitProcurement(id));
    }

    /**
     * 审核通过（submitted → approved）
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement: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(procurementService.approveProcurement(id, comment));
    }

    /**
     * 审核驳回（submitted → rejected）
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement: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(procurementService.rejectProcurement(id, comment));
    }

    /**
     * 重新提交（rejected → submitted）
     * 驳回后修改完成，直接提交审核
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:edit')")
    @Log(title = "采购管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/resubmit")
    public AjaxResult resubmit(@PathVariable Long id) {
        return toAjax(procurementService.resubmitProcurement(id));
    }

    /**
     * 确认中标供应商（approved → in_progress）
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:edit')")
    @Log(title = "采购管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/award")
    public AjaxResult award(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        Long quoteId = params.get("quoteId") != null ? Long.valueOf(params.get("quoteId").toString()) : null;
        if (quoteId == null) {
            return error("报价ID不能为空");
        }
        return toAjax(procurementService.awardProcurement(id, quoteId));
    }

    /**
     * 采购入库（in_progress → received）
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:edit')")
    @Log(title = "采购管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/receive")
    public AjaxResult receive(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        Long warehouseId = params.get("warehouseId") != null ? Long.valueOf(params.get("warehouseId").toString()) : null;
        return toAjax(procurementService.receiveProcurement(id, warehouseId));
    }

    /**
     * 查询采购明细列表
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:query')")
    @GetMapping("/{id}/items")
    public TableDataInfo listItems(@PathVariable Long id, ProcurementItem item) {
        item.setProcurementId(id);
        startPage();
        List<ProcurementItem> list = procurementService.listProcurementItems(item);
        return getDataTable(list);
    }

    /**
     * 根据ID获取采购明细详情
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:query')")
    @GetMapping("/items/{itemId}")
    public AjaxResult getItemInfo(@PathVariable Long itemId) {
        ProcurementItem item = procurementService.getProcurementItemById(itemId);
        return success(ProcurementItemAssembler.toDTO(item));
    }

    /**
     * 新增采购明细
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:edit')")
    @Log(title = "采购明细管理", businessType = BusinessType.INSERT)
    @PostMapping("/{id}/items")
    public AjaxResult addItem(@PathVariable Long id, @Validated @RequestBody ProcurementItemDTO dto) {
        dto.setProcurementId(id);
        ProcurementItem item = ProcurementItemAssembler.toDomain(dto);
        return toAjax(procurementService.createProcurementItem(item));
    }

    /**
     * 修改采购明细
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:edit')")
    @Log(title = "采购明细管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/items/{itemId}")
    public AjaxResult editItem(@PathVariable Long id, @PathVariable Long itemId, @Validated @RequestBody ProcurementItemDTO dto) {
        dto.setId(itemId);
        dto.setProcurementId(id);
        ProcurementItem item = ProcurementItemAssembler.toDomain(dto);
        return toAjax(procurementService.modifyProcurementItem(item));
    }

    /**
     * 删除采购明细
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:edit')")
    @Log(title = "采购明细管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}/items/{itemId}")
    public AjaxResult removeItem(@PathVariable Long id, @PathVariable Long itemId) {
        return toAjax(procurementService.removeProcurementItem(itemId));
    }

    /**
     * 供应商报价
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:quote')")
    @Log(title = "采购报价管理", businessType = BusinessType.INSERT)
    @PostMapping("/{id}/quote")
    public AjaxResult submitQuote(@PathVariable Long id, @Validated @RequestBody ProcurementQuoteDTO dto) {
        dto.setProcurementId(id);
        ProcurementQuote quote = ProcurementQuoteAssembler.toDomain(dto);
        return toAjax(procurementService.submitQuote(quote));
    }

    /**
     * 查询报价记录（多供应商比价）
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:query')")
    @GetMapping("/{id}/quotes")
    public TableDataInfo listQuotes(@PathVariable Long id, ProcurementQuote quote) {
        quote.setProcurementId(id);
        startPage();
        List<ProcurementQuote> list = procurementService.listProcurementQuotes(quote);
        return getDataTable(list);
    }

    /**
     * 根据ID获取报价详情
     */
    @PreAuthorize("@ss.hasPermi('resource:procurement:query')")
    @GetMapping("/quotes/{quoteId}")
    public AjaxResult getQuoteInfo(@PathVariable Long quoteId) {
        ProcurementQuote quote = procurementService.getProcurementQuoteById(quoteId);
        return success(ProcurementQuoteAssembler.toDTO(quote));
    }
}