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.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.base.domain.ProductionPlan;
import com.ruoyi.web.base.domain.ProductionPlanGoods;
import com.ruoyi.web.base.domain.param.ProductionPlanRequest;
import com.ruoyi.web.base.service.IProductionPlanGoodsService;
import com.ruoyi.web.base.service.IProductionPlanService;
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.util.List;
import java.util.Map;

import static com.ruoyi.common.core.domain.AjaxResult.success;
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-03-16
 */
@RestController
@RequestMapping("/production-plan")
public class ProductionPlanController {
    @Autowired
    private IProductionPlanService productionPlanService;
    @Autowired
    private IProductionPlanGoodsService goodsService;
    @Autowired
    private TokenService tokenService;



    @ApiOperation("获取生产计划单编号")
    @PostMapping("/getProductionNum")
    public AjaxResult getQuotaNum(HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);

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

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

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

    }



    @ApiOperation("生产计划单添加")
    @PostMapping("/add")
    @Transactional
    public AjaxResult add(@RequestBody ProductionPlan productionPlan, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);
        if (productionPlan.getOrderDate() == null) {
            throw new Exception("生产日期不能为空");
        }
        String orderNum = productionPlanService.generateOrderNum(loginOrgId, productionPlan.getOrderDate());
        productionPlan.setOrderNum(orderNum);
        String username = getUsername();
        productionPlan.setOrgId(loginOrgId);
        productionPlan.setCreateBy(username);
        List<ProductionPlanGoods> goods = productionPlan.getGoods();
        for (ProductionPlanGoods good : goods) {
            good.setOrgId(loginOrgId);
            good.setCreateBy(username);
            good.setOrderNum(productionPlan.getOrderNum());
            goodsService.save(good);
        }

        return success(productionPlanService.save(productionPlan));
    }

    @ApiOperation("生产计划单修改")
    @PostMapping("/edit")
    @Transactional
    public AjaxResult edit(@RequestBody ProductionPlan productionPlan, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);
        if (productionPlanService.count(new QueryWrapper<ProductionPlan>().ne("id",productionPlan.getId()).eq("org_id",loginOrgId).eq("order_num", productionPlan.getOrderNum())) >0 ){
            throw new Exception("该编号已存在");
        }
        String username = getUsername();
        productionPlan.setOrgId(loginOrgId);
        productionPlan.setCreateBy(username);
        List<ProductionPlanGoods> goods = productionPlan.getGoods();
        goodsService.remove(new QueryWrapper<ProductionPlanGoods>().eq("order_num",productionPlan.getOrderNum()));
        for (ProductionPlanGoods good : goods) {
            good.setOrgId(loginOrgId);
            good.setCreateBy(username);
            good.setOrderNum(productionPlan.getOrderNum());
            goodsService.save(good);
        }
        productionPlan.setUpdateBy(username);

        return success(productionPlanService.updateById(productionPlan));
    }

    @ApiOperation("生产计划单删除")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        for (String s : ids.split(",")) {
            productionPlanService.removeById(s);
        }
        return success();
    }

    @ApiOperation("生产计划单列表")
    @PostMapping("/list")
    public AjaxResult listAll( HttpServletRequest request,
    @RequestBody Map<String,String> map ){
        String productionType = map.get("productionType");
        String startDate = map.get("startDate");
        String endDate = map.get("endDate");
        List<ProductionPlan> org_id = productionPlanService.list(new QueryWrapper<ProductionPlan>()
                .eq(StringUtils.isNotEmpty(productionType),"production_type",productionType)
                .eq("org_id", tokenService.getLoginOrgId(request))
                .ge(StringUtils.isNotEmpty(startDate),"order_date",startDate)
                .le(StringUtils.isNotEmpty(endDate),"order_date",endDate)
        );
        for (ProductionPlan procureQuotation : org_id) {
            procureQuotation.setGoods(goodsService.list(new QueryWrapper<ProductionPlanGoods>().eq("order_num",procureQuotation.getOrderNum())));
        }
        return success(org_id);
    }

    @ApiOperation("生产计划单分页")
    @PostMapping("/page")
    public AjaxResult page(
            @RequestBody ProductionPlanRequest productionPlanParam, HttpServletRequest request) {


        QueryWrapper<ProductionPlan> wrapper = new QueryWrapper<ProductionPlan>().eq("org_id", tokenService.getLoginOrgId(request));

        wrapper.like(StringUtils.isNotEmpty(productionPlanParam.getOrderNum()),"order_num",productionPlanParam.getOrderNum())
                .eq(StringUtils.isNotEmpty(productionPlanParam.getProductionType()),"production_type",productionPlanParam.getProductionType())
                .ge(StringUtils.isNotEmpty(productionPlanParam.getStartTime()),"order_date",productionPlanParam.getStartTime())
                .le(StringUtils.isNotEmpty(productionPlanParam.getEndTime()),"order_date",productionPlanParam.getEndTime());
        Page<ProductionPlan> org_id =
                productionPlanService.page(new Page<ProductionPlan>(productionPlanParam.getPageNum(), productionPlanParam.getPageSize()),wrapper);

        for (ProductionPlan procureQuotation : org_id.getRecords()) {
            procureQuotation.setGoods(goodsService.list(new QueryWrapper<ProductionPlanGoods>().eq("order_num",procureQuotation.getOrderNum())));
        }
        return success(org_id);
    }

    @ApiOperation("生产计划单详情")
    @PostMapping("/listById")
    public AjaxResult listById(@RequestBody Map<String, String> paramsMap){
        String id = paramsMap.get("id");
        ProductionPlan byId = productionPlanService.getById(id);
        byId.setGoods(goodsService.list(new QueryWrapper<ProductionPlanGoods>().eq("order_num",byId.getOrderNum())));
        return success(byId);
    }

}
