package com.ruoyi.web.base.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.ProductionPlan;
import com.ruoyi.web.base.domain.ProductionPlanGoods;
import com.ruoyi.web.base.domain.ProductionRecord;
import com.ruoyi.web.base.domain.ProductionRegular;
import com.ruoyi.web.base.domain.param.ProductionRegularPlanRequest;
import com.ruoyi.web.base.service.IProductionPlanGoodsService;
import com.ruoyi.web.base.service.IProductionPlanService;
import com.ruoyi.web.base.service.IProductionRecordService;
import com.ruoyi.web.base.service.IProductionRegularService;
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.Map;

import static com.ruoyi.common.core.domain.AjaxResult.error;
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.*;

@RestController
@RequestMapping("/production-regular")
public class ProductionRegularController {

    @Autowired
    private IProductionRegularService productionRegularService;
    @Autowired
    private IProductionPlanGoodsService planGoodsService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IProductionPlanService planService;
    @Autowired
    private IProductionRecordService productionRecordService;

    @ApiOperation("批量修改加工类型")
    @PostMapping("/updateBatchType")
    @Transactional
    public AjaxResult updateBatch(@RequestBody Map<String, String> paramsMap,
    HttpServletRequest request) throws Exception {
         String ids = paramsMap.get("ids");
         String processingType = paramsMap.get("processingType");
        for (String id : ids.split(",")) {
            ProductionRegular productionRegular = new ProductionRegular();
            productionRegular.setId(Integer.parseInt(id));
            productionRegular.setProcessingType(processingType);
            productionRegularService.updateById(productionRegular);
        }
        return success();
    }

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

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

            return success(generateString2("JL", 1));
        }
        String quotationNum = one.getProductionRecordNumber();

        return success(generateString2("JL", substringToInt2(quotationNum)));

    }

    @ApiOperation("生产常规添加")
    @PostMapping("/add")
    @Transactional
    public AjaxResult add(@RequestBody ProductionRegular regular, HttpServletRequest request) throws Exception {
        if ("1".equals(regular.getQuarantineInspection()) ) {
            String pigBatch = regular.getPigBatch();
            ProductionPlanGoods productionPlanGoods = new ProductionPlanGoods();
            productionPlanGoods.setProductionStatus(1);
            planGoodsService.update(productionPlanGoods, new UpdateWrapper<ProductionPlanGoods>().eq("batch", pigBatch));
        }
        String loginOrgId = tokenService.getLoginOrgId(request);

        if (productionRegularService.count(
                new QueryWrapper<ProductionRegular>()
                        .eq("org_id", loginOrgId).eq("production_record_number", regular.getProductionRecordNumber())
                        .eq("white_strip_number", regular.getWhiteStripNumber())
        ) > 0) {
            throw new Exception("该白条已存在");
        }
        regular.setOrgId(loginOrgId);
        regular.setCreateBy(getUsername());
        ProductionRecord productionRecord = new ProductionRecord();
        BeanUtil.copyProperties(regular, productionRecord);
        productionRecord.setProductionRecordDate(regular.getProductionDate());
        productionRecordService.save(productionRecord);
        return success(productionRegularService.save(regular));
    }

    @ApiOperation("生产常规修改")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody ProductionRegular regular, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);
        if (productionRegularService.count(
                new QueryWrapper<ProductionRegular>()
                        .ne("id", regular.getId())
                        .eq("org_id", loginOrgId)
                        .eq("production_record_number", regular.getProductionRecordNumber()).eq("white_strip_number", regular.getWhiteStripNumber())
        ) > 0) {
            throw new Exception("该常规编号已存在");
        }
        regular.setUpdateBy(getUsername());
        return success(productionRegularService.updateById(regular));
    }

    @ApiOperation("生产常规删除")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        for (String id : ids.split(",")) {
            productionRegularService.removeById(id);
        }
        return success();
    }

    @ApiOperation("生产常规列表")
    @PostMapping("/list")
    public AjaxResult listAll(
            @RequestBody ProductionRegularPlanRequest planRequest, HttpServletRequest request) {

        return success(productionRegularService.list(
                new QueryWrapper<ProductionRegular>()
                        .eq("org_id", tokenService.getLoginOrgId(request)).
                        eq(StringUtils.isNotEmpty(planRequest.getProductionPlanNumber()), "production_plan_number", planRequest.getProductionPlanNumber())
                        .eq(StringUtils.isNotEmpty(planRequest.getPigBatch()), "pig_batch", planRequest.getPigBatch())
                        .eq(StringUtils.isNotEmpty(planRequest.getProductionDate()), "production_date", planRequest.getProductionDate())
                        .eq(StringUtils.isNotEmpty(planRequest.getProductionType()), "production_type", planRequest.getProductionType())
                        .eq(StringUtils.isNotEmpty(planRequest.getProductionWorkshop()), "productionorkshop", planRequest.getProductionWorkshop())
                )
        );
    }
    @ApiOperation("白条分配")
    @PostMapping("/listFenPei")
    public AjaxResult listFenPei(
            @RequestBody ProductionRegularPlanRequest planRequest, HttpServletRequest request) {

        return success(productionRegularService.list(
                new QueryWrapper<ProductionRegular>()
                        .eq("org_id", tokenService.getLoginOrgId(request)).
                        eq("is_fenpei",0).
                        eq(StringUtils.isNotEmpty(planRequest.getAnimalTag()), "animal_identification", planRequest.getAnimalTag())
                        .eq(StringUtils.isNotEmpty(planRequest.getBatch()), "pig_batch", planRequest.getBatch())
                        .eq(StringUtils.isNotEmpty(planRequest.getProductionDate()), "production_date", planRequest.getProductionDate())
                        .eq(StringUtils.isNotEmpty(planRequest.getLevel()), "grade", planRequest.getLevel())
                        .eq(StringUtils.isNotEmpty(planRequest.getVariety()), "variety", planRequest.getVariety())
                        .eq(StringUtils.isNotEmpty(planRequest.getWhiteNo()), "white_strip_num", planRequest.getWhiteNo())
                )
        );
    }

    @ApiOperation("生产常规分页")
    @PostMapping("/page")
    public AjaxResult page(@RequestBody ProductionRegularPlanRequest planRequest,
                           HttpServletRequest request
    ) {

        QueryWrapper<ProductionRegular> wrapper = new QueryWrapper<ProductionRegular>()
                .eq("org_id", tokenService.getLoginOrgId(request));
        wrapper.eq(StringUtils.isNotEmpty(planRequest.getProductionPlanNumber()), "production_plan_number", planRequest.getProductionPlanNumber())
                .eq(StringUtils.isNotEmpty(planRequest.getProductionDate()), "production_date", planRequest.getProductionDate())
                .eq(StringUtils.isNotEmpty(planRequest.getGradel()), "grade", planRequest.getGradel())
                .eq(StringUtils.isNotEmpty(planRequest.getVariety()), "variety", planRequest.getVariety())
                .eq(StringUtils.isNotEmpty(planRequest.getAnimalIdentification()), "animal_identification", planRequest.getAnimalIdentification())
                .eq(StringUtils.isNotEmpty(planRequest.getProcessingType()), "processing_type", planRequest.getProcessingType())
                .eq(StringUtils.isNotEmpty(planRequest.getProductionType()), "production_type", planRequest.getProductionType())
        ;
        return success(productionRegularService.page(
                new Page<ProductionRegular>(planRequest.getPageNum(), planRequest.getPageSize()), wrapper
                )
        );
    }

    @ApiOperation("生产常规详情")
    @PostMapping("/listById")
    public AjaxResult listById(@RequestBody Map<String, String> paramsMap) {
        String id = paramsMap.get("id");
        return success(productionRegularService.getById(id));
    }

    @ApiOperation("获取今日白条精修")
    @PostMapping("/listWhite")
    public AjaxResult listWhite(@RequestBody ProductionRegularPlanRequest planRequest,
                                HttpServletRequest request
    ) {
        long planCount = planService.count(new QueryWrapper<ProductionPlan>()
                .eq(StringUtils.isNotEmpty(planRequest.getProductionType()), "production_type", planRequest.getProductionType())
                .eq("org_id", tokenService.getLoginOrgId(request)));
        if (planCount < 1) {
            return error("今日暂无生产计划");
        }

        QueryWrapper<ProductionRegular> wrapper = new QueryWrapper<ProductionRegular>()
                .eq("org_id", tokenService.getLoginOrgId(request));
        wrapper.eq(StringUtils.isNotEmpty(planRequest.getWhiteStripDate()), "production_date", planRequest.getWhiteStripDate())
                .eq(StringUtils.isNotEmpty(planRequest.getWhiteStripNum()), "white_strip_number", planRequest.getWhiteStripNum())
                .eq(StringUtils.isNotEmpty(planRequest.getProcessingType()), "processing_type", planRequest.getProcessingType())
                .ge(StringUtils.isNotEmpty(planRequest.getStartDate()), "production_date", planRequest.getStartDate())
                .le(StringUtils.isNotEmpty(planRequest.getEndDate()), "production_date", planRequest.getEndDate())
                .eq(StringUtils.isNotEmpty(planRequest.getStartGrade()), "grade", planRequest.getStartGrade())
                .eq(StringUtils.isNotEmpty(planRequest.getEndGrade()), "grade", planRequest.getEndGrade())
                .eq(StringUtils.isNotEmpty(planRequest.getVariety()), "variety", planRequest.getVariety())
                .eq(StringUtils.isNotEmpty(planRequest.getAnimalIdentification()), "animal_identification", planRequest.getAnimalIdentification())
                .ge(StringUtils.isNotEmpty(planRequest.getStartWhiteStripNum()), "white_strip_number", planRequest.getStartWhiteStripNum())
                .le(StringUtils.isNotEmpty(planRequest.getEndWhiteStripNum()), "white_strip_number", planRequest.getEndWhiteStripNum())
        ;

        ProductionRegular one = productionRegularService.getOne(wrapper);
        if (ObjectUtils.isEmpty(one)) {
            return error("今日暂无该白条编号");
        }
        return success(one);
    }
    @ApiOperation("获取今日白条分割")
    @PostMapping("/listWhiteFenGe")
    public AjaxResult listWhiteFenGe(@RequestBody ProductionRegularPlanRequest planRequest,
                                HttpServletRequest request
    ) {


        QueryWrapper<ProductionRegular> wrapper = new QueryWrapper<ProductionRegular>()
                .eq("org_id", tokenService.getLoginOrgId(request));
        wrapper.
             eq(StringUtils.isNotEmpty(planRequest.getProcessingType()), "processing_type", planRequest.getProcessingType())
             .eq("is_fenge", 0)
                .ge(StringUtils.isNotEmpty(planRequest.getStartDate()), "production_date", planRequest.getStartDate())
                .le(StringUtils.isNotEmpty(planRequest.getEndDate()), "production_date", planRequest.getEndDate())
                .eq(StringUtils.isNotEmpty(planRequest.getStartGrade()), "grade", planRequest.getStartGrade())
                .eq(StringUtils.isNotEmpty(planRequest.getEndGrade()), "grade", planRequest.getEndGrade())
                .eq(StringUtils.isNotEmpty(planRequest.getVariety()), "variety", planRequest.getVariety())
                .eq(StringUtils.isNotEmpty(planRequest.getAnimalIdentification()), "animal_identification", planRequest.getAnimalIdentification())
                .ge(StringUtils.isNotEmpty(planRequest.getStartWhiteStripNum()), "white_strip_number", planRequest.getStartWhiteStripNum())
                .le(StringUtils.isNotEmpty(planRequest.getEndWhiteStripNum()), "white_strip_number", planRequest.getEndWhiteStripNum())
                .ge(StringUtils.isNotEmpty(planRequest.getQualityInspectionResult()), "quality_inspection_result", planRequest.getQualityInspectionResult())
        ;


        return success( productionRegularService.list(wrapper));
    }
}