package com.ximai.mes.pro.controller;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.ximai.common.utils.data.StringUtils;
import com.ximai.mes.constant.MaterialRequestEnum;
import com.ximai.mes.pro.domain.ProAllocationMaterial;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.vo.ProMaterialRequestVo;
import com.ximai.mes.pro.domain.vo.task.MaterialRequestIds;
import com.ximai.mes.pro.mapper.ProMaterialRequestMapper;

import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
import com.ximai.mes.pro.service.IProAllocationMaterialService;
import org.springframework.beans.BeanUtils;
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.ximai.common.annotation.Log;
import com.ximai.common.core.controller.BaseController;
import com.ximai.common.core.domain.AjaxResult;
import com.ximai.common.enums.BusinessType;
import com.ximai.mes.pro.domain.ProMaterialRequest;
import com.ximai.mes.pro.service.IProMaterialRequestService;
import com.ximai.common.core.page.TableDataInfo;

/**
 * 领料申请Controller
 *
 * @author generator
 * @date 2024-02-22
 */
@RestController
@RequestMapping("/pro/materialRequest")
public class ProMaterialRequestController extends BaseController {
    @Autowired
    private IProMaterialRequestService proMaterialRequestService;

    @Autowired
    private ProMaterialRequestMapper proMaterialRequestMapper;

    @Autowired
    private ProWorkorderMapper proWorkorderMapper;


    @Autowired
    private IProAllocationMaterialService proAllocationMaterialService;

    /**
     *查询领料申请列表/
     *
     */
    @ApiOperation("领料申请打印数据")
    @GetMapping("/materialRequestPrintInfo")
    public AjaxResult materialRequestPrintInfo( MaterialRequestIds materialRequestIds) {
        List<ProMaterialRequestVo> list = proMaterialRequestService.selectMaterialRequestPrintTab(materialRequestIds);
        return AjaxResult.success(list);
    }

    /**
     * 查询领料申请列表
     */
    @PreAuthorize("@ss.hasPermi('pro:materialRequest:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProMaterialRequestVo proMaterialRequestVo) {
        startPage();
        QueryWrapper<ProMaterialRequest> query = new QueryWrapper<ProMaterialRequest>();
        Object beginPurchaseDate = proMaterialRequestVo.getParams().get("beginPurchaseDate");
        Object endPurchaseDate = proMaterialRequestVo.getParams().get("endPurchaseDate");
        if(proMaterialRequestVo.getSapItemCode()!="")
        query.eq(proMaterialRequestVo.getSapItemCode() != null , "m.sap_item_code", proMaterialRequestVo.getSapItemCode());
        if(proMaterialRequestVo.getItemName()!="")
        query.eq(proMaterialRequestVo.getItemName() != null , "m.item_name", proMaterialRequestVo.getItemName());
        query.eq(proMaterialRequestVo.getApplyType() != null , "p.apply_type", proMaterialRequestVo.getApplyType());
        if(proMaterialRequestVo.getArrangeCode()!="")
        query.eq(proMaterialRequestVo.getArrangeCode() != null , "pr.arrange_code", proMaterialRequestVo.getArrangeCode());
        query.eq(proMaterialRequestVo.getApplyNum() != null , "p.apply_num", proMaterialRequestVo.getApplyNum());
        if(proMaterialRequestVo.getCreateBy()!="")
        query.eq(proMaterialRequestVo.getCreateBy() != null , "p.create_by", proMaterialRequestVo.getCreateBy());
        if(proMaterialRequestVo.getWorkorderCode()!="")
        query.eq(proMaterialRequestVo.getWorkorderCode() != null , "p.workorder_code", proMaterialRequestVo.getWorkorderCode());
        if(proMaterialRequestVo.getApplyNo()!="")
        query.eq(proMaterialRequestVo.getApplyNo() != null , "p.apply_no", proMaterialRequestVo.getApplyNo());
        query.between(beginPurchaseDate != null && endPurchaseDate != null, "p.create_time", beginPurchaseDate, endPurchaseDate);
//        query.orderBy("p.update_time",);
        List<ProMaterialRequestVo> proMaterialRequestVos = proMaterialRequestMapper.selectProMaterialRequestLis(query);
//        List<ProMaterialRequest> list = proMaterialRequestService.selectProMaterialRequestList(proMaterialRequest);
        return getDataTable(proMaterialRequestVos);
    }

    /**
     * 获取领料申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('pro:materialRequest:query')")
    @GetMapping(value = "/{materialRequestId}")
    public AjaxResult getInfo(@PathVariable("materialRequestId") Long materialRequestId) {
        return AjaxResult.success(proMaterialRequestService.selectProMaterialRequestByMaterialRequestId(materialRequestId));
    }

    /**
     * 领用申请查看生产工单物料
     *
     * @param proMaterialRequestVo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('pro:materialRequest:query')")
    @PostMapping(value = "/selectworkorder")
    public TableDataInfo getProcessItem(@RequestBody ProMaterialRequestVo proMaterialRequestVo) {
        return getDataTable(proMaterialRequestService.selectProMaterialRequestByMaterialRequestWorkorderId(proMaterialRequestVo));
    }

    /**
     * 新增领料申请
     */
    @PreAuthorize("@ss.hasPermi('pro:materialRequest:add')")
    @Log(title = "领料申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProMaterialRequest proMaterialRequest) {
        return toAjax(proMaterialRequestService.insertProMaterialRequestCreate(proMaterialRequest));
    }


    /**
     * 修改领料申请
     */
    @PreAuthorize("@ss.hasPermi('pro:materialRequest:edit')")
    @Log(title = "领料申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProMaterialRequest proMaterialRequest) {
        return toAjax(proMaterialRequestService.updateProMaterialRequest(proMaterialRequest));
    }
    /**
     * 删除领料申请
     */
    @PreAuthorize("@ss.hasPermi('pro:materialRequest:remove')")
    @Log(title = "领料申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{materialRequestIds}")
    public AjaxResult remove(@PathVariable Long[] materialRequestIds) {
        return toAjax(proMaterialRequestService.deleteProMaterialRequestByMaterialRequestIds(materialRequestIds));
    }


    /**
     * 查了领料申请单计录查询
     */
    @PreAuthorize("@ss.hasPermi('pro:materialRequest:list')")
    @GetMapping("/recordList")
    public TableDataInfo recordList(ProMaterialRequest proMaterialRequest){
        if(StringUtils.isNotEmpty(proMaterialRequest.getWorkorderId())) {
            ProWorkorder proWorkorder = proWorkorderMapper.selectWorkorderById(proMaterialRequest.getWorkorderId());
            proMaterialRequest.setWorkorderCode(proWorkorder.getWorkorderCode());
        }
        //查看倒冲料数据
        ProAllocationMaterial proAllocationMaterial = new ProAllocationMaterial();
        proAllocationMaterial.setTaskId(proMaterialRequest.getTaskId());
        List<ProAllocationMaterial> proAllocationMaterials = proAllocationMaterialService.selectProAllocationMaterialList(proAllocationMaterial);
        List<ProAllocationMaterial> collect2 = proAllocationMaterials.stream().filter(s -> s.getMaterialType() == 1).collect(Collectors.toList());
        //查看直发料的额数据
        List<ProMaterialRequest> proMaterialRequests = proMaterialRequestService.selectProMaterialRequestList(proMaterialRequest);
        List<ProMaterialRequest> collect = proMaterialRequests.stream().map(s -> {
            ProMaterialRequest proMaterialRequest1 = new ProMaterialRequest();
            BeanUtils.copyProperties(s, proMaterialRequest1);
            if (StringUtils.isNotEmpty(s.getGrantNum())) {
                if (s.getGrantNum().compareTo(BigDecimal.ZERO) > 0) {
                    proMaterialRequest1.setAttr1(MaterialRequestEnum.REQUEST.getStatusValue());
                    proMaterialRequest1.setIsBackflush("N");
                } else {
                    proMaterialRequest1.setAttr1(MaterialRequestEnum.NOT_REQUEST.getStatusValue());
                    proMaterialRequest1.setIsBackflush("N");
                }

            } else {
                proMaterialRequest1.setAttr1(MaterialRequestEnum.NOT_REQUEST.getStatusValue());
                proMaterialRequest1.setIsBackflush("N");
            }
            return proMaterialRequest1;
        }).collect(Collectors.toList());
        List<ProMaterialRequest> collect1 = collect.stream().filter(s -> s.getMaterialType() == 1).collect(Collectors.toList());
        for (ProAllocationMaterial allocationMaterial : collect2) {
            ProMaterialRequest proMaterialRequest1 = new ProMaterialRequest();
            proMaterialRequest1.setIsBackflush("Y");
            proMaterialRequest1.setApplyNo(allocationMaterial.getApplyNo());
            proMaterialRequest1.setApplyNum(allocationMaterial.getApplyNum());
            proMaterialRequest1.setSapItemCode(allocationMaterial.getSapItemCode());
            proMaterialRequest1.setAttr1(MaterialRequestEnum.APPLY.getStatusValue());
            collect1.add(proMaterialRequest1);
        }


        return getDataTable(collect1);
    }



}
