package cn.ezhizao.project.business.workshopTrunover.controller;

import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.project.business.daywork.domain.BizDaywork;
import cn.ezhizao.project.business.daywork.domain.BizDayworkItem;
import cn.ezhizao.project.business.daywork.service.IBizDayworkService;
import cn.ezhizao.project.business.workshopTrunover.domain.BizWorkshopTurnover;
import cn.ezhizao.project.business.workshopTrunover.service.IBizWorkshopTurnoverService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 车间管理Controller
 *
 * @author ezhizao
 * @date 2024-02-22
 */
@RestController
@RequestMapping("/business/workshopTurnover")
public class BizWorkshopTurnoverController extends BaseController
{
    @Resource
    private IBizWorkshopTurnoverService bizWorkshopTurnoverService;

    @Resource
    HttpServletRequest request;
    @Resource
    private IBizDayworkService bizDayworkService;

    /**
     * 查询车间管理列表
     */
    //@PreAuthorize("@ss.hasPermi('business:workshop:list')")
    @Log(title = "车间周转区查询", businessType = BusinessType.SELECT)
    @PostMapping("/list")
    public AjaxResult list(@RequestBody Map<String, Object> data) throws NoSuchFieldException, IllegalAccessException
    {
        int zero = 0;
        String tenantId = request.getHeader("tenantId");
        QueryWrapper<BizWorkshopTurnover> queryWrapper = new QueryWrapper<>();
        final String param1 = "workshopId";
        long workshopId = 0L;
        if (data.get(param1) != null) {
            workshopId = Long.parseLong(data.get(param1).toString());
        }

        queryWrapper.eq("workshop_id", workshopId).ne("status",9);
//        if (tenantId != null && !Integer.toString(zero).equals(tenantId)) {
//            queryWrapper.eq("tenant_id", Long.valueOf(tenantId));
//        }
        List<BizWorkshopTurnover> list = bizWorkshopTurnoverService.list(queryWrapper);
        return success(list);
    }

    /**
     * 获取周转区详细信息
     */
//    @PreAuthorize("@ss.hasPermi('business:turnover:query')")
    @Log(title = "车间周转区查询详细信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizWorkshopTurnoverService.getById(id));
    }

    /**
     * 新增周转区
     */
//    @PreAuthorize("@ss.hasPermi('business:turnover:add, business:turnover:edit')")
    @Log(title = "车间周转区保存", businessType = BusinessType.INSERT)
    @PostMapping(value = "/save")
    public AjaxResult save(@RequestBody BizWorkshopTurnover bizWorkshopTurnover) throws NoSuchFieldException, IllegalAccessException {
        String tenantId = request.getHeader("tenantId");
        QueryWrapper<BizWorkshopTurnover> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", bizWorkshopTurnover.getCode());
        queryWrapper.eq("workshop_id", bizWorkshopTurnover.getWorkshopId());
        queryWrapper.eq("status", 0);
        queryWrapper.eq("tenant_id", Long.valueOf(tenantId));
        long currentTurnoverId = 0L;
        if (bizWorkshopTurnover.getId() != null) {
            currentTurnoverId = bizWorkshopTurnover.getId();
        }
        queryWrapper.ne("id", currentTurnoverId);
        List<BizWorkshopTurnover> turnovers = bizWorkshopTurnoverService.list(queryWrapper);
        if (!turnovers.isEmpty()) {
            return AjaxResult.warn("该周转区编码已存在");
        }
        bizWorkshopTurnover.setTenantId(Long.valueOf(tenantId));
        return toAjax(bizWorkshopTurnoverService.saveOrUpdate(bizWorkshopTurnover));
    }

    /**
     * 删除周转区
     */
//    @PreAuthorize("@ss.hasPermi('business:turnover:remove')")
    @Log(title = "车间周转区删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long ids) {
        List<BizDayworkItem> turnoverDayworkList = getTurnoverDayworkList((ids+""));
        if(turnoverDayworkList.size()>0){
            return error("当前周转区有未领取批次");
        }else {
            return toAjax(bizWorkshopTurnoverService.removeById(ids));
        }
    }

    /**
     * 根据周转位置获取批次报工
     * @param turnoverId
     * @return
     */
    public List<BizDayworkItem> getTurnoverDayworkList(String turnoverId) {
        List<BizDaywork> turnoverDayworkList = bizDayworkService.getTurnoverDayworkList();

        List<BizDayworkItem> itemList = turnoverDayworkList.stream()
                .filter(daywork -> daywork.getTurnoverDayworkItem().getStatus().equals("4") ||
                        daywork.getTurnoverDayworkItem().getStatus().equals("5") ||
                        daywork.getTurnoverDayworkItem().getStatus().equals("7"))
                .map(BizDaywork::getTurnoverDayworkItem) // 直接映射到BizDayworkItem
                .collect(Collectors.toList());

        // 使用Stream API过滤出placeId包含"abc"的BizDayworkItem对象
        List<BizDayworkItem> filteredItems = itemList.stream()
                .filter(item -> item.getTurnoverId().contains(turnoverId)) // 假设getPlaceId()返回placeId属性的值
                .collect(Collectors.toList());
        return filteredItems;
    }
}
