package com.sifang.modules.kingdee.service;

import com.google.gson.Gson;
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.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrderDetail;
import com.sifang.modules.supply.setting.dao.CrmSupplyWarehouseDao;
import com.sifang.modules.supply.setting.entity.CrmSupplySupplier;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
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.*;

@Service
public class MiscellaneousService extends BaseService {

    @Autowired
    private CrmSupplyWarehouseDao warehouseDao;

    //新增(盘点单入库)
    public String saveOrderToKingDee(CrmSupplyInventoryOrder order, List<CrmSupplyInventoryOrderDetail> details) {
        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();
        Map<String,Object> data = new HashMap<>();
        try {
            data.put("ValidateFlag", false);  //是否验证数据合法性标志
            data.put("NumberSearch",false);  //是否用编码搜索基础资料
            data.put("Model",doOrderData(order,details));
            KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.MISCELLANEOUS_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.MISCELLANEOUS_FORM_ID, gson, client);
            //审核
            KingDeeUtil.kingDeeClitAudit(gson.toJson(data1),KingDeeConstants.MISCELLANEOUS_FORM_ID, gson, client);
            return repoResult.getId();
        } catch (Exception e) {
            logger.error("下单入库同步金蝶数据异常 <>>>>>>>>>>>>> {}",e);
            throw new BusinessException("下单入库同步金蝶数据异常");
        }

    }

    //新增(调拨入库)
    public String saveAllocaOrderToKingDee(CrmSupplyAllocationOrder order,List<CrmSupplyAllocationOrderDetail> details) {
        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();
        Map<String,Object> data = new HashMap<>();
        try {
            data.put("ValidateFlag", false);  //是否验证数据合法性标志
            data.put("NumberSearch",false);  //是否用编码搜索基础资料
            data.put("Model",doAllocaOrderData(order,details));
            KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.MISCELLANEOUS_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.MISCELLANEOUS_FORM_ID, gson, client);
            //审核
            KingDeeUtil.kingDeeClitAudit(gson.toJson(data1),KingDeeConstants.MISCELLANEOUS_FORM_ID, gson, client);
            return repoResult.getId();
        } catch (Exception e) {
            logger.error("调拨入库同步金蝶数据异常 <>>>>>>>>>>>>> {}",e);
            throw new BusinessException("调拨入库同步金蝶数据异常");
        }
    }

    //修改(调拨入库)
    public String editAllocaOrderToKingDee(CrmSupplyAllocationOrder order,List<CrmSupplyAllocationOrderDetail> details) throws Exception {
        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();

        //反审核
        Map<String,Object> data1 = new HashMap<>();
        data1.put("Ids",order.getKingDeeId());
        String jsonData = gson.toJson(data1);
        KingDeeUtil.kingDeeClitUnAudit(jsonData,KingDeeConstants.MISCELLANEOUS_FORM_ID, gson, client);

        Map<String,Object> data = new HashMap<>();
        data.put("Model",doAllocaOrderData(order,details));
        KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.MISCELLANEOUS_FORM_ID, gson, client);
        logger.info("saveOrderToKingDee repoResult ={}",gson.toJson(repoResult));
        //提交
        KingDeeUtil.kingDeeClitSubmit(gson.toJson(data1),KingDeeConstants.MISCELLANEOUS_FORM_ID, gson, client);
        //审核
        KingDeeUtil.kingDeeClitAudit(gson.toJson(data1),KingDeeConstants.MISCELLANEOUS_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.MISCELLANEOUS_FORM_ID, gson, client);
    }

    public Map<String,Object> doOrderData(CrmSupplyInventoryOrder order, List<CrmSupplyInventoryOrderDetail> details) {
        Map<String,Object> model = new HashMap<>();

        CrmSupplyWarehouse inWarehouse = warehouseDao.get(order.getWarehouseId());
        model.put("FBillNo",order.getCode());//单据编号
        model.put("FBillTypeID",new FNumberVo("QTRKD01_SYS"));//单据类型
        model.put("FStockOrgId",new FNumberVo("R001"));//库存组织
        model.put("FStockDirect","GENERAL");//库存方向
        model.put("FDate", DateUtils.formatDateTime(order.getAuditTime()));//日期

        model.put("FOwnerTypeIdHead","BD_OwnerOrg");//货主类型
        List<Map<String,Object>> FEntityList = new ArrayList<>();
        for (CrmSupplyInventoryOrderDetail detail : details) {
            BigDecimal diffAmount = detail.getAmount().subtract(detail.getStock());
            Map<String,Object> FEntity = new HashMap<>();
            FEntity.put("FMATERIALID",new FNumberVo(detail.getMaterialCode()));//物料编码
            FEntity.put("FUnitID",new FNumberVo(detail.getUnitCode()));//单位
            FEntity.put("FExtAuxUnitId",new FNumberVo(detail.getUnitCode()));//辅单位
            FEntity.put("FSTOCKID",new FNumberVo(inWarehouse.getNumber()));//收货仓库
            FEntity.put("FSTOCKSTATUSID",new FNumberVo("KCZT01_SYS"));//库存状态
            FEntity.put("FQty",diffAmount);//实收数量
            FEntity.put("FExtAuxUnitQty",diffAmount);//实收数量（辅单位）
            FEntity.put("FOWNERTYPEID","BD_OwnerOrg");//货主类型
            FEntity.put("FOWNERID",new FNumberVo("R001"));//货主
            FEntity.put("FKEEPERTYPEID","BD_KeeperOrg");//保管者类型
            FEntity.put("FKEEPERID",new FNumberVo("R001"));//保管者
            FEntity.put("FInstockDate",DateUtils.formatDateTime(order.getAuditTime()));//入库日期
            FEntity.put("F_QSVH_Base", new FNumberVo("XM0001"));  //项目
            FEntityList.add(FEntity);
        }
        model.put("FEntity",FEntityList);
        return model;
    }

    public Map<String,Object> doAllocaOrderData(CrmSupplyAllocationOrder order,List<CrmSupplyAllocationOrderDetail> details) {
        Map<String,Object> model = new HashMap<>();
//        if (StringUtil.isNotBlank(order.getKingDeeId())) {
//            model.put("FID",order.getKingDeeId());
//        }
        model.put("FBillNo",order.getCode());//单据编号
        model.put("FBillTypeID",new FNumberVo("QTRKD01_SYS"));//单据类型
        model.put("FStockOrgId",new FNumberVo("R001"));//库存组织
        model.put("FStockDirect","GENERAL");//库存方向
        model.put("FDate", DateUtils.formatDateTime(order.getInTime()));//日期
        model.put("FOwnerTypeIdHead","BD_OwnerOrg");//货主类型
        CrmSupplyWarehouse inWarehouse = warehouseDao.get(order.getInWarehouseId());
        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("FExtAuxUnitId",new FNumberVo(detail.getUnitCode()));//辅单位
            FEntity.put("FSTOCKID",new FNumberVo(inWarehouse.getNumber()));//收货仓库
            FEntity.put("FSTOCKSTATUSID",new FNumberVo("KCZT01_SYS"));//库存状态
            FEntity.put("FQty",detail.getInoutAmount());//实收数量
            FEntity.put("FExtAuxUnitQty",detail.getInoutAmount());//实收数量（辅单位）
            FEntity.put("FOWNERTYPEID","BD_OwnerOrg");//货主类型
            FEntity.put("FOWNERID",new FNumberVo("R001"));//货主
            FEntity.put("FKEEPERTYPEID","BD_KeeperOrg");//保管者类型
            FEntity.put("FKEEPERID",new FNumberVo("R001"));//保管者
            FEntity.put("FInstockDate",DateUtils.formatDateTime(order.getInTime()));//入库日期
            FEntity.put("F_QSVH_Base", new FNumberVo("XM0001"));  //项目
            FEntityList.add(FEntity);
        }
        model.put("FEntity",FEntityList);
        return model;
    }

    public static void main(String[] args) {
        try {
            Gson gson = new Gson();
            K3CloudApi client = new K3CloudApi();

            CrmSupplyMaterialDeliverOrder order = new CrmSupplyMaterialDeliverOrder();
            order.setNumber("366524");
            order.setPattern("1");
            order.setReceiveTime(new Date());
            order.setSupplyId("123456789");
            order.setCreateBy("我");
            order.setRemarks("捡的");
            order.setInWarehouseId("987654321");

            Map<String,Object> data = new HashMap<>();
            data.put("ValidateFlag", false);  //是否验证数据合法性标志
            data.put("NumberSearch",false);
            Map<String,Object> model = new HashMap<>();
            if (StringUtil.isNotBlank(order.getKingDeeId())) {
                model.put("FID",order.getKingDeeId());
            }
            model.put("FBillNo",order.getNumber());//单据编号
            model.put("FBillTypeID",new FNumberVo("QTRKD01_SYS"));//单据类型
            model.put("FStockOrgId",new FNumberVo("R001"));//库存组织
            model.put("FStockDirect","GENERAL");//库存方向
            model.put("FDate", DateUtils.formatDateTime(order.getReceiveTime()));//日期
//            model.put("FSUPPLIERID",new FNumberVo(""));//供应商
            model.put("FOwnerTypeIdHead","BD_OwnerOrg");//货主类型
            List<Map<String,Object>> FEntityList = new ArrayList<>();
            Map<String,Object> FEntity = new HashMap<>();
            FEntity.put("FMATERIALID",new FNumberVo("KZH_001"));//物料编码
            FEntity.put("FUnitID",new FNumberVo("8633"));//单位
            FEntity.put("FExtAuxUnitId",new FNumberVo("8633"));//辅单位
            FEntity.put("FSTOCKID",new FNumberVo("CK001"));//收货仓库
            FEntity.put("FSTOCKSTATUSID",new FNumberVo("KCZT01_SYS"));//库存状态
            FEntity.put("FQty",2);//实收数量
            FEntity.put("FExtAuxUnitQty",2);//实收数量（辅单位）
            FEntity.put("FOWNERTYPEID","BD_OwnerOrg");//货主类型
            FEntity.put("FOWNERID",new FNumberVo("R001"));//货主
            FEntity.put("FKEEPERTYPEID","BD_KeeperOrg");//保管者类型
            FEntity.put("FKEEPERID",new FNumberVo("R001"));//保管者
            FEntity.put("FInstockDate",DateUtils.formatDateTime(order.getReceiveTime()));//入库日期
            FEntity.put("F_QSVH_Base", new FNumberVo("XM0001"));  //项目
            FEntityList.add(FEntity);
            model.put("FEntity",FEntityList);

            data.put("Model",model);
            KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.MISCELLANEOUS_FORM_ID, gson, new K3CloudApi());
            Map<String,Object> data1 = new HashMap<>();
            data1.put("Ids",repoResult.getId());
            //提交
            KingDeeUtil.kingDeeClitSubmit(gson.toJson(data1),KingDeeConstants.MISCELLANEOUS_FORM_ID, gson, new K3CloudApi());
            //审核
            KingDeeUtil.kingDeeClitAudit(gson.toJson(data1),KingDeeConstants.MISCELLANEOUS_FORM_ID, gson, new K3CloudApi());


            //禁用
//            Map<String,Object> data = new HashMap<>();
//            data.put("Ids","125286");
//            RepoResult repoResult = KingDeeUtil.kingDeeClitStatusOperation(gson.toJson(data),KingDeeConstants.MISCELLANEOUS_FORM_ID,KingDeeConstants.STATUS_FORBID, gson, new K3CloudApi());


            //反禁用
//            Map<String,Object> data = new HashMap<>();
//            data.put("Ids","125286");
//            RepoResult repoResult = KingDeeUtil.kingDeeClitStatusOperation(gson.toJson(data),KingDeeConstants.MISCELLANEOUS_FORM_ID,KingDeeConstants.STATUS_ENABLE, gson, new K3CloudApi());

            //查看
//            Map<String, Object> data = new HashMap<>();
//            data.put("Id", "125286");
//            String json = gson.toJson(data);
//            RepoResult repoResult =KingDeeUtil.kingDeeClitDetail(json,KingDeeConstants.MISCELLANEOUS_FORM_ID,gson,client);
            System.out.println("saveSupplierToKingDee repoResult ="+gson.toJson(repoResult));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
