package cn.ezhizao.project.business.turnover.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.turnover.domain.BizTurnover;
import cn.ezhizao.project.business.turnover.service.IBizTurnoverService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;

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


/**
 * 周转区Controller
 *
 * @author ezhizao
 * @date 2023-11-14
 */
@RestController
@RequestMapping("/business/turnover")
public class BizTurnoverController extends BaseController {
    @Resource
    private IBizTurnoverService iBizTurnoverService;
    @Resource
    HttpServletRequest request;
    @Resource
    private IBizDayworkService bizDayworkService;

    /**
     * 查询周转区列表
     */
//    @PreAuthorize("@ss.hasPermi('business:turnover:list')")
    @Log(title = "周转区列表获取", businessType = BusinessType.SELECT)
    @PostMapping("/list")
    public AjaxResult list(@RequestBody Map<String, Object> data) throws NoSuchFieldException, IllegalAccessException {

        Integer zero = 0;
        String tenantId = request.getHeader("tenantId");
        QueryWrapper<BizTurnover> queryWrapper = new QueryWrapper<>();
        final String param1 = "deptId";
        long deptId = 0L;
        if (data.get(param1) != null) {
            deptId = Long.parseLong(data.get(param1).toString());
        }

        queryWrapper.eq("dept_id", deptId).ne("status",9);
//        if (tenantId != null && !zero.toString().equals(tenantId)) {
//            queryWrapper.eq("tenant_id", Long.valueOf(tenantId));
//        }
        List<BizTurnover> list = iBizTurnoverService.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(iBizTurnoverService.getById(id));
    }

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

    /**
     * 删除周转区
     */
//    @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(iBizTurnoverService.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.getPlaceId().contains(turnoverId)) // 假设getPlaceId()返回placeId属性的值
                .collect(Collectors.toList());
        return filteredItems;
    }
}
