package com.dk.mdm.service.pur;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dk.common.exception.BaseBusinessException;
import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.convert.pur.PurChaseConvert;
import com.dk.mdm.infrastructure.convert.pur.PurChaseItemConvert;
import com.dk.mdm.mapper.common.CommonMapper;
import com.dk.mdm.mapper.pur.PurchaseItemMapper;
import com.dk.mdm.model.pojo.pur.Purchase;
import com.dk.mdm.mapper.pur.PurchaseMapper;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.pojo.pur.PurchaseItem;
import com.dk.mdm.model.pojo.sale.Order;
import com.dk.mdm.model.query.pur.PurchaseItemQuery;
import com.dk.mdm.model.query.pur.PurchaseQuery;
import com.dk.mdm.model.response.pur.PurchaseItemResponse;
import com.dk.mdm.model.response.pur.PurchaseResponse;
import com.dk.mdm.model.vo.ivt.InboundItemVO;
import com.dk.mdm.model.vo.ivt.InboundVO;
import com.dk.mdm.model.vo.pur.PurchaseItemVO;
import com.dk.mdm.model.vo.pur.PurchaseVO;
import com.dk.mdm.service.common.CommonService;
import com.dk.mdm.service.ivt.inbound.InboundItemService;
import com.dk.mdm.service.ivt.inbound.InboundService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
public class PurchaseService extends BaseService<Purchase> {

    @Override
    public BaseMapper<Purchase> getRepository() {
        return purchaseMapper;
    }

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private PurChaseConvert purChaseConvert;

    @Autowired
    private PurChaseItemConvert purchaseItemConvert;

    @Autowired
    private PurchaseItemMapper purchaseItemMapper;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private PurchaseItemService purchaseItemService;

    @Autowired
    private InboundService inboundService;

    @Autowired
    private InboundItemService inboundItemService;

    /**
     * @desc : 条件查询
     * @author : 常皓宁
     * @date : 2024/2/28 9:47
     */
    @Pagination
    public ResponseResultVO<PageList<PurchaseResponse>> selectByCond(PurchaseQuery purchaseQuery) {
        return super.mergeListWithCount(purchaseQuery, purchaseMapper.selectByCond(purchaseQuery), purchaseMapper.countByCond(purchaseQuery));
    }
    /**
     * @desc : 条件查询 带明细（采购入库 查询采购订单 过滤已入库数据）
     * @author : 王英杰
     * @date : 2024/2/28 9:47
     */
    @Pagination
    public ResponseResultVO<PageList<Map<String, Object>>> selectByCondItem(PurchaseQuery purchaseQuery) {
        return super.mergeListWithCount(purchaseQuery, purchaseMapper.selectPurOrderAndDeatil(purchaseQuery), purchaseMapper.countByCond(purchaseQuery));
    }
    /**
     * @desc : 采购订单 待入库查询
     * @author : 王英杰
     * @date : 2024/2/28 9:46
     */
    @Pagination
    public ResponseResultVO<PageList<PurchaseResponse>> noStoredSelectByCond(PurchaseQuery purchaseQuery) {
        return super.mergeListWithCount(purchaseQuery, purchaseMapper.noStoredSelectByCond(purchaseQuery), purchaseMapper.noStoredCountByCond(purchaseQuery));
    }

    /**
     * @desc : 新建
     * @author : 常皓宁
     * @date : 2024/2/28 9:42
     */
    @Transactional(rollbackFor = {Exception.class})
    public ResponseResultVO<Boolean> insert(PurchaseVO purchasevo) {
        //region  组织结构不能为空
        if (purchasevo.getOrgId() == null) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ORGANIZATION_CANNOT_BE_EMPTY.getMessage());
        }
        //endregion

        //region  员工不能为空
        if (purchasevo.getStaffId() == null) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.STAFF_CANNOT_BE_EMPTY.getMessage());
        }
        //endregion

        //region  供应商不能为空
        if (purchasevo.getSupId() == null) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.SUPLIER_CANNOT_BE_EMPTY.getMessage());
        }
        //endregion

        //region 设置采购订单总单信息并新建
        // 制单时间
        purchasevo.setMakeTime(LocalDateTime.now());
        // 单据类型
        purchasevo.setPurType(Constant.DocumentType.PUR_CHASE.getName());
        // 入库状态
        purchasevo.setIntoStatus(Constant.IntoStatus.DAIRUKU.getName());
        // 订单状态
        purchasevo.setPurStatus(Constant.OrderStatus.STATUS_DEAL.getName());
        // 获取单号
        Map<String, Object> codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.PURCHASE.getName(), false);
        purchasevo.setPurId(codeMap.get("outId").toString());
        purchasevo.setPurNo(codeMap.get("outNote").toString());
        Purchase purchase = purChaseConvert.convertToPo(purchasevo);
        super.insert(purchase);
        //endregion
        //region 设置采购订单明细信息并新建
//        List<PurchaseItemVO> purchaseItemVOList = purchasevo.getPurchaseItemVOList().stream().filter(it -> it.getItemId() == null).collect(Collectors.toList());
        List<PurchaseItemVO> purchaseItemVOList = purchasevo.getPurchaseItemVOList();
        // 商品顺序
        for (PurchaseItemVO purchaseItemVO : purchaseItemVOList) {
            PurchaseItem purchaseItem = purchaseItemConvert.convertToPo(purchaseItemVO);
            purchaseItem.setPurId(purchase.getPurId());
            purchaseItem.setItemIndex(purchaseItemVO.getItemIndex());
            purchaseItem.setIntoStatus(Constant.IntoStatus.DAIRUKU.getName());
            purchaseItem.setCpId(purchase.getCpId());
            purchaseItem.setItemId(null);
            purchaseItem.setPriceDiscount(purchaseItemVO.getPriceDiscount());
            purchaseItemMapper.insert(purchaseItem);
        }
        //endregion
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 新建
     * @author : 常皓宁
     * @date : 2024/2/28 9:42
     */
    @Transactional(rollbackFor = {Exception.class})
    public ResponseResultVO<Boolean> soldAndPurchasedInsert(PurchaseVO purchasevo) {
        this.insert(purchasevo);
        return ResponseResultUtil.success();
    }


    /**
     * @desc : 根据总单id查询
     * @author : 常皓宁
     * @date : 2024/2/29 9:56
     */
    public ResponseResultVO selectById(String purId) {
        //根据id查询
        PurchaseResponse purchaseResponse = purchaseMapper.selectById(purId);
        //不存在
        if (purchaseResponse == null) {
            return ResponseResultUtil.error(ErrorCodeEnum.PURCHASE_CANNOT_BE_EMPTY.getCode(),
                    ErrorCodeEnum.PURCHASE_CANNOT_BE_EMPTY.getMessage());
        }
        //查询明细
        List<PurchaseItemResponse> purchaseItemResponses = purchaseItemMapper.selectByCond(new PurchaseItemQuery().setPurId(purId));
        for (PurchaseItemResponse item : purchaseItemResponses) {
            item.setPurNo(purchaseResponse.getPurNo());
        }
        purchaseResponse.setPurchaseItemResponseList(purchaseItemResponses);
        return ResponseResultUtil.success(purchaseResponse);
    }


    /**
     * @desc   : 转入库 查询采购订单 总单带明细(过滤明细已入库数据)
     * @author : 王英杰
     * @date   : 2024/2/28 14:56
     */
    public ResponseResultVO purSelectById(String purId) {
        //根据id查询
        PurchaseResponse purchaseResponse = purchaseMapper.selectById(purId);
        //不存在
        if (purchaseResponse == null) {
            return ResponseResultUtil.error(ErrorCodeEnum.PURCHASE_CANNOT_BE_EMPTY.getCode(),
                    ErrorCodeEnum.PURCHASE_CANNOT_BE_EMPTY.getMessage());
        }
        //查询明细 (过滤掉已入库数据)
        List<PurchaseItemResponse> purchaseItemResponses = purchaseItemMapper.purSelectByCond(new PurchaseItemQuery().setPurId(purId));
        for (PurchaseItemResponse item : purchaseItemResponses) {
            item.setPurNo(purchaseResponse.getPurNo());
        }
        purchaseResponse.setPurchaseItemResponseList(purchaseItemResponses);
        return ResponseResultUtil.success(purchaseResponse);
    }

    /**
     * @desc : 编辑方法
     * @author : 常皓宁
     * @date : 2024/2/28 10:57
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<Boolean> update(PurchaseVO purchasevo) {
        // 转化实体
        Purchase purchase = purChaseConvert.convertToPo(purchasevo);
        //删除的
        List<PurchaseItemVO> deletePurchaseItemVOList = purchasevo.getDeletePurchaseItemList().stream().filter(it -> it.getItemId() != null).collect(Collectors.toList());
        if (deletePurchaseItemVOList.size() > 0) {
            for (PurchaseItemVO purchaseItemVO : deletePurchaseItemVOList) {
                // 非待入库单据不能删除
                if (!Constant.IntoStatus.DAIRUKU.getName().equals(purchaseItemVO.getIntoStatus())) {
                    throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.NO_WAIT_INTO.getMessage());
                } else {
                    purchaseItemMapper.deleteById(purchaseItemVO.getItemId());
                }
            }
        }
        // 编辑的（包括新增的）
        // 新增的
        List<PurchaseItemVO> insertPurchaseItemVOList = purchasevo.getEditPurchaseItemList().stream().filter(it -> it.getItemId() == null).collect(Collectors.toList());
        for (PurchaseItemVO purchaseItemVO : insertPurchaseItemVOList) {
            PurchaseItem purchaseItem = purchaseItemConvert.convertToPo(purchaseItemVO);
            purchaseItem.setPurId(purchase.getPurId());
            purchaseItem.setItemIndex(purchaseItemVO.getItemIndex());
            purchaseItem.setIntoStatus(Constant.IntoStatus.DAIRUKU.getName());
            purchaseItem.setCpId(purchase.getCpId());
            purchaseItem.setFromId(purchaseItemVO.getFromId());
            purchaseItem.setFromItemId(purchaseItemVO.getFromItemId());
            purchaseItem.setPriceDiscount(purchaseItemVO.getPriceDiscount());
            purchaseItemMapper.insert(purchaseItem);
        }
        // 编辑的
        List<PurchaseItemVO> editPurchaseItemVOList = purchasevo.getEditPurchaseItemList().stream().filter(it -> it.getItemId() != null).collect(Collectors.toList());
        for (PurchaseItemVO purchaseItemVO : editPurchaseItemVOList) {
            // 商品数量不能小于可转入库数量数量(入库中+已入库)
            if (purchaseItemVO.getItemQty().compareTo(purchaseItemVO.getIntoQty().add(purchaseItemVO.getIntoingQty())) == -1) {
                throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ITEMQTY_NO_LESS_INTOQTY.getMessage());
            } else {
                PurchaseItem purchaseItem = purchaseItemConvert.convertToPo(purchaseItemVO);
                purchaseItemService.updataById(purchaseItem);
            }
        }
        return ResponseResultUtil.success(super.update(purchase, new UpdateWrapper<Purchase>().lambda().eq(Purchase::getPurId,
                UUID.fromString(purchase.getPurId ()))));
    }

    /**
     * @desc : 作废
     * @author : 常皓宁
     * @date : 2024-03-08 16:38
     */
    public ResponseResultVO<?> invalid(String id) {
        Purchase purForUpdate = purchaseMapper.selectByIdForUpdate(id);
        // 并发校验
        if (!purForUpdate.getFlgValid()) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ISFLGVALID_FALSE.getMessage());
        }

        // 如果入库中数量或已入库数量不是0，不能作废
        if (purForUpdate.getIntoQty().compareTo(BigDecimal.ZERO) != 0 || purForUpdate.getIntoingQty().compareTo(BigDecimal.ZERO) != 0) {
            throw new BaseBusinessException(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.ISEXISTS_AFTER_OPERATE.getMessage());
        }
        // 作废
        Purchase purUpdate = new Purchase();
        purUpdate.setFlgValid(false).setPurId(id);
        super.update(purUpdate, new UpdateWrapper<Purchase>().lambda().eq(Purchase::getPurId,
                UUID.fromString(purUpdate.getPurId ())));
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 采购订单 转 采购入库   （目前废弃）
     * @author : 王英杰
     * @date : 2024年3月11日
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<Boolean> insertInbound(PurchaseVO purchasevo) {
        ResponseResultVO<Boolean> result = new ResponseResultVO<>();

        // todo 给 inboundVO 实体放入数据
        InboundVO inboundVO = convertEntity(purchasevo); //转换实体
        inboundService.insert(inboundVO); //新建入库单
        //TODO 反更 采购订单 状态为已入库
//        PurchaseService.update(purchasevo);
        // 检查入库单是否成功插入
        if (inboundVO.getIntoId() != null) { //插入入库单成功
            List<InboundItemVO> itemList = new ArrayList<>();
            itemList = inboundVO.getItemList();
            for (InboundItemVO objitem : itemList) {
                inboundItemService.insert(objitem); //插入入库单明细
                //todo 插入一个 已入库明细 就要插入一个 库存明细
            }


            result.setData(true);
        } else {
            // 如果入库单插入失败，可以进行相应的处理，比如回滚事务或者返回错误信息
            result.setData(false);
            result.setMessage("插入入库单失败");
        }
        return result;
    }

    /**
     * @desc :  采购订单实体数据 转 入库单数据 （目前废弃）
     * @author : 王英杰
     * @date : 2024年3月11日
     */
    private InboundVO convertEntity (PurchaseVO purchaseVO){
        InboundVO inboundVO = new InboundVO();
        inboundVO.setItemList(convertEntityDetail(purchaseVO.getPurchaseItemVOList()));//转明细实体

        inboundVO.setIntoType("入库类型-采购入库");
        inboundVO.setFromId(purchaseVO.getPurId());
        inboundVO.setFromNo(purchaseVO.getPurNo());
        inboundVO.setOrgId(purchaseVO.getOrgId());
        inboundVO.setStaffId(purchaseVO.getStaffId());
        inboundVO.setCusId("");
        inboundVO.setSupId(purchaseVO.getSupId());
        inboundVO.setIntoStatus("入库状态-已入库");
//        inboundVO.setIntoingQty();  todo 合计 商品入库中数量
 //        inboundVO.setIntoingAmt();  todo 合计 商品入库中金额
        inboundVO.setWhId(purchaseVO.getWhId());
        inboundVO.setIntoDate(LocalDate.now()); //入库时间为当前时间
        inboundVO.setRemarks(purchaseVO.getRemarks());
//        inboundVO.getAnnexPaths(purchaseVO.getAnnexPaths());  todo 附件
        inboundVO.setMakeStaff(purchaseVO.getMakeStaff());
        inboundVO.setMakeTime(purchaseVO.getMakeTime());
        inboundVO.setCpId(purchaseVO.getCpId());

        return inboundVO;
    }
    /**
     * @desc :  采购订单明细实体数据 转 入库单明细数据 （目前废弃）
     * @author : 王英杰
     * @date : 2024年3月11日
     */
    private List<InboundItemVO> convertEntityDetail( List <PurchaseItemVO>  PurchaseItemVOList){
        List<InboundItemVO>  InboundItemVOList =  new ArrayList<>();
        for (int i=0 ; i<PurchaseItemVOList.size() ; i++){
            InboundItemVO inboundItemVO = new InboundItemVO();
            PurchaseItemVO purchaseItemVO = PurchaseItemVOList.get(i);
            inboundItemVO.setIntoId(purchaseItemVO.getPurId());
            inboundItemVO.setIntoType("入库类型-采购入库");
            inboundItemVO.setFromId(purchaseItemVO.getPurId());
            inboundItemVO.setFromItemId(purchaseItemVO.getItemId());
            inboundItemVO.setItemIndex(purchaseItemVO.getItemIndex());
            inboundItemVO.setSkuId(purchaseItemVO.getSkuId());
            inboundItemVO.setPriceInto(purchaseItemVO.getPricePur());
//            inboundItemVO.setNonStdCode();  todo 非标号
            inboundItemVO.setIntoStatus("入库状态-已入库");
            inboundItemVO.setIntoingQty(purchaseItemVO.getItemQty());
            inboundItemVO.setIntoingAmt(purchaseItemVO.getItemAmt());
            inboundItemVO.setRemarks(purchaseItemVO.getRemarks());
//            inboundItemVO.setInvId( );  todo 需要先生成 库存明细 在生成入库明细




            InboundItemVOList.add(inboundItemVO);
        }

        return InboundItemVOList;

    }

    /**
     * @desc   : 采购跟踪
     * @author : 常皓宁
     * @date   : 2024/4/22 10:19
     */
    public ResponseResultVO<PageList> selectTrackReport(Map<String, Object> param) {
        // 获取组合商品
        Map<String, Object> map = purchaseMapper.selectTrackReport(param);
        JSONObject sku = JSONObject.parseObject(map.get("f_query_pur_for_track").toString());
        // 定义返回值
        PageList data = new PageList<>();
        List dataList = sku.get("data") != null ? JSONObject.parseArray(sku.get("data").toString()).toJavaList(Map.class) : new ArrayList();
        // 组装返回值
        data.setList(dataList);
        return ResponseResultUtil.success(data);
    }
}
