package com.ruoyi.web.base.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.*;
import com.ruoyi.web.base.domain.param.WiteStripAllRequest;
import com.ruoyi.web.base.service.*;
import com.ruoyi.web.sales.domain.SalesOrder;
import com.ruoyi.web.sales.domain.SalesOrderGoods;
import com.ruoyi.web.sales.service.ISalesOrderGoodsService;
import com.ruoyi.web.sales.service.ISalesOrderService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
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;

@RestController
@RequestMapping("/production-white-strip-allocation")
public class ProductionWhiteStripAllocationController {

    @Autowired
    private IProductionWhiteStripAllocationService productionWhiteStripAllocationService;
    @Autowired
    private IProductionRegularService regularService;
    @Autowired
    private IBaseMaterialService baseMaterialService;
    @Autowired
    private IProductionShipmentNotificationService shipmentNotificationService;
    @Autowired
    private TokenService tokenService;
    @Autowired
     private ISalesOrderService salesOrderService;
    @Autowired
    private ISalesOrderGoodsService salesOrderGoodsService;

    @ApiOperation("白条分配添加")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ProductionWhiteStripAllocation allocation, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);

        allocation.setOrgId(loginOrgId);
        allocation.setCreateBy(getUsername());
        Integer regularId = allocation.getRegularId();
        ProductionRegular productionRegular = new ProductionRegular();
        productionRegular.setId(regularId);
        productionRegular.setIsFenpei(1);
        regularService.updateById(productionRegular);
        return success(productionWhiteStripAllocationService.save(allocation));
    }
    @ApiOperation("白条分配批量添加")
    @PostMapping("/addBatch")
    public AjaxResult addBatch(@RequestBody WiteStripAllRequest witeStripAllRequest, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);



        String ids = witeStripAllRequest.getIds();
        for (String id : ids.split(",")) {
            ProductionRegular byId = regularService.getById(id);
            byId.setIsFenpei(1);
            regularService.updateById(byId);
            ProductionWhiteStripAllocation allocation = new ProductionWhiteStripAllocation();
            allocation.setOrgId(loginOrgId);
            allocation.setCreateBy(getUsername());
            allocation.setAnimalIdentification(byId.getAnimalIdentification());
//            allocation.setBatchNumber();
            allocation.setCoatColor(byId.getCoatColor());
            allocation.setCustomer(witeStripAllRequest.getCustomer());
//            allocation.setDeductionScore(witeStripAllRequest.getd());
            allocation.setDeliveryCustomer(witeStripAllRequest.getDeliveryCustomer());
            allocation.setDeliveryDate(witeStripAllRequest.getDeliveryDate());
            allocation.setGrade(byId.getGrade());
            allocation.setMarket(witeStripAllRequest.getMarket());
            allocation.setLockedLogisticsLine(witeStripAllRequest.getLockedLogisticsLine());
            BaseMaterial material = baseMaterialService.getOne(new QueryWrapper<BaseMaterial>().eq("goods_num", byId.getGoodsNum()));

            allocation.setMaterialName(material.getGoodsName());
//            allocation.setOrderUnallocatedQuantity(witeStripAllRequest.geto);
            allocation.setPigBatch(byId.getPigBatch());
            allocation.setProductionDate(witeStripAllRequest.getProductionDate());
            allocation.setRegularId(Integer.parseInt(id));
            allocation.setSaleId(witeStripAllRequest.getSaleId());
            allocation.setSaleNum(witeStripAllRequest.getSaleNum());
            allocation.setVariety(byId.getVariety());
//            allocation.setWeight(witeStripAllRequest.getw);
            allocation.setWhiteStripNumber(byId.getWhiteStripNumber());

            productionWhiteStripAllocationService.save(allocation);
        }


        return success();
    }

    @ApiOperation("白条分配修改")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody ProductionWhiteStripAllocation allocation, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);

        allocation.setUpdateBy(getUsername());
        return success(productionWhiteStripAllocationService.updateById(allocation));
    }

    @ApiOperation("白条分配删除")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        for (String id : ids.split(",")) {
            ProductionWhiteStripAllocation byId = productionWhiteStripAllocationService.getById(id);
            ProductionRegular productionRegular = new ProductionRegular();
            productionRegular.setId(byId.getRegularId());
            productionRegular.setIsFenpei(0);
            regularService.updateById(productionRegular);

            productionWhiteStripAllocationService.removeById(id);
        }
        return success();
    }

    @ApiOperation("白条分配列表")
    @PostMapping("/list")
    public AjaxResult listAll(HttpServletRequest request) {
        return success(productionWhiteStripAllocationService.list(
                new QueryWrapper<ProductionWhiteStripAllocation>()
                        .eq("org_id", tokenService.getLoginOrgId(request))
        ));
    }
    @ApiOperation("根据saleNum查询")
    @PostMapping("/listBySaleNum")
    public AjaxResult listBySaleNum(@RequestBody WiteStripAllRequest witeStripAllRequest,
                                    HttpServletRequest request
    ) {
        QueryWrapper<ProductionWhiteStripAllocation> wrapper = new QueryWrapper<ProductionWhiteStripAllocation>()
                .eq("org_id", tokenService.getLoginOrgId(request));
//        wrapper
//                .like(StringUtils.isNotEmpty(witeStripAllRequest.getMaterialCode()), "material_code", witeStripAllRequest.getMaterialCode())
//                .like(StringUtils.isNotEmpty(witeStripAllRequest.getSaleNum()), "sale_num", witeStripAllRequest.getSaleNum())
//                .eq(StringUtils.isNotEmpty(witeStripAllRequest.getProductionDate()), "production_date", witeStripAllRequest.getProductionDate());
        wrapper.eq("sale_id",witeStripAllRequest.getSaleId() );
        return success(productionWhiteStripAllocationService.list(
                wrapper
        ));
    }
    @ApiOperation("批量修改状态")
    @PostMapping("/editAllStatus")
    public AjaxResult editAllStatus(@RequestBody Map<String, String> paramsMap) throws Exception {
        String ids = paramsMap.get("ids");
        for (String id : ids.split(",")) {
            ProductionWhiteStripAllocation productionWhiteStripAllocation = new ProductionWhiteStripAllocation();
            productionWhiteStripAllocation.setId(Integer.parseInt(id));
            productionWhiteStripAllocation.setCompletionStatus(1);
            productionWhiteStripAllocationService.updateById(productionWhiteStripAllocation);
            ProductionWhiteStripAllocation byId = productionWhiteStripAllocationService.getById(id);
            saveShipmentNotification(byId);
        }
        return success();
    }

    private void saveShipmentNotification(ProductionWhiteStripAllocation byId) {

        ProductionShipmentNotification productionShipmentNotification = new ProductionShipmentNotification();

        SalesOrderGoods salesOrder = salesOrderGoodsService.getById(byId.getSaleId());

        BeanUtil.copyProperties(byId,productionShipmentNotification);
        productionShipmentNotification.setAmount(salesOrder.getSubTotal()) ;
        productionShipmentNotification.setUnitPrice(salesOrder.getUnitPrice()) ;


        BaseMaterial material = baseMaterialService.getOne(new QueryWrapper<BaseMaterial>().eq("goods_num", byId.getMaterialCode()));
        productionShipmentNotification.setProductType(material.getProductTypeName()) ;
        productionShipmentNotification.setProductNum(material.getProductType());
        productionShipmentNotification.setMaterialName(material.getGoodsName());
        productionShipmentNotification.setBaseNum(salesOrder.getBaseNum());
        productionShipmentNotification.setUnit(salesOrder.getBaseUnit());
        productionShipmentNotification.setAssNum(salesOrder.getAssNum());
        productionShipmentNotification.setAuxiliaryUnit(salesOrder.getAssUnit());
//        productionShipmentNotification.setTotalDeduction(salesOrder.getReceivableCustomer()) ;
//        productionShipmentNotification.setCustomerChannel(salesOrder.getc()) ;
        productionShipmentNotification.setWarehouse(material.getWarehouseName()) ;
        List<SalesOrder> salesOrders = salesOrderService.list(new QueryWrapper<SalesOrder>().eq("order_num", salesOrder.getOrderNum()));
        if(ObjectUtil.isNotEmpty(salesOrders)){
            productionShipmentNotification.setReceivableCustomer(salesOrders.get(0).getCustomerName()) ;
            productionShipmentNotification.setCustomer(salesOrders.get(0).getCustomerName()) ;
            productionShipmentNotification.setCustomerNumber(salesOrders.get(0).getCustomerNum()) ;

        }


        productionShipmentNotification.setSalesWeight(byId.getWeight()) ;
//        productionShipmentNotification.setSalesDeductionPercentage(salesOrder.getReceivableCustomer()) ;

        shipmentNotificationService.save(productionShipmentNotification);
    }

    @ApiOperation("白条分配分页")
    @GetMapping("/page")
    public AjaxResult page(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            HttpServletRequest request
    ) {
        return success(productionWhiteStripAllocationService.page(
                new Page<ProductionWhiteStripAllocation>(pageNum, pageSize),
                new QueryWrapper<ProductionWhiteStripAllocation>()
                        .eq("org_id", tokenService.getLoginOrgId(request))
        ));
    }

    @ApiOperation("白条分配详情")
    @PostMapping("/listById")
    public AjaxResult listById(@RequestBody Map<String, String> paramsMap) {
        String id = paramsMap.get("id");
        return success(productionWhiteStripAllocationService.getById(id));
    }
}
