package com.sifang.modules.kingdee.service;

import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Record;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.sifang.modules.kingdee.constants.KingDeeConstants;
import com.sifang.modules.kingdee.util.KingDeeUtil;
import com.sifang.modules.kingdee.vo.FNumberVo;
import com.sifang.modules.kingdee.vo.KingDeeResponseVo;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.order.dao.MaterialDeliverDetailDao;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyAllocationOrderDetailDao;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyAllocationOrder;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyAllocationOrderDetail;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyInventoryOrder;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyInventoryOrderDetail;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MisDeliveryService extends BaseService {
    @Autowired
    private MaterialDeliverDetailDao deliverDetailDao;
    @Autowired
    private CrmSupplyAllocationOrderDetailDao allocationDetailDao;

    //新增(盘点.出库)
    public String saveOutOrderToKingDee(CrmSupplyInventoryOrder order, List<CrmSupplyInventoryOrderDetail> details, CrmSupplyWarehouse warehouse) throws Exception {
        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();
        Map<String,Object> data = new HashMap<>();
        data.put("Model",doOrderData(order,details,warehouse));
        KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
        logger.info("saveOrderToKingDee repoResult ={}",gson.toJson(repoResult));
        Map<String,Object> data1 = new HashMap<>();
        data1.put("Ids",repoResult.getId());
        //提交
        KingDeeUtil.kingDeeClitSubmit(gson.toJson(data1),KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
        //审核
        KingDeeUtil.kingDeeClitAudit(gson.toJson(data1),KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
        return repoResult.getId();
    }


    //新增(调拨出库)
    public String saveOutAllocaOrderToKingDee(CrmSupplyAllocationOrder order,List<CrmSupplyAllocationOrderDetail> details, CrmSupplyWarehouse warehouse) throws Exception {
        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();
        Map<String,Object> data = new HashMap<>();
        data.put("Model",doAllocaOrderData(order,details,warehouse));
        KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
        logger.info("saveOrderToKingDee repoResult ={}",gson.toJson(repoResult));
        Map<String,Object> data1 = new HashMap<>();
        data1.put("Ids",repoResult.getId());
        //提交
        KingDeeUtil.kingDeeClitSubmit(gson.toJson(data1),KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
        //审核
        KingDeeUtil.kingDeeClitAudit(gson.toJson(data1),KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
        return repoResult.getId();
    }


    //反审核
    public void unauditOrderToKingDee(String kingDeeId) throws Exception {
        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();
        Map<String,Object> data1 = new HashMap<>();
        data1.put("Ids",kingDeeId);
        String jsonData = gson.toJson(data1);
        KingDeeUtil.kingDeeClitUnAudit(jsonData,KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
    }

    public Map<String,Object> doOrderData(CrmSupplyInventoryOrder order, List<CrmSupplyInventoryOrderDetail> details, CrmSupplyWarehouse warehouse) {
        Map<String,Object> model = new HashMap<>();
        model.put("FBillNo",order.getCode());//单据编号
        model.put("FBillTypeID",new FNumberVo());//单据类型
        model.put("FStockOrgId",new FNumberVo("R001"));//库存组织
        model.put("FDate", DateUtils.formatYMDDateTime(order.getAuditTime()));//日期
        model.put("FOwnerTypeIdHead","BD_OwnerOrg");//货主类型
        model.put("FDeptId",new FNumberVo("D001"));  //领料部门
        List<Map<String,Object>> FEntityList = new ArrayList<>();
        for (CrmSupplyInventoryOrderDetail detail : details) {
            BigDecimal diffAmount = detail.getStock().subtract(detail.getAmount());
            Map<String,Object> FEntity = new HashMap<>();
            FEntity.put("FMaterialId",new FNumberVo(detail.getMaterialCode()));//物料编码
            FEntity.put("FUnitID",new FNumberVo(detail.getUnitCode()));//单位
            FEntity.put("FQty",diffAmount);//实发数量
            FEntity.put("FBaseUnitId",new FNumberVo("Pcs"));//基本单位
            FEntity.put("FStockId",new FNumberVo(warehouse.getNumber()));//发货仓库
            FEntity.put("FOwnerTypeId","BD_OwnerOrg");//货主类型
            FEntity.put("FOwnerId",new FNumberVo("R001"));//货主
            FEntity.put("FStockStatusId",new FNumberVo("KCZT01_SYS"));//库存状态
            FEntity.put("FExtAuxUnitId",new FNumberVo(detail.getUnitCode()));//（辅单位）
            FEntity.put("FExtAuxUnitQty",diffAmount);//实发数量（辅单位）
            FEntity.put("FKEEPERTYPEID","BD_KeeperOrg");//保管者类型
            FEntity.put("FKEEPERID",new FNumberVo("R001"));//保管者
            FEntityList.add(FEntity);
        }
        model.put("FEntity",FEntityList);
        return model;
    }

    public Map<String,Object> doAllocaOrderData(CrmSupplyAllocationOrder order, List<CrmSupplyAllocationOrderDetail> details,CrmSupplyWarehouse warehouse) {
        Map<String,Object> model = new HashMap<>();
        model.put("FBillNo",order.getCode());//单据编号
        model.put("FBillTypeID",new FNumberVo());//单据类型
        model.put("FStockOrgId",new FNumberVo("R001"));//库存组织
        model.put("FDate", DateUtils.formatYMDDateTime(order.getOutTime()));//日期
        model.put("FOwnerTypeIdHead","BD_OwnerOrg");//货主类型
        model.put("FDeptId",new FNumberVo("D001"));  //领料部门
        List<Map<String,Object>> FEntityList = new ArrayList<>();
        for (CrmSupplyAllocationOrderDetail detail : details) {
            Map<String,Object> FEntity = new HashMap<>();
            FEntity.put("FMaterialId",new FNumberVo(detail.getMaterialCode()));//物料编码
            FEntity.put("FUnitID",new FNumberVo(detail.getUnitCode()));//单位
            FEntity.put("FQty",detail.getAmount());//实发数量
            FEntity.put("FBaseUnitId",new FNumberVo("Pcs"));//基本单位
            FEntity.put("FStockId",new FNumberVo(warehouse.getNumber()));//发货仓库
            FEntity.put("FOwnerTypeId","BD_OwnerOrg");//货主类型
            FEntity.put("FOwnerId",new FNumberVo("R001"));//货主
            FEntity.put("FExtAuxUnitQty",detail.getAmount());//（辅单位）
            FEntity.put("FStockStatusId",new FNumberVo("KCZT01_SYS"));//库存状态
            FEntityList.add(FEntity);
        }
        model.put("FEntity",FEntityList);
        return model;
    }

    public static void main(String[] arr) throws Exception {
        CrmSupplyMaterialDeliverOrder order=new CrmSupplyMaterialDeliverOrder();
                CrmSupplyWarehouse warehouse   =new CrmSupplyWarehouse();
                order.setNumber("9090");
                warehouse.setNumber("CK001");
        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();
        Map<String,Object> data = new HashMap<>();
        Map<String,Object> model = new HashMap<>();

        model.put("FBillNo",order.getNumber());//单据编号
        model.put("FBillTypeID",new FNumberVo());//单据类型
        model.put("FStockOrgId",new FNumberVo("R001"));//库存组织
       /* model.put("FStockDirect","");//库存方向*/
        model.put("FDate", "2023-07-18");//日期
     /*   model.put("FBizType","");//业务类型*/
        model.put("FOwnerTypeIdHead","BD_OwnerOrg");//货主类型
        model.put("FDeptId",new FNumberVo("D001"));  //领料部门
        List<Map<String,Object>> FEntityList = new ArrayList<>();
        List<Record> details = new ArrayList<>();
        Record record=new Record();
        record.set("code", "KZH_001");
        record.set("unit_code", "Pcs");
        record.set("out_amount", "12");
        details.add(record);
        for (Record detail : details) {
            Map<String,Object> FEntity = new HashMap<>();
            FEntity.put("FMaterialId",new FNumberVo(detail.getStr("code")));//物料编码
            FEntity.put("FUnitID",new FNumberVo(detail.getStr("unit_code")));//单位
            FEntity.put("FQty",detail.get("out_amount"));//实发数量
            FEntity.put("FBaseUnitId",new FNumberVo("Pcs"));//基本单位
            FEntity.put("FStockId",new FNumberVo(warehouse.getNumber()));//发货仓库
            FEntity.put("FOwnerTypeId","BD_OwnerOrg");//货主类型
            FEntity.put("FOwnerId",new FNumberVo("R001"));//货主
            FEntity.put("FStockStatusId",new FNumberVo("KCZT01_SYS"));//库存状态
          /*  FEntity.put("FKeeperTypeId","BD_OwnerOrg");//保管者类型
            FEntity.put("FKeeperId",new FNumberVo("R001"));//保管者*/
            FEntityList.add(FEntity);
        }
        model.put("FEntity",FEntityList);
        data.put("Model",model);
        KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
        Map<String,Object> data1 = new HashMap<>();
        data1.put("Ids",repoResult.getId());
        //提交
        KingDeeUtil.kingDeeClitSubmit(gson.toJson(data1),KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
        //审核
        KingDeeUtil.kingDeeClitAudit(gson.toJson(data1),KingDeeConstants.MISDELIVERY_FORM_ID, gson, client);
    }
    
    
}
