package cn.ezhizao.project.business.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.poi.ExcelUtil;
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.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.BizDayworkItem;
import cn.ezhizao.project.business.domain.BizNoCurrentReject;
import cn.ezhizao.project.business.domain.BizOutsourcedOrderDetail;
import cn.ezhizao.project.business.service.IBizDayworkItemService;
import cn.ezhizao.project.business.service.IBizNoCurrentRejectService;
import cn.ezhizao.project.business.service.IBizOutsourcedOrderDetailService;
import cn.ezhizao.project.business.service.IBizSupplierService;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.service.ISysDeptService;
import cn.ezhizao.project.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 非本序废品Controller
 *
 * @author ezhizao
 * @date 2024-05-12
 */
@RestController
@RequestMapping("/business/noCurrentReject")
public class BizNoCurrentRejectController extends BaseController
{
    @Resource
    private IBizNoCurrentRejectService bizNonCurrentRejectService;

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private IBizDayworkItemService bizDayworkItemService;
    @Resource
    private IBizSupplierService bizSupplierService;
    @Resource
    private IBizOutsourcedOrderDetailService bizOutsourcedOrderDetailService;
    @Resource
    private ISysDeptService sysDeptService;

    /**
     * 查询非本序废品列表
     */
    @PreAuthorize("@ss.hasPermi('business:noCurrentReject:list')")
    @GetMapping("/list")
    @Log(title = "查询非本序废品列表", businessType = BusinessType.SELECT)
    public TableDataInfo list(BizNoCurrentReject bizNoCurrentReject) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizNoCurrentReject);
        startPage();
        List<BizNoCurrentReject> list = bizNonCurrentRejectService.getList(bizNoCurrentReject);
        return getDataTable(list);
    }

    /**
     * 导出非本序废品列表
     */
    @PreAuthorize("@ss.hasPermi('business:noCurrentReject:export')")
    @Log(title = "导出非本序废品列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizNoCurrentReject bizNoCurrentReject) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizNoCurrentReject);
        List<BizNoCurrentReject> list = bizNonCurrentRejectService.getList(bizNoCurrentReject);
        ExcelUtil<BizNoCurrentReject> util = new ExcelUtil<BizNoCurrentReject>(BizNoCurrentReject.class);
        util.exportExcel(response, list, "非本序废品数据");
    }

    /**
     * 获取非本序废品详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:noCurrentReject:query')")
    @GetMapping(value = "/{id}")
    @Log(title = "获取非本序废品详细信息", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        BizNoCurrentReject bizNoCurrentReject = bizNonCurrentRejectService.getById(id);
        List<BizDayworkItem> dayworkItemList = bizDayworkItemService.query().eq("daywork_id", bizNoCurrentReject.getDayworkId())
                .eq("process_step_number", bizNoCurrentReject.getProcessStepNumber())
                .in("status", new ArrayList<Integer>(){{add(1);add(2);add(3);}})
                .list();
        SysDept sysDept = sysDeptService.selectDeptById(bizNoCurrentReject.getDeptId());
        if(sysDept.getIsOutsourcing() == 1 || sysDept.getDeptCode().equals("170000")){
            //外协
            bizNoCurrentReject.setIsWx(1);
            List<Long> outsourceDetailIds = dayworkItemList.stream().map(BizDayworkItem::getOutsourceDetailId).collect(Collectors.toList());
            List<BizOutsourcedOrderDetail> outsourceOrderDetailList = bizOutsourcedOrderDetailService.query().in("id", outsourceDetailIds).list();
            List<Long> allSupplierIds = outsourceOrderDetailList.stream().map(BizOutsourcedOrderDetail::getSupplierId).collect(Collectors.toList());
            bizNoCurrentReject.setSupplierList( bizSupplierService.query().in("id", allSupplierIds).list());
        }else{
            //普通报工
            bizNoCurrentReject.setIsWx(0);
            List<BizDayworkItem> newList = new ArrayList<>();
            for(BizDayworkItem dayworkItem : dayworkItemList){
                if(!newList.stream().anyMatch(item -> item.getUserId().equals(dayworkItem.getUserId()))){
                    newList.add(dayworkItem);
                }
            }
            bizNoCurrentReject.setDayworkItemList(newList);
        }

        //普通报工
        if(bizNoCurrentReject.getUserId() != null && !bizNoCurrentReject.getUserId().equals("") && !bizNoCurrentReject.getUserId().equals("0")){
            List<Long> userIds = Arrays.stream(bizNoCurrentReject.getUserId().split(","))
                    .map(String::trim) // 去除多余的空格
                    .filter(s -> !s.isEmpty()) // 过滤空字符串
                    .map(Long::parseLong) // 将字符串转换为 Long
                    .collect(Collectors.toList());
            bizNoCurrentReject.setUserIds(userIds);

        }
        //外协报工
        if(bizNoCurrentReject.getSupplierId() != null && !bizNoCurrentReject.getSupplierId().equals("") && !bizNoCurrentReject.getSupplierId().equals("0")){
            List<Long> supplierIds = Arrays.stream(bizNoCurrentReject.getSupplierId().split(","))
                    .map(String::trim) // 去除多余的空格
                    .filter(s -> !s.isEmpty()) // 过滤空字符串
                    .map(Long::parseLong) // 将字符串转换为 Long
                    .collect(Collectors.toList());
            bizNoCurrentReject.setSupplierIds(supplierIds);

        }
        return success(bizNoCurrentReject);
    }

    @GetMapping(value = "userList/{data}")
    public TableDataInfo getUserList(@PathVariable("data") String data)
    {
        return getDataTable(sysUserService.selectUserByCode(data));
    }
    @GetMapping(value = "/getUserByProcessStepNumber")
    public AjaxResult getUserByProcessStepNumber( BizDayworkItem bizDayworkItem) throws NoSuchFieldException, IllegalAccessException {
        List<BizDayworkItem> dayworkItemList = bizDayworkItemService.query().eq("daywork_id", bizDayworkItem.getDayworkId())
                .eq("process_step_number", bizDayworkItem.getProcessStepNumber())
                .in("status", new ArrayList<Integer>(){{add(1);add(2);add(3);}})
                .list();
        //外协商
        if(bizDayworkItem.getIsWx() == 1){
            List<Long> outsourceDetailIds = dayworkItemList.stream().map(BizDayworkItem::getOutsourceDetailId).collect(Collectors.toList());
            List<BizOutsourcedOrderDetail> outsourceOrderDetailList = bizOutsourcedOrderDetailService.query().in("id", outsourceDetailIds).list();
            List<Long> supplierIds = outsourceOrderDetailList.stream().map(BizOutsourcedOrderDetail::getSupplierId).collect(Collectors.toList());
            return success(bizSupplierService.query().in("id", supplierIds).list());
        }else{
            //普通报工
            List<BizDayworkItem> newList = new ArrayList<>();
           for(BizDayworkItem dayworkItem : dayworkItemList){
               if(!newList.stream().anyMatch(item -> item.getUserId().equals(dayworkItem.getUserId()))){
                   newList.add(dayworkItem);
               }
           }
            return success(newList);
        }
    }
    /**
     * 新增非本序废品
     */
    @PreAuthorize("@ss.hasPermi('business:noCurrentReject:save')")
    @Log(title = "非本序废品保存")
    @PostMapping("/save")
    public AjaxResult save(@RequestBody BizNoCurrentReject bizNoCurrentReject) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizNoCurrentReject);
        if(bizNoCurrentReject.getUserIds() != null && bizNoCurrentReject.getUserIds().size() > 0) {
            String userIdsString = bizNoCurrentReject.getUserIds().stream()
                    .map(String::valueOf).collect(Collectors.joining(","));
            bizNoCurrentReject.setUserId(userIdsString);
            bizNoCurrentReject.setSupplierId("");
        }else{
            bizNoCurrentReject.setUserId("");
        }
        if(bizNoCurrentReject.getSupplierIds() != null && bizNoCurrentReject.getSupplierIds().size() > 0) {
            String supplierIdsString = bizNoCurrentReject.getSupplierIds().stream()
                    .map(String::valueOf).collect(Collectors.joining(","));
            bizNoCurrentReject.setSupplierId(supplierIdsString);
            bizNoCurrentReject.setUserId("");
        }else{
            bizNoCurrentReject.setSupplierId("");
        }
        boolean flag ;
        if(bizNoCurrentReject.getId() != null){
            flag=   bizNonCurrentRejectService.saveOrUpdate(bizNoCurrentReject);
        }else{
            flag= bizNonCurrentRejectService.save(bizNoCurrentReject);
        }
        return toAjax(flag);
    }

    /**
     * 修改非本序废品
     */
    @PreAuthorize("@ss.hasPermi('business:noCurrentReject:edit')")
    @Log(title = "修改非本序废品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizNoCurrentReject bizNoCurrentReject) throws NoSuchFieldException, IllegalAccessException
    {
        if(bizNoCurrentReject.getUserIds() != null && bizNoCurrentReject.getUserIds().size() > 0) {
            String userIdsString = bizNoCurrentReject.getUserIds().stream()
                    .map(String::valueOf).collect(Collectors.joining(","));
            bizNoCurrentReject.setUserId(userIdsString);
            bizNoCurrentReject.setSupplierId("");
        }else{
            bizNoCurrentReject.setUserId("");
        }
        if(bizNoCurrentReject.getSupplierIds() != null && bizNoCurrentReject.getSupplierIds().size() > 0) {
            String supplierIdsString = bizNoCurrentReject.getSupplierIds().stream()
                    .map(String::valueOf).collect(Collectors.joining(","));
            bizNoCurrentReject.setSupplierId(supplierIdsString);
            bizNoCurrentReject.setUserId("");
        }else{
            bizNoCurrentReject.setSupplierId("");
        }
        return toAjax(bizNonCurrentRejectService.updateById(bizNoCurrentReject));
    }

    /**
     * 删除非本序废品
     */
    @PreAuthorize("@ss.hasPermi('business:noCurrentReject:remove')")
    @Log(title = "删除非本序废品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizNonCurrentRejectService.removeBatchByIds(ids));
    }
}
