package cn.ezhizao.project.business.controller;

import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.task.RyTask;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.BizCarrier;
import cn.ezhizao.project.business.domain.BizDayworkCarrier;
import cn.ezhizao.project.business.domain.BizOutsourcedOrderDetail;
import cn.ezhizao.project.business.domain.BizReturnReceiptDetail;
import cn.ezhizao.project.business.service.IBizCarrierService;
import cn.ezhizao.project.business.service.IBizDayworkCarrierService;
import cn.ezhizao.project.business.service.IBizOutsourcedOrderDetailService;
import cn.ezhizao.project.business.service.IBizReturnReceiptDetailService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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


/**
 * 载具Controller
 *
 * @author ezhizao
 * @date 2023-11-14
 */
@RestController
@RequestMapping("/business/carrier")
public class BizCarrierController extends BaseController {
    @Resource
    private IBizCarrierService iBizCarrierService;
    @Resource
    private HttpServletRequest request;

    @Resource
    private IBizOutsourcedOrderDetailService bizOutsourcedOrderDetailService;

    @Resource
    private IBizDayworkCarrierService bizDayworkCarrierService;

    @Resource
    private IBizReturnReceiptDetailService bizReturnReceiptDetailService;

    @GetMapping("/list")
    public TableDataInfo list(BizCarrier data) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        List<BizCarrier> list = iBizCarrierService.getList(data);
        return getDataTable(list);
    }
    @Log(title="查验无箱是否被使用", businessType = BusinessType.SELECT)
    @GetMapping("/checkCanAbandoned/{ids}")
    @Transactional
    public AjaxResult checkCanAbandoned(@PathVariable List<Long> ids) {
        List<BizDayworkCarrier> list = bizDayworkCarrierService.query().in("carrier_id", ids).eq("deleted", 0).eq("is_changed", 0).list();
        if(!list.isEmpty()) {
            String msg = "当前箱正被使用,请解绑载具后废弃";
            return AjaxResult.success(msg, false);
        }
        return success(true);
    }
    @GetMapping("/getListNotInspectionList")
    @Log(title = "获取非检查箱列表", businessType = BusinessType.SELECT)
    public TableDataInfo getListNotInspectionList(BizCarrier data) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        startPage();
        List<BizCarrier> list = iBizCarrierService.getListNotInspectionList(data);
        return getDataTable(list);
    }

//    @PostMapping("/whether")
    public AjaxResult whether(@RequestBody List<BizCarrier> carrierList) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        /**  判断载具是否可以打印 **/
        List<Long> ids = carrierList.stream().map(BizCarrier::getId).collect(Collectors.toList());
        //先查询载具是否绑定了批次，获取到dayworkId
        List<BizDayworkCarrier> dayworkCarrierListr = bizDayworkCarrierService.query().in("carrier_id", ids).eq("deleted", 0).eq("is_changed", 0).list();
        if(dayworkCarrierListr.size()==0){
            return success(true);
        }

        //获取dayworkIds
        List<Long> dayworkIds = dayworkCarrierListr.stream().map(BizDayworkCarrier::getDayworkId).collect(Collectors.toList());

        //根据dayworkId查询是否从外协发出
        List<BizOutsourcedOrderDetail> outsourcedOrderDetails = bizOutsourcedOrderDetailService.query().in("daywork_id", dayworkIds).eq("deleted", 0).list();
        if(outsourcedOrderDetails.size()==0){
            return success(true);
        }
        dayworkIds=outsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList());
        List<BizReturnReceiptDetail> bizReturnReceiptDetails =  bizReturnReceiptDetailService.query().in("daywork_id", dayworkIds).eq("deleted", 0).list();

        //根据从外协发出的批次，查询是否回收
        bizReturnReceiptDetails= bizReturnReceiptDetails.stream()
                .collect(Collectors.groupingBy(BizReturnReceiptDetail::getDayworkId))
                .values() // 获取所有组的键值对集合的值（即每个分组的列表）
                .stream() // 将 Map 的值转换为 Stream
                .map(list -> list.get(0)) // 从每个分组列表中取第一个元素
                .collect(Collectors.toList()); // 收集结果到新的列表
        if(bizReturnReceiptDetails.size()==0){
            // 将 dayworkId 列表转换为 Set 以提高搜索效率
            Set<Long> dayworkIdSet = new HashSet<>(dayworkIds);
            // 使用 stream() 和 filter() 筛选 dayworkCarrierList 中的 code
            List<String> filteredCodes = dayworkCarrierListr.stream()
                    .filter(carrier -> dayworkIdSet.contains(carrier.getDayworkId()))
                    .map(BizDayworkCarrier::getCarrierCode) // 假设 getCode() 返回 DayworkCarrier 对象的 code 属性
                    .collect(Collectors.toList());

            //将未收回的箱号拼接
            // 将整数转换为字符串
            String str = String.join(", ", filteredCodes);
            return error("箱号《"+str+"》未回收无法打印");
        }

        // 这段我新加的，没意义


        dayworkIds = bizReturnReceiptDetails.stream()
                .map(BizReturnReceiptDetail::getDayworkId) // 假设 getDayworkId() 返回 dayworkId
                .collect(Collectors.toList());

//        /*  20240614 箱码收回后可以打印
        //如果有未回收的则不能打印
        if(dayworkIds.size()!=0){
        // 将 dayworkId 列表转换为 Set 以提高搜索效率
        Set<Long> dayworkIdSet = new HashSet<>(dayworkIds);
        // 使用 stream() 和 filter() 筛选 dayworkCarrierList 中的 code
        List<String> filteredCodes = dayworkCarrierListr.stream()
                .filter(carrier -> dayworkIdSet.contains(carrier.getDayworkId()))
                .map(BizDayworkCarrier::getCarrierCode) // 假设 getCode() 返回 DayworkCarrier 对象的 code 属性
                .collect(Collectors.toList());

            //将未收回的箱号拼接
            String str =  String.join(", ", filteredCodes);
            return error("箱号《"+str+"》未回收无法打印");

        }
//        */

        return success();
    }

    @PostMapping("/whether")
    @Log(title = "判断载具码是否可打印", businessType = BusinessType.SELECT)
    public AjaxResult whether2(@RequestBody List<BizCarrier> carrierList) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        /**  判断载具是否可以打印 **/
        List<Long> ids = carrierList.stream().map(BizCarrier::getId).collect(Collectors.toList());
        //先查询载具是否绑定了批次，获取到dayworkId
        List<BizDayworkCarrier> dayworkCarrierListr = bizDayworkCarrierService.query().in("carrier_id", ids).eq("deleted", 0).eq("is_changed", 0).list();
        if(dayworkCarrierListr.size()==0){
            return success(true);
        }

        //获取dayworkIds
        List<Long> dayworkIds = dayworkCarrierListr.stream().map(BizDayworkCarrier::getDayworkId).collect(Collectors.toList());

        //根据dayworkId查询是否从外协发出
        List<BizOutsourcedOrderDetail> outsourcedOrderDetails = bizOutsourcedOrderDetailService.query().in("daywork_id", dayworkIds).eq("deleted", 0).list();
        if(outsourcedOrderDetails.size()==0){
            return success(true);
        }
        dayworkIds=outsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList());
        List<BizReturnReceiptDetail> bizReturnReceiptDetails =  bizReturnReceiptDetailService.query().in("daywork_id", dayworkIds).eq("deleted", 0).list();

        // 判断没有任何发出单没有回收单则可以发出
        // 有任何发出单
        List<BizOutsourcedOrderDetail> unreturned = outsourcedOrderDetails.stream().filter(v -> bizReturnReceiptDetails.stream().filter(e -> e.getIsAudit().equals(1)).noneMatch(e -> e.getOutsourceDetailId().equals(v.getId()))).collect(Collectors.toList());
        if (!unreturned.isEmpty()) {
            dayworkIds = unreturned.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList());
            Set<Long> dayworkIdSet = new HashSet<>(dayworkIds);
            List<String> filteredCodes = dayworkCarrierListr.stream()
                    .filter(carrier -> dayworkIdSet.contains(carrier.getDayworkId()))
                    .map(BizDayworkCarrier::getCarrierCode) // 假设 getCode() 返回 DayworkCarrier 对象的 code 属性
                    .distinct().collect(Collectors.toList());

            //将未收回的箱号拼接
            String str =  String.join(", ", filteredCodes);
            return error("箱号《"+str+"》未回收无法打印");
        }

        return success();
    }
}
