package com.dayou.service.impl;

import com.dayou.common.BaseEntity;
import com.dayou.dto.TaskRecordDTO;
import com.dayou.entity.*;
import com.dayou.enums.FinanceInvoiceState;
import com.dayou.enums.MainBusinessEnum;
import com.dayou.exception.ErrorCode;
import com.dayou.mapper.ProductionOutWarehouseMapper;
import com.dayou.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayou.utils.DateUtils;
import com.dayou.utils.LoginContext;
import com.dayou.vo.ProductionOutWarehouseApplyVO;
import org.apache.commons.collections.BagUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dayou.utils.ExcelUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.ArrayList;
import org.springframework.transaction.annotation.Transactional;
import com.dayou.enums.BatchTaskTypeEnum;

import static com.dayou.enums.MainBusinessEnum.ASSET_BUSINESS;
import static com.dayou.enums.MainBusinessEnum.PERSONAL_BUSINESS;

/**
 * <p>
 * 产品提前出库申请 服务实现类
 * </p>
 *
 * @author wucl
 * @since 2023-12-12
 */
@Service
public class ProductionOutWarehouseServiceImpl extends ServiceImpl<ProductionOutWarehouseMapper, ProductionOutWarehouse> implements IProductionOutWarehouseService {

    @Autowired
    private ProductionOutWarehouseMapper outWarehouseMapper;

    @Autowired
    private IMajorProductionService majorProductionService;

    @Autowired
    private IOrderFundService orderFundService;

    @Autowired
    private IPersonalService personalService;

    @Override
    @SuppressWarnings("unchecked")
    public Page<ProductionOutWarehouse> selectPage(Page page,ProductionOutWarehouse productionOutWarehouse,String keyword){
        Page<ProductionOutWarehouse>  ret = outWarehouseMapper.getPage(page,productionOutWarehouse,keyword);
        return ret;
    }


    @Override
    public ProductionOutWarehouse detail(Long id){
        return this.getById(id);
    }

    @Transactional
    @Override
    public Boolean add(TaskRecordDTO<ProductionOutWarehouse> taskRecordDTO){
        ProductionOutWarehouse productionOutWarehouse = taskRecordDTO.getTaskData();
        if (productionOutWarehouse.getBusinessType().equals(MainBusinessEnum.MAJOR_BUSINESS.name())){
            MajorProduction production = majorProductionService.getOne(new LambdaQueryWrapper<MajorProduction>().select(MajorProduction::getRepertoryState,MajorProduction::getReportNo)
                    .eq(BaseEntity::getId, productionOutWarehouse.getId())
                    .eq(MajorProduction::getDeleted, Boolean.FALSE));
            if (production!=null && production.getRepertoryState()!=null && !production.getRepertoryState()){
                productionOutWarehouse.setApplyId(LoginContext.getCurrentUserId());
                productionOutWarehouse.setProductionId(productionOutWarehouse.getId());
                productionOutWarehouse.setReportNo(production.getReportNo());
                //获取财务审核人.
                return  this.save(productionOutWarehouse);
            }
        }
        //个贷出库申请 创建应收款
        if (productionOutWarehouse.getBusinessType().equals(PERSONAL_BUSINESS.name())){
            Long businessId = productionOutWarehouse.getBusinessId();
            BigDecimal shouldAmount = productionOutWarehouse.getShouldAmount();
            OrderFund xOrderFund = orderFundService.getOne(new LambdaQueryWrapper<OrderFund>().eq(OrderFund::getBusinessType, PERSONAL_BUSINESS.name()).eq(OrderFund::getBusinessId, businessId).eq(BaseEntity::getDeleted, Boolean.FALSE));
            Personal personal = personalService.getOne(new LambdaQueryWrapper<Personal>().select(Personal::getOrderId, Personal::getLocation).eq(BaseEntity::getId, businessId).eq(BaseEntity::getDeleted, Boolean.FALSE));
            if (xOrderFund==null){
                OrderFund orderFund = new OrderFund();
                orderFund.setBusinessType(PERSONAL_BUSINESS.name());
                orderFund.setBusinessId(businessId);
                orderFund.setOrderName(personal.getLocation());
                orderFund.setOrderId(personal.getOrderId());
                orderFund.setShouldAmount(shouldAmount);
                orderFundService.add(orderFund);
            }else {
                orderFundService.update(new LambdaUpdateWrapper<OrderFund>().set(OrderFund::getShouldAmount,shouldAmount).eq(BaseEntity::getId,xOrderFund.getId()));
            }
            productionOutWarehouse.setApplyId(LoginContext.getCurrentUserId());
            productionOutWarehouse.setOrderId(businessId);
            productionOutWarehouse.setReportNo(personal.getOrderId());
            //获取财务审核人
            return  this.save(productionOutWarehouse);
        }
        // 资产出库申请
        if (productionOutWarehouse.getBusinessType().equals(ASSET_BUSINESS.name())){
            productionOutWarehouse.setApplyId(LoginContext.getCurrentUserId());
//            productionOutWarehouse.setDepartmentCheckState("审核中");
            return this.save(productionOutWarehouse);
        }
        ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"产品不在库存中，还未入库或则已经出库。请确认。");
        return Boolean.FALSE;
    }

    @Override
    public Boolean update(TaskRecordDTO<ProductionOutWarehouse> taskRecordDTO){
        ProductionOutWarehouse productionOutWarehouse = taskRecordDTO.getTaskData();
        ProductionOutWarehouse outWarehouse = this.getById(productionOutWarehouse.getId());
        if (outWarehouse.getProductionOut()){
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"已进行了出库操作，出库申请无法修改。");
            return Boolean.FALSE;
        }
//        productionOutWarehouse.setCheckerId(LoginContext.getCurrentUserId());
//        productionOutWarehouse.setCheckTime(DateUtils.getNowDate());
        if (productionOutWarehouse.getCheckType()){
            productionOutWarehouse.setFinanceCheckerId(LoginContext.getCurrentUserId());
            productionOutWarehouse.setFinanceCheckTime(DateUtils.getNowDate());
            productionOutWarehouse.setFinanceCheckState(productionOutWarehouse.getState());
            productionOutWarehouse.setFinanceReply(productionOutWarehouse.getReply());
        }else{
            productionOutWarehouse.setDepartmentCheckerId(LoginContext.getCurrentUserId());
            productionOutWarehouse.setDepartmentCheckTime(DateUtils.getNowDate());
            productionOutWarehouse.setDepartmentCheckState(productionOutWarehouse.getState());
            productionOutWarehouse.setDepartmentReply(productionOutWarehouse.getReply());
        }
        return  this.updateById(productionOutWarehouse);
    }

    @Override
    public Boolean delete(Long id){
        //逻辑删除
        return this.removeById(id);
    }

    @Override
    public List<ProductionOutWarehouseApplyVO> getList(Long id) {
        List<ProductionOutWarehouseApplyVO> list = outWarehouseMapper.getList(id);
        return list;
    }

    @Override
    public Boolean cancel(Long id) {
        ProductionOutWarehouse outWarehouse = this.getById(id);
        if (outWarehouse.getProductionOut()){
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"已进行了出库操作，出库申请无法撤销。");
        }
        boolean ret = this.removeById(id);
        return ret;
    }

    @Override
    public List<ProductionOutWarehouseApplyVO> getListByBizTypeProductionId(String businessType, Long productionId) {
       return outWarehouseMapper.getListByBizTypeProductionId(businessType,productionId);
    }

    @Override
    public List<ProductionOutWarehouseApplyVO> getPersonalByOrderId(Long orderId) {
        return outWarehouseMapper.getPersonalByOrderId(orderId);
    }
}
