package com.sifang.modules.kingdee.service;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
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.BusinessException;
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.CrmSupplySupplier;
import com.sifang.modules.supply.setting.service.CrmSupplySupplierService;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class PurchaseService extends BaseService {

    @Autowired
    private MaterialDeliverDetailDao deliverDetailDao;
    @Autowired
    private CrmSupplySupplierService supplierService;

    //新增
    public String savePurchaseOrderToKingDee(CrmSupplyMaterialDeliverOrder order)
    {
        try {

            CrmSupplySupplier supplier  = supplierService.getById(order.getSupplyId());
            Gson gson = new Gson();
            K3CloudApi client = new K3CloudApi();
            Map<String,Object> data = new HashMap<>();
            data.put("Model",doPurchaseOrderData(order,supplier));
            KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.PURCHASE_FORM_ID, gson, client);
            logger.info("savePurchaseOrderToKingDee repoResult ={}",gson.toJson(repoResult));
            Map<String,Object> data1 = new HashMap<>();
            data1.put("Ids",repoResult.getId());
            //提交
            KingDeeUtil.kingDeeClitSubmit(gson.toJson(data1),KingDeeConstants.PURCHASE_FORM_ID, gson, client);
            //审核
            KingDeeUtil.kingDeeClitAudit(gson.toJson(data1),KingDeeConstants.PURCHASE_FORM_ID, gson, client);
            return repoResult.getId();
        }catch (Exception e){
            logger.error("采购单同步金蝶数据异常 <>>>>>>>>>>>>> {}",e);
            throw new BusinessException("采购单同步金蝶数据异常");
        }
    }

    //修改
    public void editPurchaseOrderToKingDee(CrmSupplyMaterialDeliverOrder order) throws Exception {
        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();
        CrmSupplySupplier supplier  = supplierService.getById(order.getSupplyId());
        //反审核
        Map<String,Object> data1 = new HashMap<>();
        data1.put("Ids",order.getKingDeeId());
        String jsonData = gson.toJson(data1);
        KingDeeUtil.kingDeeClitUnAudit(jsonData,KingDeeConstants.PURCHASE_FORM_ID, gson, client);

        Map<String,Object> data = new HashMap<>();
        data.put("Model",doPurchaseOrderData(order,supplier));
        KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.PURCHASE_FORM_ID, gson, client);
        logger.info("editPurchaseOrderToKingDee repoResult ={}",gson.toJson(repoResult));
        //提交
        KingDeeUtil.kingDeeClitSubmit(gson.toJson(data1),KingDeeConstants.PURCHASE_FORM_ID, gson, client);
        //审核
        KingDeeUtil.kingDeeClitAudit(gson.toJson(data1),KingDeeConstants.PURCHASE_FORM_ID, gson, client);
    }

    //反审核
    public void unauditPurchaseOrderToKingDee(CrmSupplyMaterialDeliverOrder order) 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.PURCHASE_FORM_ID, gson, client);
    }

    /**
     * 金蝶接口
     */
    public  Map<String,Object> doPurchaseOrderData(CrmSupplyMaterialDeliverOrder order, CrmSupplySupplier supplier) {
        Map<String,Object> model = new HashMap<>();
        if (StringUtil.isNotBlank(order.getKingDeeId())) {
            model.put("FID",order.getKingDeeId());
        }
        model.put("FBillTypeID",new HashMap<>().put("FNUMBER","CGDD01_SYS"));//单据类型
        model.put("FBillNo",order.getNumber());//单据编号
        model.put("FDate", DateUtils.formatDateTime(order.getCreateTime()));//采购日期
        model.put("FSupplierId",new FNumberVo(supplier.getKingDeeNumber()));//供应商
        Map<String,String> purMap = Maps.newHashMap();
            //平台采购
        purMap.put("FNumber","R001");

        model.put("FPurchaseOrgId",purMap);//采购组织 ---能辉光伏编码是R001，如果是平台采购

       // model.put("FPurchaserId",new HashMap<>().put("FNumber",order.getCreator()));//采购员
       // model.put("FProviderId",new HashMap<>().put("FNumber",order.getDeliverId()));//供货方
        List<Map<String,Object>> FPOOrderEntryList = new ArrayList<>();
        List<Record> details = deliverDetailDao.findDetailsByOrderId(order.getId());
        for (Record detail : details) {
            Map<String,Object> FPOOrderEntry = new HashMap<>();
            FPOOrderEntry.put("FMaterialId",new FNumberVo(detail.getStr("code")));//物料编码
            FPOOrderEntry.put("FMaterialDesc",detail.getStr("remarks"));//物料说明
            FPOOrderEntry.put("FUnitId",new FNumberVo(detail.getStr("unit_code")));//采购单位
            FPOOrderEntry.put("FQty",detail.getBigDecimal("apply_amount").intValue());//采购数量
            FPOOrderEntry.put("FPriceUnitId",new FNumberVo(detail.getStr("unit_code")));//计价单位
          //  FPOOrderEntry.put("FPrice",detail.getBigDecimal("purchase_price").intValue());//单价
            FPOOrderEntry.put("FEntryTaxRate","13");
            FPOOrderEntry.put("FEntrySettleOrgId",new FNumberVo("R001"));//结算组织
            FPOOrderEntry.put("FStockUnitID",new FNumberVo(detail.getStr("unit_code")));
            FPOOrderEntry.put("F_QSVH_Base1",new FNumberVo("XM0001"));//项目
            FPOOrderEntry.put("FTAXPRICE",detail.getBigDecimal("purchase_price").intValue());//含税单价
            FPOOrderEntryList.add(FPOOrderEntry);
        }
        model.put("FPOOrderEntry",FPOOrderEntryList);
        return model;
    }

    public static void main(String[] args)  {
        try {


        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();
        Map<String,Object> data = new HashMap<>();
        Map<String,Object> datad = new HashMap<>();
        data.put("FNUMBER","CGDD01_SYS");
        Map<String,Object> model = new HashMap<>();

        model.put("FBillTypeID",datad);//单据类型
        model.put("FBillNo","CG23062717310452");//单据编号
        model.put("FDate", DateUtils.formatDateTime(new Date()));//采购日期
            datad = new HashMap<>();
            datad.put("FNumber","VEN00001");
        model.put("FSupplierId",datad);//供应商
        Map<String,String> purMap = Maps.newHashMap();
        //平台采购
        purMap.put("FNumber","R001");

        model.put("FPurchaseOrgId",purMap);//采购组织 ---能辉光伏编码是R001，如果是平台采购

        // model.put("FPurchaserId",new HashMap<>().put("FNumber",order.getCreator()));//采购员
        // model.put("FProviderId",new HashMap<>().put("FNumber",order.getDeliverId()));//供货方
        List<Map<String,Object>> FPOOrderEntryList = new ArrayList<>();
        List<Record> details = new ArrayList<>();
        Record record = new Record();
        record.set("code","BWX-1027");
            record.set("remarks","苟富贵过分过分发给");
            record.set("unit","台");
            record.set("apply_amount",new BigDecimal("650"));
            record.set("unit","UOM003");
            record.set("purchase_price",new BigDecimal("200"));
            record.set("unit_code","UOM003");

        details.add(record);
        for (Record detail : details) {
            Map<String,Object> FPOOrderEntry = new HashMap<>();
            FPOOrderEntry.put("FMaterialId",new FNumberVo("7I000119"));//物料编码
            FPOOrderEntry.put("FMaterialDesc","热太热太热天太热太热太");//物料说明
            FPOOrderEntry.put("FUnitId",new FNumberVo("UOM003"));//采购单位
            FPOOrderEntry.put("FQty",detail.getBigDecimal("apply_amount").intValue());//采购数量
            FPOOrderEntry.put("FPriceUnitId",new FNumberVo("UOM003"));//计价单位
            FPOOrderEntry.put("FPrice",detail.getBigDecimal("purchase_price").intValue());//单价
            FPOOrderEntry.put("FEntrySettleOrgId",new FNumberVo("R001"));//结算组织
            FPOOrderEntry.put("FStockUnitID",new FNumberVo("UOM003"));//结算组织
            FPOOrderEntry.put("F_QSVH_Base1",new FNumberVo("XM0001"));//项目
            FPOOrderEntryList.add(FPOOrderEntry);
        }
        model.put("FPOOrderEntry",FPOOrderEntryList);
        data.put("Model",model);
        KingDeeResponseVo repoResult = KingDeeUtil.kingDeeClitSave(gson.toJson(data), KingDeeConstants.PURCHASE_FORM_ID, gson, client);
        System.out.println("savePurchaseOrderToKingDee repoResult ={}"+gson.toJson(repoResult));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
