package cn.ibizlab.businesscentral.core.extensions.service;

import cn.ibizlab.businesscentral.core.odoo_ir.domain.Ir_sequence;
import cn.ibizlab.businesscentral.core.odoo_ir.service.IIr_sequenceService;
import cn.ibizlab.businesscentral.core.odoo_product.domain.Product_product;
import cn.ibizlab.businesscentral.core.odoo_product.domain.Product_supplierinfo;
import cn.ibizlab.businesscentral.core.odoo_product.domain.Product_template;
import cn.ibizlab.businesscentral.core.odoo_purchase.domain.Purchase_order;
import cn.ibizlab.businesscentral.core.odoo_purchase.domain.Purchase_requisition_line;
import cn.ibizlab.businesscentral.core.odoo_purchase.domain.Purchase_requisition_type;
import cn.ibizlab.businesscentral.core.odoo_purchase.service.impl.Purchase_requisitionServiceImpl;
import cn.ibizlab.businesscentral.util.dict.StaticDict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.businesscentral.core.odoo_purchase.domain.Purchase_requisition;
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 org.springframework.context.annotation.Primary;

import java.util.*;

/**
 * 实体[采购申请] 自定义服务对象
 */
@Slf4j
@Primary
@Service("Purchase_requisitionExService")
public class Purchase_requisitionExService extends Purchase_requisitionServiceImpl {

    @Autowired
    IIr_sequenceService sequenceService;

    @Autowired
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_productService productService;

    @Autowired
    protected cn.ibizlab.businesscentral.core.odoo_product.service.IProduct_supplierinfoService supplierinfoService;

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * 自定义行为[Action_cancel]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Purchase_requisition action_cancel(Purchase_requisition et) {
        //purchase_requisition cancel
        List<Purchase_requisition_line> lines = purchaseRequisitionLineService.selectByRequisitionId(et.getId());
        if(lines.size() != 0){
            for(Purchase_requisition_line line : lines){
                //移除 line 关联 supplierinfo,从Product_supplierinfo表中将采购申请所对应的供应商价格记录删除
                supplierinfoService.removeByPurchaseRequisitionLineId(line.getRequisitionId());
            }
        }
        // 取消采购申请所对应的采购订单
        List<Purchase_order> orders = purchaseOrderService.selectByRequisitionId(et.getId());
        for(Purchase_order order : orders){
            purchaseOrderService.button_cancel(order);
            // 本采购申请单相关的采购询价单已取消
        }
//        log.warn("purchase_order");

        et.setState(StaticDict.PURCHASE_REQUISITION__STATE.CANCEL.getValue());
        this.update(et);
        return super.action_cancel(et);
    }

    /**
     * 自定义行为[Action_done]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Purchase_requisition action_done(Purchase_requisition et) {
        List<Purchase_order> orders = purchaseOrderService.selectByRequisitionId(et.getId());
        for (Purchase_order order:orders           ) {
            if(StringUtils.compare(order.getState(),StaticDict.PURCHASE_ORDER__STATE.DRAFT.getValue())==0||StringUtils.compare(order.getState(), StaticDict.PURCHASE_ORDER__STATE.SENT.getValue()
            )==0||StringUtils.compare(order.getState(),StaticDict.PURCHASE_ORDER__STATE.TO_APPROVE.getValue())==0){
                throw new RuntimeException("关闭采购申请单前，你必须取消或批准每个RFQ采购订单。") ;
            }
        }

        List<Purchase_requisition_line> lines = purchaseRequisitionLineService.selectByRequisitionId(et.getId());
        //移除 line 关联 supplierinfo,从Product_supplierinfo中删除相关的记录
        if(lines.size() != 0){
            for(Purchase_requisition_line line : lines){
                supplierinfoService.removeByPurchaseRequisitionLineId(line.getRequisitionId());
            }
        }
//        log.warn("移除 line 关联 supplierinfo");

        et.setState(StaticDict.PURCHASE_REQUISITION__STATE.DONE.getValue());
        this.update(et);
        return super.action_done(et);
    }

    /**
     * 自定义行为[Action_draft]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Purchase_requisition action_draft(Purchase_requisition et) {
        et.setName("New");
        et.setState(StaticDict.PURCHASE_REQUISITION__STATE.DRAFT.getValue());
        this.update(et);
        return super.action_draft(et);
    }

    /**
     * 自定义行为[Action_in_progress]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Purchase_requisition action_in_progress(Purchase_requisition et) {
        et = this.get(et.getId());
        List<Purchase_requisition_line> lines = purchaseRequisitionLineService.selectByRequisitionId(et.getId());
        if (lines.size() == 0) {
            throw new RuntimeException(String.format("没有明细行，无法确认此申请单 '%s'", et.getName()));
        }
        if (StringUtils.compare(et.getQuantityCopy(), StaticDict.PURCHASE_REQUISITION_TYPE__QUANTITY_COPY.NONE.getValue()) == 0 && et.getVendorId() != null) {
            for (Purchase_requisition_line line : lines) {
                if (line.getPriceUnit() <= 0) {
                    throw new RuntimeException("你无法确认没有单价的单一供应商采购申请单。");
                }
                if (line.getProductQty() <= 0) {
                    throw new RuntimeException("你无法确认没有数量的单一供应商采购申请单");
                }

                // 关联 create_supplier_info，调用的是purchase_resquisition_line的_create_supplier_info()方法
                // 向product_supplierinfo表中添加供应商价格记录，在action_done行为时将这些记录删除
                Purchase_requisition purchaseRequisition = this.baseMapper.selectById(line.getRequisitionId());
                Purchase_requisition_type requisitionType = purchaseRequisitionTypeService.get(purchaseRequisition.getTypeId());
                if(StringUtils.compare(requisitionType.getQuantityCopy(), StaticDict.PURCHASE_REQUISITION_TYPE__QUANTITY_COPY.NONE.getValue()) == 0 && purchaseRequisition.getVendorId() != null){
                    Product_supplierinfo supplierinfo = new Product_supplierinfo();
                    supplierinfo.setName(purchaseRequisition.getVendorId());
                    supplierinfo.setProductId(line.getProductId());
                    Product_product product = productService.get(line.getProductId());
                    supplierinfo.setProductTmplId(product.getProductTmplId());
                    supplierinfo.setPrice(line.getPriceUnit());
                    supplierinfo.setCurrencyId(purchaseRequisition.getCurrencyId());
                    supplierinfo.setPurchaseRequisitionLineId(line.getId());
                    // 设置不能为空的值为默认值，sequence,minqty,delay
                    supplierinfo.setSequence(1);
                    supplierinfo.setMinQty(0.0);
                    supplierinfo.setDelay(1);
                    supplierinfoService.create(supplierinfo);
                }
//                log.warn("关联 create_supplier_info");
            }
            et.setState(StaticDict.PURCHASE_REQUISITION__STATE.ONGOING.getValue());
        } else {
            et.setState(StaticDict.PURCHASE_REQUISITION__STATE.IN_PROGRESS.getValue());
        }
        if (StringUtils.compare(et.getName(), "New") == 0) {
            Ir_sequence sequence = new Ir_sequence();
            if (StringUtils.compare(et.getQuantityCopy(), StaticDict.PURCHASE_REQUISITION_TYPE__QUANTITY_COPY.NONE.getValue()) != 0) {
                sequence.setCode("purchase.requisition.purchase.tender");
            } else {
                sequence.setCode("purchase.requisition.blanket.order");
            }
            sequenceService.get_next_by_code(sequence);
            et.setName(sequence.getNextChar());
        }
        this.update(et);
        return super.action_in_progress(et);
    }

    /**
     * 自定义行为[Action_open]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Purchase_requisition action_open(Purchase_requisition et) {
        et.setState("open");
        this.update(et);
        return super.action_open(et);
    }

    @Override
    public boolean remove(Long key) {
        Purchase_requisition et = this.get(key);

        if(StringUtils.compare(et.getState(),StaticDict.PURCHASE_REQUISITION__STATE.DRAFT.getValue())!=0||StringUtils.compare(et.getState(),StaticDict.PURCHASE_REQUISITION__STATE.CANCEL.getValue())!=0){
            throw new RuntimeException("你只能删除草稿申请单。");
        }
        purchaseRequisitionLineService.removeByRequisitionId(key);
        return super.remove(key);
    }

    /**
     * 自定义行为[MasterTabCount]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public Purchase_requisition masterTabCount(Purchase_requisition et) {
        et = this.get(et.getId());

        //采购订单
        if (StringUtils.compare(et.getState(), StaticDict.PURCHASE_REQUISITION__STATE.DRAFT.getValue()) == 0) {
            et.setOrderCount(0);
        } else {
            Purchase_order order = new Purchase_order();
            order.setRequisitionId(et.getId());
            et.setOrderCount(purchaseOrderService.count(new QueryWrapper<Purchase_order>().setEntity(order)));
        }

//        Mail_followersExService.add_default_followers(et);

        return super.masterTabCount(et);
    }

    @Autowired
    Mail_followersExService Mail_followersExService ;


}

