package com.junmp.jyzb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.jyzb.api.bean.req.BaseOrderItemReq;
import com.junmp.jyzb.api.bean.req.BaseOrderReq;
import com.junmp.jyzb.api.exception.enums.CabinetExceptionEnum;
import com.junmp.jyzb.api.exception.enums.OrderExceptionEnum;
import com.junmp.jyzb.entity.Handover;
import com.junmp.jyzb.entity.HandoverBill;
import com.junmp.jyzb.service.HandoverBillService;
import com.junmp.jyzb.service.HandoverService;
import com.junmp.jyzb.mapper.HandoverMapper;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
* @author lxh专属坐骑
* @description 针对表【base_order】的数据库操作Service实现
* @createDate 2023-09-12 12:53:49
*/
@Service
public class HandoverServiceImpl extends ServiceImpl<HandoverMapper, Handover>
    implements HandoverService {

    @Resource
    private HandoverBillService handoverBillService;


    //装备移交申请
    @Override
    public List<String> EquipmentHandover(BaseOrderReq req) {
        //存放主单据和子单据id
        List<String> list=new ArrayList<>();
        //添加单据存储到数据库
        Handover handover = new Handover();
        BeanPlusUtil.copyProperties(req, handover);
        //设置总价格和应出入库数量
        //设置id
        String id= UUID.randomUUID().toString();
        handover.setId(id);
        Integer sumNum=0;
        BigDecimal priceTotal=new BigDecimal(0);
        List<HandoverBill> itemsList=new ArrayList<>();
        //通过遍历批量保存详细信息
        for (BaseOrderItemReq listReq:req.getOrderItemList()) {
            HandoverBill handoverBill = new HandoverBill();
            BeanPlusUtil.copyProperties(listReq, handoverBill);
            handoverBill.setOrderId(handover.getId());
            //将数量和价格进行累加
            sumNum += handoverBill.getNum();
            priceTotal = priceTotal.add(BigDecimal.valueOf(handoverBill.getNum()).multiply(handoverBill.getPrice())) ;
            handoverBill.setCreateTime(DateTimeUtil.getCurrentDateTime());
            itemsList.add(handoverBill);
        }
        handoverBillService.saveBatch(itemsList);
        //设置总价格和总数量
        handover.setPrice(priceTotal);
        handover.setTotalNum(sumNum);
        handover.setCreateTime(DateTimeUtil.getCurrentDateTime());
        //保存
        this.save(handover);
        list.add(handover.getId());
        for (HandoverBill handoverBill :itemsList) {
            list.add(Long.toString(handoverBill.getId()));
        }
        return list;
    }

    //个人装备管理申请单的修改
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean UpdatePersonalEqsOrder(BaseOrderReq req) {
        Handover handover = getById(req.getId());
        if (!req.getExamineState().equals("none"))
        {
            throw new ServiceException(OrderExceptionEnum.ORDER_CAN_NOT_UPDATE);
        }
        List<HandoverBill> list = handoverBillService.list(new LambdaQueryWrapper<HandoverBill>()
                .eq(HandoverBill::getOrderId, req.getId()));

        //idSet中存放的是存在数据库中的子单据中的id（原始的工作单中的数据id）
        Set<Long> idSet =new HashSet<>();
        for (HandoverBill handoverBill :list){
            idSet.add(handoverBill.getId());
        }
        //将该任务单的所有id转换为String,并添加到updateList中，用来判断删除或者修改新增的是否存在
        //判断删除列表是否为空，如果不为空则进行批量删除
        if (ObjectUtil.isNotNull(req.getDeleteList())&& ObjectUtil.isNotEmpty(req.getDeleteList())) {
            //判断传递的list Id是否存在，如果不存在则抛出异常
            for (Long s:req.getDeleteList()){
                if (idSet.contains(s)){
                    //将要删除的装备价格和数据进行查询出来，并别对任务单的总数量和总价格进行更改
                    HandoverBill one = handoverBillService.getOne(new LambdaQueryWrapper<HandoverBill>()
                            .eq(HandoverBill::getOrderId, s));
                    handover.setPrice(handover.getPrice().subtract(one.getPrice().multiply(BigDecimal.valueOf(one.getNum()))));
                    handover.setTotalNum(handover.getTotalNum() - one.getNum());

                }else {
                    throw new ServiceException(CabinetExceptionEnum.PARAMETER_ERROR);
                }
            }
            handoverBillService.removeBatchByIds(req.getDeleteList());
        }
        //对detaillist进行处理
        List<HandoverBill> addList = new ArrayList<>();//新增的
        List<HandoverBill> updateList = new ArrayList<>();//更新
        for (BaseOrderItemReq baseOrderItemReq :req.getOrderItemList()) {
            //判断是否存在，存在则进行修改
            if (idSet.contains(baseOrderItemReq.getId())){
                HandoverBill one = handoverBillService.getOne(new LambdaQueryWrapper<HandoverBill>()
                        .eq(HandoverBill::getId, baseOrderItemReq.getId()));
                BeanPlusUtil.copyProperties(baseOrderItemReq,one);
                //判断数量和价格是否有变动，如果有变动，则将order的总价和总数量进行更新操作，否则不变
                if (one.getNum().equals(baseOrderItemReq.getNum()) && one.getPrice().compareTo(baseOrderItemReq.getPrice())!=0){
                    handover.setPrice(handover.getPrice().subtract(one.getPrice().multiply(BigDecimal.valueOf(one.getNum())))
                            .add(baseOrderItemReq.getPrice().multiply(BigDecimal.valueOf(baseOrderItemReq.getNum()))));
                    handover.setTotalNum(handover.getTotalNum() - one.getNum()+ baseOrderItemReq.getNum());
                }
                one.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                updateList.add(one);
            }else {
                //否则判断id是否为空或者错误，如果为空则添加，不为空则抛出异常
                if (ObjectUtil.isNull(baseOrderItemReq.getId()) || ObjectUtil.isEmpty(baseOrderItemReq.getId())){
                    HandoverBill detail=new HandoverBill();
                    BeanPlusUtil.copyProperties(baseOrderItemReq, detail);
                    detail.setOrderId(req.getId());
                    //将数量和价格进行相加处理
                    handover.setPrice(handover.getPrice().add(baseOrderItemReq.getPrice().multiply(BigDecimal.valueOf(baseOrderItemReq.getNum()))));
                    handover.setTotalNum(handover.getTotalNum() + baseOrderItemReq.getNum());
                    detail.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                    addList.add(detail);
                }else {
                    throw new ServiceException(CabinetExceptionEnum.PARAMETER_ERROR);
                }

            }
        }
        handoverBillService.updateBatchById(updateList);
        handoverBillService.saveBatch(addList);
        BeanPlusUtil.copyProperties(req, handover);
        return this.updateById(handover);
    }
}




