package cn.ezhizao.project.business.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
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.BizOutsourcedOrderDetail;
import cn.ezhizao.project.business.domain.BizOutsourcedOrderDetailProcess;
import cn.ezhizao.project.business.domain.BizReturnReceiptDetail;
import cn.ezhizao.project.business.service.IBizDayworkItemService;
import cn.ezhizao.project.business.service.IBizDayworkService;
import cn.ezhizao.project.business.service.IBizOutsourcedOrderDetailProcessService;
import cn.ezhizao.project.business.service.IBizReturnReceiptDetailService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
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-08
 */
@RestController
@RequestMapping("/business/returnReceiptDetail")
public class BizReturnReceiptDetailController extends BaseController
{
    @Resource
    private IBizReturnReceiptDetailService bizReturnReceiptDetailService;
    @Resource
    private IBizDayworkItemService bizDayworkItemService;
    @Resource
    private IBizDayworkService bizDayworkService;
    @Resource
    private IBizOutsourcedOrderDetailProcessService bizOutsourcedOrderDetailProcessService;

    /**
     * 查询外协单从列表
     */
    @PreAuthorize("@ss.hasPermi('business:returnReceiptDetail:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizReturnReceiptDetail bizReturnReceiptDetail) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizReturnReceiptDetail);
        if(bizReturnReceiptDetail.getStartTime()!=null) {
            bizReturnReceiptDetail.setStartTime(bizReturnReceiptDetail.getStartTime()+ " 00:00:00");
        }
        if(bizReturnReceiptDetail.getEndTime()!=null) {
            bizReturnReceiptDetail.setEndTime(bizReturnReceiptDetail.getEndTime()+ " 23:59:59");
        }
        startPage();
        List<BizReturnReceiptDetail> list = bizReturnReceiptDetailService.getList(bizReturnReceiptDetail);
        return getDataTable(list);
    }

    /**
     * 导出外协单从列表
     */
    @PreAuthorize("@ss.hasPermi('business:returnReceiptDetail:export')")
    @Log(title = "外协单从", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizReturnReceiptDetail bizReturnReceiptDetail) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizReturnReceiptDetail);
        List<BizReturnReceiptDetail> list = bizReturnReceiptDetailService.getList(bizReturnReceiptDetail);
        ExcelUtil<BizReturnReceiptDetail> util = new ExcelUtil<BizReturnReceiptDetail>(BizReturnReceiptDetail.class);
        util.exportExcel(response, list, "外协单从数据");
    }

    /**
     * 获取外协单从详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:returnReceiptDetail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizReturnReceiptDetailService.getById(id));
    }

    /**
     * 新增外协单从
     */
    @PreAuthorize("@ss.hasPermi('business:returnReceiptDetail:add')")
    @Log(title = "外协单从", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizReturnReceiptDetail bizReturnReceiptDetail) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizReturnReceiptDetail);
        return toAjax(bizReturnReceiptDetailService.save(bizReturnReceiptDetail));
    }

    /**
     * 修改外协单从
     */
    @PreAuthorize("@ss.hasPermi('business:returnReceiptDetail:edit')")
    @Log(title = "外协单从", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizReturnReceiptDetail bizReturnReceiptDetail) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizReturnReceiptDetail);
        return toAjax(bizReturnReceiptDetailService.updateById(bizReturnReceiptDetail));
    }
    @GetMapping("/getReturnReceiptDetail")
    public AjaxResult getReturnReceiptDetail(BizOutsourcedOrderDetail bizOutsourcedOrderDetail)
    {
        List<BizReturnReceiptDetail> list = bizReturnReceiptDetailService.query().eq("outsource_detail_id", bizOutsourcedOrderDetail.getId()).list();
        list.stream().forEach(item->{
            if(item.getAuditNum() == 0){
                item.setAuditNum(item.getReceiptNum());
            }
        });
        return success(list);
    }
    @PostMapping("/saveOrUpdateDetail")
    @Transactional
    public AjaxResult save(@RequestBody BizReturnReceiptDetail bizReturnReceiptDetail) throws ParseException {
        //修改回收明细
        List<BizReturnReceiptDetail> oldList = bizReturnReceiptDetailService.query().eq("outsource_detail_id", bizReturnReceiptDetail.getOutsourceDetailId()).list();
        //查找发出单的工序
        List<BizOutsourcedOrderDetailProcess> bizOutsourcedOrderDetailProcess = bizOutsourcedOrderDetailProcessService.query().eq("detail_id", bizReturnReceiptDetail.getOutsourceDetailId()).list();
        saveOrUpdateBatch(bizReturnReceiptDetailService, bizReturnReceiptDetail.getDetailList(), oldList);
        //将dayworkItem外协报工状态改成3,添加工时,审核数量设置成合格数
        //找到要修改的报工记录
        List<Long> dayworkListIds = new ArrayList<>();
        dayworkListIds.add(bizReturnReceiptDetail.getDayworkId());
        List<BizDayworkItem> dayworkItem = bizDayworkItemService.getListByDayworkIdsForOutsourced(dayworkListIds);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date2 = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
        if(bizReturnReceiptDetail.getDetailList().size()>0) {
            for (BizDayworkItem item : dayworkItem) {
                for (BizReturnReceiptDetail info : bizReturnReceiptDetail.getDetailList()) {
                    if (item.getProcessStepNumber().equals(info.getProcessStepNumber())) {
                        item.setStatus("3");
                        item.setEndTime(date2);
                        item.setNickName("外协");
                        item.setQualifiedNum(info.getAuditNum());
                        long timeDifference = date2.getTime() - item.getStartTime().getTime();
                        item.setWorkingHours(timeDifference);
                    }
                }
            }
        }else{
            //做了反选，删除了明细,重新给dayworkItem赋值,把发出单工序的投入数和合格数置为0
            for (BizDayworkItem item : dayworkItem) {
                for (BizOutsourcedOrderDetailProcess info : bizOutsourcedOrderDetailProcess) {
                    if (item.getProcessStepNumber().equals(info.getProcessStepNumber())) {
                        item.setStatus("1");
                        item.setEndTime(simpleDateFormat.parse("0000-00-00 00:00:00.000000"));
                        item.setNickName("");
                        item.setQualifiedNum(0);
                        item.setWorkingHours(0L);
                    }
                }
            }
            bizOutsourcedOrderDetailProcess.stream().forEach(item->{item.setStatus(0);item.setProductionNum(0);item.setQualifiedNum(0);item.setLoss(BigDecimal.valueOf(0));});
            bizOutsourcedOrderDetailProcessService.updateBatchById(bizOutsourcedOrderDetailProcess);
        }
        bizDayworkItemService.updateBatchById(dayworkItem);
        return success();
    }

    /**
     * 删除外协单从
     */
    @PreAuthorize("@ss.hasPermi('business:returnReceiptDetail:remove')")
    @Log(title = "外协单从", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        //通过outsourceDetailId删除
        List<Long> outsourceDetailId = bizReturnReceiptDetailService.query().eq("outsource_detail_id", ids.get(0)).list().stream().map(BizReturnReceiptDetail::getId).collect(Collectors.toList());
        return toAjax(bizReturnReceiptDetailService.removeBatchByIds(outsourceDetailId));
    }
    @PostMapping("/saveDetails")
    public AjaxResult saveDetails(@RequestBody List<BizReturnReceiptDetail> bizReturnReceiptDetail) throws NoSuchFieldException, IllegalAccessException, ParseException {
        List<BizReturnReceiptDetail> oldList = bizReturnReceiptDetailService.query().eq("outsource_detail_id", bizReturnReceiptDetail.get(0).getOutsourceDetailId()).list();
        bizReturnReceiptDetail.stream().forEach(item->{item.setIsAudit(1);});
        saveOrUpdateBatch(bizReturnReceiptDetailService, bizReturnReceiptDetail, oldList);
        //将dayworkItem外协报工状态改成3,添加工时,审核数量设置成合格数
        //找到要修改的报工记录
        List<Long> dayworkListIds = bizReturnReceiptDetail.stream().map(BizReturnReceiptDetail::getDayworkId).distinct().collect(Collectors.toList());
        List<BizDayworkItem> dayworkItem = bizDayworkItemService.getListByDayworkIdsForOutsourced(dayworkListIds);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date2 = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
            for (BizDayworkItem item : dayworkItem) {
                for (BizReturnReceiptDetail info : bizReturnReceiptDetail) {
                    if (item.getProcessStepNumber().equals(info.getProcessStepNumber())) {
                        item.setStatus("3");
                        item.setEndTime(date2);
                        item.setNickName("外协");
                        item.setQualifiedNum(info.getAuditNum());
                        long timeDifference = date2.getTime() - item.getStartTime().getTime();
                        item.setWorkingHours(timeDifference);
                }
            }
        }
        bizDayworkItemService.updateBatchById(dayworkItem);
        return success();
    }
    @PostMapping("/saveDetailsForAdd")
    public AjaxResult saveDetailsForAdd(@RequestBody List<BizReturnReceiptDetail> bizReturnReceiptDetail) throws NoSuchFieldException, IllegalAccessException, ParseException {
        bizReturnReceiptDetail.stream().forEach(item->{item.setIsAudit(1);});
        bizReturnReceiptDetailService.saveBatch(bizReturnReceiptDetail);
        //将dayworkItem外协报工状态改成3,添加工时,审核数量设置成合格数
        //找到要修改的报工记录
        List<Long> dayworkListIds = bizReturnReceiptDetail.stream().map(BizReturnReceiptDetail::getDayworkId).distinct().collect(Collectors.toList());
        List<BizDayworkItem> dayworkItem = bizDayworkItemService.getListByDayworkIdsForOutsourced(dayworkListIds);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date2 = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
        for (BizDayworkItem item : dayworkItem) {
            for (BizReturnReceiptDetail info : bizReturnReceiptDetail) {
                if (item.getProcessStepNumber().equals(info.getProcessStepNumber())) {
                    item.setStatus("3");
                    item.setEndTime(date2);
                    item.setNickName("外协");
                    item.setQualifiedNum(info.getAuditNum());
                    long timeDifference = date2.getTime() - item.getStartTime().getTime();
                    item.setWorkingHours(timeDifference);
                }
            }
        }
        bizDayworkItemService.updateBatchById(dayworkItem);
        return success();
    }
}


