package com.ruoyi.web.base.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.base.domain.ProcureQuotation;
import com.ruoyi.web.base.domain.ProcureQuotationGoods;
import com.ruoyi.web.base.domain.ProcureReceiving;
import com.ruoyi.web.base.domain.ProcureReceivingGoods;
import com.ruoyi.web.base.service.IProcureReceivingGoodsService;
import com.ruoyi.web.base.service.IProcureReceivingService;
import com.ruoyi.web.stock.domain.WarehouseIn;
import com.ruoyi.web.stock.domain.WarehouseInGoods;
import com.ruoyi.web.stock.service.IRoleOrgService;
import com.ruoyi.web.stock.service.IWarehouseInboundService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.success;
import static com.ruoyi.common.utils.MapUtils.convertValue;
import static com.ruoyi.common.utils.SecurityUtils.getUsername;
import static com.ruoyi.web.base.util.NumUtils.generateString;
import static com.ruoyi.web.base.util.NumUtils.substringToInt;

/**
 * <p>
 * 采购入库单 前端控制器
 * </p>
 *
 * @author author
 * @since 2026-02-05
 */
@RestController
@RequestMapping("/procure-receiving")
public class ProcureReceivingController extends BaseController {
    @Autowired
    private IProcureReceivingService procureReceivingService;
    @Autowired
    private IProcureReceivingGoodsService goodsService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IRoleOrgService roleOrgService;

    @Autowired
    private IWarehouseInboundService warehouseInboundService;

    @ApiOperation("获取采购入库单编号")
    @PostMapping("/getReceivingNum")
    public AjaxResult getQuotaNum(HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);

        ProcureReceiving one = procureReceivingService.getOne(new QueryWrapper<ProcureReceiving>().eq("org_id", loginOrgId).orderByDesc("id").last("limit 1"));
        if (ObjectUtils.isEmpty(one)){

            return success(generateString("cg",1));
        }
        String quotationNum = one.getReceivingNum();

        return success(generateString("bj",substringToInt(quotationNum)));

    }

    @ApiOperation("采购入库单添加")
    @PostMapping("/add")
    @Transactional
    public AjaxResult add(@RequestBody ProcureReceiving procureReceiving, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);
        if (procureReceivingService.count(new QueryWrapper<ProcureReceiving>().eq("org_id",loginOrgId).eq("receiving_num", procureReceiving.getReceivingNum())) >0 ){
            throw new Exception("该编号已存在");
        }
        String username = getUsername();
        procureReceiving.setOrgId(loginOrgId);
        procureReceiving.setCreateBy(username);
        List<ProcureReceivingGoods> goods = procureReceiving.getGoods();
        for (ProcureReceivingGoods good : goods) {
            good.setOrgId(loginOrgId);
            good.setCreateBy(username);
            good.setReceivingNum(procureReceiving.getReceivingNum());
            goodsService.save(good);
        }
        //入库存
        List<WarehouseInGoods> inGoods = goods.stream()
                .map(item -> {
                    WarehouseInGoods good = new WarehouseInGoods();
                    good.setGoodsNum(item.getGoodsNum());
                    good.setGoodsName(item.getGoodsName());
                    good.setGoodsSpec(item.getGoodsSpec());
                    good.setGoodsType("");
                    good.setWarehouseNo(item.getWarehouseNo());
                    good.setWarehouseName(item.getWarehouseName());
                    good.setBatchNo(item.getBatch());
                    good.setBaseUnit(item.getBaseUnit());
                    good.setBaseQty(BigDecimal.valueOf(Double.parseDouble(item.getBaseNum())));
                    good.setAssistantUnit(item.getAssUnit());
                    good.setAssistantQty(BigDecimal.valueOf(Double.parseDouble(item.getAssNum())));
                    good.setAmount(BigDecimal.valueOf(Double.parseDouble(item.getAmount())));
                    good.setRemark(item.getRemark());

                    return good;
                })
                .collect(Collectors.toList());
        WarehouseIn warehouseInEntity = new WarehouseIn();
        warehouseInEntity.setSheetDate(procureReceiving.getReceivingDate());
        warehouseInEntity.setProductionType(procureReceiving.getOrderType());
        warehouseInEntity.setTotalAmount(BigDecimal.valueOf(Double.parseDouble(procureReceiving.getTotalAmount())));
        warehouseInEntity.setOrgId(currentOrgId());
        warehouseInEntity.setGoodsList(inGoods);
        warehouseInboundService.submitInbound(warehouseInEntity, getUsername());
        return success(procureReceivingService.save(procureReceiving));
    }

    @ApiOperation("采购入库单修改")
    @PostMapping("/edit")
    @Transactional
    public AjaxResult edit(@RequestBody ProcureReceiving procureReceiving, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);
        if (procureReceivingService.count(new QueryWrapper<ProcureReceiving>().ne("id",procureReceiving.getId()).eq("org_id",loginOrgId).eq("receiving_num", procureReceiving.getReceivingNum())) >0 ){
            throw new Exception("该编号已存在");
        }

        String username = getUsername();
        procureReceiving.setOrgId(loginOrgId);
        procureReceiving.setCreateBy(username);
        List<ProcureReceivingGoods> goods = procureReceiving.getGoods();
        goodsService.remove(new QueryWrapper<ProcureReceivingGoods>().eq("receiving_num",procureReceiving.getReceivingNum()));
        for (ProcureReceivingGoods good : goods) {
            good.setOrgId(loginOrgId);
            good.setCreateBy(username);
            good.setReceivingNum(procureReceiving.getReceivingNum());
            goodsService.save(good);
        }
        procureReceiving.setUpdateBy(username);

        return success(procureReceivingService.updateById(procureReceiving));
    }

    @ApiOperation("采购入库单删除")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        for (String s : ids.split(",")) {
            procureReceivingService.removeById(s);
        }
        return success();
    }

    @ApiOperation("采购入库单列表")
    @PostMapping("/list")
    public AjaxResult listAll( HttpServletRequest request){
        List<ProcureReceiving> org_id = procureReceivingService.list(new QueryWrapper<ProcureReceiving>().eq("org_id", tokenService.getLoginOrgId(request)));
        for (ProcureReceiving procureQuotation : org_id) {
            procureQuotation.setGoods(goodsService.list(new QueryWrapper<ProcureReceivingGoods>().eq("receiving_num",procureQuotation.getReceivingNum())));
        }
        return success(org_id);
    }

    @ApiOperation("采购入库单分页")
    @GetMapping("/page")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize
            , HttpServletRequest request) {
        Page<ProcureReceiving> org_id = procureReceivingService.page(new Page<ProcureReceiving>(pageNum, pageSize), new QueryWrapper<ProcureReceiving>().eq("org_id", tokenService.getLoginOrgId(request)));
        for (ProcureReceiving procureQuotation : org_id.getRecords()) {
            procureQuotation.setGoods(goodsService.list(new QueryWrapper<ProcureReceivingGoods>().eq("receiving_num",procureQuotation.getReceivingNum())));
        }
        return success(org_id);
    }

    @ApiOperation("采购入库单详情")
    @PostMapping("/listById")
    public AjaxResult listById(@RequestBody Map<String, String> paramsMap){
        String id = paramsMap.get("id");
        ProcureReceiving byId = procureReceivingService.getById(id);
        byId.setGoods(goodsService.list(new QueryWrapper<ProcureReceivingGoods>().eq("receiving_num",byId.getReceivingNum())));
        return success(byId);
    }

    private String currentOrgId() {
        return roleOrgService.resolveOrgId(getUserId(), getDeptId());
    }
}
