package com.zg.project.wisdom.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageHelper;
import com.zg.project.wisdom.domain.dto.*;
import com.zg.project.wisdom.domain.vo.PcodeQtyVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zg.framework.aspectj.lang.annotation.Log;
import com.zg.framework.aspectj.lang.enums.BusinessType;
import com.zg.project.wisdom.domain.RkInfo;
import com.zg.project.wisdom.service.IRkInfoService;
import com.zg.framework.web.controller.BaseController;
import com.zg.framework.web.domain.AjaxResult;
import com.zg.common.utils.poi.ExcelUtil;
import com.zg.framework.web.page.TableDataInfo;

/**
 * 库存单据主Controller
 * 
 * @author zg
 * @date 2025-05-28
 */
@RestController
@RequestMapping("/wisdom/stock")
public class RkInfoController extends BaseController
{
    @Autowired
    private IRkInfoService rkInfoService;


    /**
     * 查询出库，借料，待审批，撤销出入库单据主列表
     */
//    @PreAuthorize("@ss.hasPermi('wisdom:stock:list')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody RkInfoQueryDTO rkInfo) {
        PageHelper.startPage(rkInfo.getPageNum(), rkInfo.getPageSize());
        List<RkInfo> list = rkInfoService.selectRkInfoList(rkInfo);
        return getDataTable(list);
    }

//    @PreAuthorize("@ss.hasPermi('wisdom:stock:stat')")
    @GetMapping("/pcode/{pcode}")
    public AjaxResult listRkInfoByPcode(@PathVariable String pcode) {
        List<RkInfo> rows = rkInfoService.listRkInfoByPcode(pcode);
        return AjaxResult.success(rows);
    }


    @ApiOperation("按单据分组（bill_no）列表：若存在出库则同时返回 bill_no_ck")
    @PreAuthorize("@ss.hasPermi('wisdom:stock:list')")
    @PostMapping("/bill/groups")
    public TableDataInfo billGroups(@RequestBody RkInfoQueryDTO query) {
        // 分页
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        // 查询
        List<RkInfo> rows = rkInfoService.selectGroupedByBill(query);

        return getDataTable(rows);
    }

    /**
     * 导出库存单据主列表
     */
    @PreAuthorize("@ss.hasPermi('wisdom:stock:export')")
    @Log(title = "库存单据主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RkInfo rkInfo)
    {
        List<RkInfo> list = rkInfoService.selectRkInfoList(rkInfo);
        ExcelUtil<RkInfo> util = new ExcelUtil<RkInfo>(RkInfo.class);
        util.exportExcel(response, list, "库存单据主数据");
    }

    /**
     * 获取库存单据主详细信息
     */
    @PreAuthorize("@ss.hasPermi('wisdom:stock:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(rkInfoService.selectRkInfoById(id));
    }

    /**
     * 入库操作
     */
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('wisdom:stock:add')")
    @Log(title = "库存单据主", businessType = BusinessType.INSERT)
    public AjaxResult batchAdd(@RequestBody PcRkInfoBatchDTO dto) {
        rkInfoService.batchInsert(dto);
        return AjaxResult.success("提交成功");
    }

    /**
     * 修改库存单据主
     */
    @PreAuthorize("@ss.hasPermi('wisdom:stock:edit')")
    @Log(title = "库存单据主", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult edit(@RequestBody RkInfo rkInfo)
    {
        return toAjax(rkInfoService.updateRkInfo(rkInfo));
    }

    /**
     * 删除库存单据主
     */
    @PreAuthorize("@ss.hasPermi('wisdom:stock:remove')")
    @Log(title = "库存单据主", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(rkInfoService.deleteRkInfoByIds(ids));
    }

    /**
     * 库龄超过20天统计
     * @return
     */
    @GetMapping("/warning/stock/over20")
    @PreAuthorize("@ss.hasPermi('wisdom:stock:warning')")
    public AjaxResult getOverdueStockTopList() {
        int total = rkInfoService.countOverdueStock();
        List<RkInfo> list = rkInfoService.selectTopOverdueStock(20);
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("list", list);
        return AjaxResult.success(result);
    }

    /**
     * App撤销出库
     * @param
     * @return
     */
    @PutMapping("/deleteByCkBillNo")
    @PreAuthorize("@ss.hasPermi('wisdom:stock:deleteByBillNo')")
    public AjaxResult deleteByCkBillNo(@RequestBody Map<String, String> body) {
        String billNoCk = body.get("billNoCk");
        if (billNoCk == null || billNoCk.trim().isEmpty()) {
            return AjaxResult.error("参数错误，缺少出库单据号（billNoCk）");
        }

        int result = rkInfoService.deleteByCkBillNo(billNoCk);
        return result > 0
                ? AjaxResult.success("出库单据: " + billNoCk + " 撤销成功")
                : AjaxResult.error("撤销失败，出库单据: " + billNoCk + " 不存在或已处理");
    }

    /**
     * 根据主键ID撤销入库
     */
    @PostMapping("/cancel")
    @PreAuthorize("@ss.hasPermi('wisdom:stock:deleteByBillNo')")
    public AjaxResult deleteById(@RequestBody RkCancelDTO dto) {
        rkInfoService.deleteRkInfoById(dto);
        return AjaxResult.success("撤销成功");
    }

    /**
     * 根据主键ID撤销出库
     */
    @PostMapping("/cancelById/{id}")
    @PreAuthorize("@ss.hasPermi('wisdom:stock:deleteByBillNo')")
    public AjaxResult cancelOutStockById(@PathVariable Long id) {
        rkInfoService.cancelOutStockById(id);
        return AjaxResult.success("撤销出库成功");
    }


    /**
     * 根据主键id进行删除
     * 出入库撤销记录删除
     */
    @PostMapping("/deleteByIds")
    @PreAuthorize("@ss.hasPermi('wisdom:stock:deleteById')")
    public AjaxResult deleteByIds(@RequestBody Long[] ids) {
        return AjaxResult.success(rkInfoService.deleteRkInfoByIds(ids));
    }

    /**
     * 根据ids恢复出库或入库
     */
    @PostMapping("/revertByIds")
    @PreAuthorize("@ss.hasPermi('wisdom:stock:deleteById')")
    public AjaxResult revertByIds(@RequestBody Long[] ids) {
        rkInfoService.revertByIds(ids);
        return AjaxResult.success();
    }

    /**
     * 出库操作
     * @param
     * @return
     */
    @PreAuthorize("@ss.hasPermi('wisdom:outbound:add')")
    @Log(title = "库存单据主", businessType = BusinessType.UPDATE)
    @PutMapping("/outStock")
    public AjaxResult doOutStock(@RequestBody StockOutDTO dto) {
        return toAjax(rkInfoService.batchOutStock(dto));
    }

    /**
     * 还料入库
     * @param
     * @return
     */
    @Log(title = "还料入库", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('wisdom:outbound:add')")
    @PostMapping("/refund")
    public AjaxResult refundMaterial(@RequestBody RefundRequestDTO dto) {
        return toAjax(rkInfoService.refundMaterial(dto));
    }

    /**
     * 配送出库单据查询
     * @param
     * @return
     */
    @Log(title = "配送出库单据查询", businessType = BusinessType.OTHER)
    @GetMapping("/delivery")
    public AjaxResult listAllForDelivery(RkInfo query) {
        List<RkInfo> list = rkInfoService.selectDeliveryAll(query);
        return AjaxResult.success(list);
    }
}
