package com.zfire.mall.manager.logic.front;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.front.*;
import com.zfire.mall.manager.commonmapper.front.CustomerFrontMapper;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.enums.JiaXianStockEnum;
import com.zfire.mall.manager.enums.JiaXianStockTypeEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.CustomerStockService;
import com.zfire.mall.manager.plus.service.CustomerTransferOrderItemService;
import com.zfire.mall.manager.plus.service.CustomerTransferOrderService;
import com.zfire.mall.manager.plus.service.KingDeeCustomerService;
import com.zfire.mall.manager.utils.JiaXianUtils;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class CustomerTransferOrderLogic {

    @Autowired
    CustomerFrontMapper customerFrontMapper;

    @Autowired
    CustomerTransferOrderItemService customerTransferOrderItemService;

    @Autowired
    CustomerTransferOrderService customerTransferOrderService;

    @Autowired
    JiaXianUtils jiaXianUtils;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    CustomerStockService customerStockService;

    @Autowired
    CustomerFrontLogic customerFrontLogic;

    @Autowired
    CustomerFrontOrderLogic customerFrontOrderLogic;

    @Autowired
    KingDeeCustomerService kingDeeCustomerService;


    public IPage<CustomerTransferOrderBean> list(Page page, ZfireParamBean zfireParam) {
        zfireParam = FieldUtils.supplyParam(zfireParam);
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> customers=new ArrayList<>();
        if (adminUser.getIsCustomer()) {
            KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUser.getCustomerId());
            customers.add(kingDeeCustomer.getNumber());
            if (kingDeeCustomer.getJiaxianType().equals("KING")){
                List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getHigherPrantNumber, adminUser.getCustomerNumber()).list();
                if (CollectionUtils.isNotEmpty(list)){
                    list.stream().forEach(item -> customers.add(item.getNumber()));
                }
            }
        }
        IPage<CustomerTransferOrderBean> customerStockBeanIPage = customerFrontMapper.listTransfer(page, zfireParam,customers);
        return customerStockBeanIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(CustomerTransferOrderAddOrUp customerTransferOrderAddOrUp) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (!adminUser.getIsCustomer())
            throw new RemoteServiceException("非经销商无权调拨经销商库存");

        if (!customerTransferOrderAddOrUp.getStockType().equals(JiaXianStockEnum.JIAXIAN.getKey()))
            throw new RemoteServiceException("调拨嘉贤库存到子经销商");

        customerTransferOrderAddOrUp.setCustomerName(adminUser.getCustomerName());
        customerTransferOrderAddOrUp.setCustomerNumber(adminUser.getCustomerNumber());
        customerTransferOrderAddOrUp.setCustomerId(adminUser.getCustomerId());

        String orderId = customerFrontOrderLogic.generateOrder();
        customerTransferOrderAddOrUp.setId("DB" + orderId);

        KingDeeCustomer one = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getNumber, customerTransferOrderAddOrUp.getTransferCustomerNumber())
                .last("limit 1").one();

        customerTransferOrderAddOrUp.setTransferCustomerId(one.getId());
        customerTransferOrderAddOrUp.insert();
        Map<String, String> map = new HashMap<>();
        for (CustomerTransferOrderItem order : customerTransferOrderAddOrUp.getOrders()) {
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, adminUser.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                    .last("limit 1").one();

            String s = map.get(order.getMaterialCode());
            if (StringUtils.isNotEmpty(s))
                throw new RemoteServiceException("不能重复添加同一机型");

            map.put(order.getMaterialCode(), order.getMaterialName());
            if (Convert.toInt(customerStock.getFrontStockNum()) < Convert.toInt(order.getQty()) || order.getQty() <= 0) {
                throw new RemoteServiceException("数量大于可调整数量");
            }

            customerFrontLogic.stockAcc(false, Convert.toInt(order.getQty()), customerTransferOrderAddOrUp.getId(), "调拨单", 1, customerStock.getMaterialId(), customerStock.getCustomerId(), order.getNotes());


            customerStock.setFrontStockNum(customerStock.getFrontStockNum().subtract(new BigDecimal(order.getQty())));
            customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().add(new BigDecimal(order.getQty())));
            customerStock.updateById();
            order.setTransferOrderId(customerTransferOrderAddOrUp.getId());
        }
        customerTransferOrderItemService.saveBatch(customerTransferOrderAddOrUp.getOrders());
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(CustomerTransferOrderAddOrUp customerTransferOrderAddOrUp) {
        customerTransferOrderAddOrUp.updateById();

        List<CustomerTransferOrderItem> customerTransferOrderItems = customerTransferOrderItemService.lambdaQuery().eq(CustomerTransferOrderItem::getTransferOrderId, customerTransferOrderAddOrUp.getId()).list();
        for (CustomerTransferOrderItem order : customerTransferOrderItems) {
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerTransferOrderAddOrUp.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                    .last("limit 1").one();


            customerFrontLogic.stockAcc(true, Convert.toInt(order.getQty()), customerTransferOrderAddOrUp.getId(), "调拨单修改-返回修改前得库存",
                    1, customerStock.getMaterialId(), customerStock.getCustomerId(), order.getNotes());


            customerStock.setFrontStockNum(customerStock.getFrontStockNum().add(new BigDecimal(order.getQty())));
            customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().subtract(new BigDecimal(order.getQty())));

            customerStock.updateById();

        }

        Map<String, String> map = new HashMap<>();
        customerTransferOrderItemService.lambdaUpdate().eq(CustomerTransferOrderItem::getTransferOrderId, customerTransferOrderAddOrUp.getId()).remove();
        for (CustomerTransferOrderItem order : customerTransferOrderAddOrUp.getOrders()) {
            order.setTransferOrderId(customerTransferOrderAddOrUp.getId());

            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, customerTransferOrderAddOrUp.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                    .last("limit 1").one();

            String s = map.get(order.getMaterialCode());
            if (StringUtils.isNotEmpty(s))
                throw new RemoteServiceException("不能重复添加同一机型");

            map.put(order.getMaterialCode(), order.getMaterialName());
            if (Convert.toInt(customerStock.getFrontStockNum()) < Convert.toInt(order.getQty())) {
                throw new RemoteServiceException("数量大于可调整数量");
            }

            customerFrontLogic.stockAcc(false, Convert.toInt(order.getQty()), customerTransferOrderAddOrUp.getId(), "调拨单", 1, customerStock.getMaterialId(), customerStock.getCustomerId(), order.getNotes());


            customerStock.setFrontStockNum(customerStock.getFrontStockNum().subtract(new BigDecimal(order.getQty())));
            customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().add(new BigDecimal(order.getQty())));
            customerStock.updateById();
            order.setTransferOrderId(customerTransferOrderAddOrUp.getId());
        }
        customerTransferOrderItemService.saveBatch(customerTransferOrderAddOrUp.getOrders());
    }

    public CustomerTransferOrderAddOrUp detail(String id) {
        CustomerTransferOrderAddOrUp customerTransferOrderAddOrUp = BeanUtil.toBean(customerTransferOrderService.getById(id), CustomerTransferOrderAddOrUp.class);

        customerTransferOrderAddOrUp.setOrders(customerTransferOrderItemService.lambdaQuery().eq(CustomerTransferOrderItem::getTransferOrderId, customerTransferOrderAddOrUp.getId()).list());
        return customerTransferOrderAddOrUp;
    }

    public void invoice(String id, String status) {
        CustomerTransferOrder byId = customerTransferOrderService.getById(id);
        if (byId.equals("OK"))
            throw new RemoteServiceException("订单状态已变更");
        customerTransferOrderService.lambdaUpdate().eq(CustomerTransferOrder::getId, id)
                .set(CustomerTransferOrder::getStatus, status).update();
    }

    @Transactional(rollbackFor = Exception.class)
    public void examine(String id, String status, String approvalRemark) {
        CustomerTransferOrder byId = customerTransferOrderService.getById(id);
        if (byId.equals("WAIT"))
            throw new RemoteServiceException("订单状态已变更");
        customerTransferOrderService.lambdaUpdate().eq(CustomerTransferOrder::getId, id).set(CustomerTransferOrder::getApprovalRemark, approvalRemark)
                .set(CustomerTransferOrder::getStatus, status).update();

        if (!byId.getStockType().equals("JIAXIAN"))
            return;

        List<MerchantAllocationOrderMainJsonListDto> merchantAllocationOrderMainJsonListDtos = new ArrayList<>();


        MerchantAllocationOrderMainJsonListDto merchantAllocationOrderMainJsonListDto = new MerchantAllocationOrderMainJsonListDto();
        merchantAllocationOrderMainJsonListDto.setComment(byId.getNotes());
        merchantAllocationOrderMainJsonListDto.setUpMerchantCode(byId.getCustomerNumber());
        merchantAllocationOrderMainJsonListDto.setUpMerchantName(byId.getCustomerName());
        merchantAllocationOrderMainJsonListDto.setInMerchantCode(byId.getTransferCustomerNumber());
        merchantAllocationOrderMainJsonListDto.setInMerchantName(byId.getTransferCustomerName());

        List<CustomerTransferOrderItem> list = customerTransferOrderItemService.lambdaQuery().eq(CustomerTransferOrderItem::getTransferOrderId, byId.getId()).list();

        List<MerchantAllocationOrderDetailList> merchantAllocationOrderDetailLists = new ArrayList<>();
        for (CustomerTransferOrderItem customerOrderItem : list) {

            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, byId.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderItem.getMaterialCode())
                    .last("limit 1").one();

            customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().subtract(new BigDecimal(customerOrderItem.getQty())));
            if (Convert.toInt(customerStock.getLockFrontStockNum()) < 0)
                throw new RemoteServiceException("库存数量不够");


            customerStock.updateById();

            CustomerStock customerStockCustomer = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, byId.getTransferCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderItem.getMaterialCode())
                    .last("limit 1").one();


            if (customerStockCustomer == null){
                CustomerStock customerStockTwo = BeanUtil.toBean(customerStock, CustomerStock.class);
                customerStockTwo.setId(null);
                customerStockTwo.setCustomerId(byId.getTransferCustomerId());
                customerStockTwo.setCustomerNumber(byId.getTransferCustomerNumber());
                customerStockTwo.setCustomerName(byId.getTransferCustomerName());
                customerStockTwo.setFrontStockNum(Convert.toBigDecimal(customerOrderItem.getQty()));
                customerStockTwo.insert();
            }else {
                customerStockCustomer.setFrontStockNum(customerStockCustomer.getFrontStockNum().add(Convert.toBigDecimal(customerOrderItem.getQty())));
                customerStockCustomer.updateById();
            }

            customerFrontLogic.stockAcc(true, Convert.toInt(customerOrderItem.getQty()), byId.getId(), "调拨单", 1, customerStock.getMaterialId(), byId.getTransferCustomerId(), customerOrderItem.getNotes());


            MerchantAllocationOrderDetailList merchantAllocationOrderDetailList = new MerchantAllocationOrderDetailList();
            merchantAllocationOrderDetailList.setMaterialCode(customerOrderItem.getMaterialOldNumber());
            merchantAllocationOrderDetailList.setMaterialName(customerOrderItem.getMaterialName());
            merchantAllocationOrderDetailList.setMaterialSpecification(customerOrderItem.getSpecification());
            merchantAllocationOrderDetailList.setDeliveredNumber(customerOrderItem.getQty());
            merchantAllocationOrderDetailList.setComment(customerOrderItem.getNotes());
            merchantAllocationOrderDetailLists.add(merchantAllocationOrderDetailList);
        }
        merchantAllocationOrderMainJsonListDto.setMerchantAllocationOrderDetailList(merchantAllocationOrderDetailLists);


        merchantAllocationOrderMainJsonListDtos.add(merchantAllocationOrderMainJsonListDto);


        try {
            List<String> strings = jiaXianUtils.apiMerchantAllocationOrderSave(merchantAllocationOrderMainJsonListDtos);
            byId.setSyncStatus("OK");
            byId.setJiaxianOrderId(strings.get(0));
            byId.setStatus(status);
            byId.setApprovalRemark(approvalRemark);
            byId.setApprovalTime(new Date());
            byId.updateById();
        } catch (Exception e) {

            throw new RemoteServiceException(e.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void NeExamine(String id, String status, String approvalRemark) {
        CustomerTransferOrder byId = customerTransferOrderService.getById(id);
        if (byId.equals("OK"))
            throw new RemoteServiceException("订单状态已变更");
        customerTransferOrderService.lambdaUpdate().eq(CustomerTransferOrder::getId, id).set(CustomerTransferOrder::getApprovalRemark, approvalRemark)
                .set(CustomerTransferOrder::getStatus, status).update();

        if (!byId.getStockType().equals("JIAXIAN"))
            return;


        List<CustomerTransferOrderItem> list = customerTransferOrderItemService.lambdaQuery().eq(CustomerTransferOrderItem::getTransferOrderId, byId.getId()).list();


        for (CustomerTransferOrderItem customerOrderItem : list) {

            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, byId.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderItem.getMaterialCode())
                    .last("limit 1").one();

            customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().add(new BigDecimal(customerOrderItem.getQty())));
            if (Convert.toInt(customerStock.getLockFrontStockNum()) < 0)
                throw new RemoteServiceException("库存数量不够");


            customerStock.updateById();

            CustomerStock customerStockCustomer = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, byId.getTransferCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, customerOrderItem.getMaterialCode())
                    .last("limit 1").one();


            if (customerStockCustomer == null){
              throw new RemoteServiceException("库存存在问题");
            }else {
                customerStockCustomer.setFrontStockNum(customerStockCustomer.getFrontStockNum().subtract(Convert.toBigDecimal(customerOrderItem.getQty())));
                if (Convert.toInt(customerStockCustomer.getFrontStockNum()) < 0)
                    throw new RemoteServiceException("子经销商已经把库存锁定无法弃审");
                customerStockCustomer.updateById();
            }

            customerFrontLogic.stockAcc(true, Convert.toInt(customerOrderItem.getQty()), byId.getId(), "调拨单", 1, customerStock.getMaterialId(), byId.getTransferCustomerId(), customerOrderItem.getNotes());


            MerchantAllocationOrderDetailList merchantAllocationOrderDetailList = new MerchantAllocationOrderDetailList();
            merchantAllocationOrderDetailList.setMaterialCode(customerOrderItem.getMaterialOldNumber());
            merchantAllocationOrderDetailList.setMaterialName(customerOrderItem.getMaterialName());
            merchantAllocationOrderDetailList.setMaterialSpecification(customerOrderItem.getSpecification());
            merchantAllocationOrderDetailList.setDeliveredNumber(customerOrderItem.getQty());
            merchantAllocationOrderDetailList.setComment(customerOrderItem.getNotes());

        }


        List<String> strings = new ArrayList<>();
        strings.add(byId.getJiaxianOrderId());

        try {
           jiaXianUtils.apiMerchantAllocationOrderRemove(strings);

        } catch (Exception e) {

            throw new RemoteServiceException(e.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        CustomerTransferOrder byId = customerTransferOrderService.getById(id);

        if (byId.getStatus().equals(ExamineStatusEnum.OK.getKey()) )
            throw new RemoteServiceException("订单为通过无法删除");


        List<CustomerTransferOrderItem> list = customerTransferOrderItemService.lambdaQuery().eq(CustomerTransferOrderItem::getTransferOrderId, byId.getId()).list();

        for (CustomerTransferOrderItem order : list) {
            CustomerStock customerStock = customerStockService.lambdaQuery()
                    .eq(CustomerStock::getCustomerNumber, byId.getCustomerNumber())
                    .eq(CustomerStock::getMaterialCode, order.getMaterialCode())
                    .last("limit 1").one();



            customerFrontLogic.stockAcc(true, Convert.toInt(order.getQty()), byId.getId(), "调拨单删除", 1, customerStock.getMaterialId(), byId.getCustomerId(), order.getNotes());


            customerStock.setFrontStockNum(customerStock.getFrontStockNum().add(new BigDecimal(order.getQty())));
            customerStock.setLockFrontStockNum(customerStock.getLockFrontStockNum().subtract(new BigDecimal(order.getQty())));
            customerStock.updateById();

        }


        customerTransferOrderService.removeById(id);
        customerTransferOrderItemService.lambdaUpdate().eq(CustomerTransferOrderItem::getTransferOrderId, byId.getId()).remove();
    }
}
