package com.yem.wm.task;

import com.yem.em.utils.AtlasUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.RequestCmmp;
import com.yem.wm.utils.RequestEAS;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;


import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhouc
 * @date 2024/4/25 11:03
 * @className TransFerorderGetRealityPrice
 * @description 调拨订单申请单获取EAS实际含税单价
 */
public class TransFerorderGetRealityPrice extends AbstractTask {
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        //基本信息-业务日期是上月+明细信息-业务分类为整机+明细信息-含税单价为0.01的分录
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Date> acquire = getAcquire();
        QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");//
        qFilter.and(new QFilter("yem_bizdate", QCP.large_equals, acquire.get("start")));
        qFilter.and(new QFilter("yem_bizdate", QCP.less_equals, acquire.get("end")));
        qFilter.and(new QFilter("yem_es_materialinfo.yem_businesssort", QCP.equals, "Z"));
        qFilter.and(new QFilter("yem_es_materialinfo.yem_pricetax", QCP.equals, new BigDecimal("0.01")));
        String selectfield = DynamicObjectUtil.getSelectfields("yem_transferorder", false);
        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_transferorder", "yem_es_materialinfo", false);
        DynamicObject[] yem_transferorder = BusinessDataServiceHelper.load("yem_transferorder", "id," + selectfields, new QFilter[]{qFilter}, null);
        if (yem_transferorder.length > 0) {
            for (int i = 0; i < yem_transferorder.length; i++) {
                DynamicObject transferorder = yem_transferorder[i];
                updatePrice(transferorder);
            }
        }
    }

    /**
     * 获取上月开始时间，结束时间
     *
     * @return
     */
    public Map<String, Date> getAcquire() {
        Map<String, Date> map = new HashMap<>();
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -1);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            Date startTime = cal.getTime();//上个月第一天
            String start = dateFormat.format(startTime) + " 00:00:00";
            Date startdate = sdf2.parse(start);
            map.put("start", startdate);
            Calendar calendar = Calendar.getInstance();
            int month = calendar.get(Calendar.MONTH);
            calendar.set(Calendar.MONTH, month - 1);
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date endTime = calendar.getTime();//上个月最后一天
            String end = dateFormat.format(endTime) + " 23:59:59";
            Date enddate = sdf2.parse(end);
            map.put("end", enddate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 获取EAS 更新金额
     *
     * @param transferorder 动态对象
     */
    public void updatePrice(DynamicObject transferorder) {
        DynamicObjectCollection yem_es_materialinfo = transferorder.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject materialinfo : yem_es_materialinfo) {
            String yem_businesssort = materialinfo.getString("yem_businesssort");
            BigDecimal yem_pricetax = materialinfo.getBigDecimal("yem_pricetax");
            if (yem_businesssort.equals("Z") && yem_pricetax.compareTo(new BigDecimal("0.01")) == 0) {
                //获取EAS单价
                List<Map> easPrice = getEASPrice(materialinfo.getString("id"));
                if (easPrice.size() > 0) {
                    Map map = easPrice.get(0);
                    //（0）实际含税单价：EAS采购入库的实际含税单价；  6位；
                    BigDecimal bigDecimal = (BigDecimal) map.get("ftaxprice");
                    BigDecimal yem_realitypricetax = bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP);
                    materialinfo.set("yem_realitypricetax", yem_realitypricetax);
                    //（1）税率：EAS采购入库的税率（%）；
                    BigDecimal yem_taxrate = (BigDecimal) map.get("ftaxrate");
                    materialinfo.set("yem_taxrate", yem_taxrate);
                    //---剩下外贸计算：
                    //（7）含税单价=实际含税单价；保留6位；
                    BigDecimal pricetax = yem_realitypricetax.setScale(6, BigDecimal.ROUND_HALF_UP);
                    materialinfo.set("yem_pricetax", pricetax);
                    //（2）单价=实际含税单价/（1+税率），6位
                    BigDecimal taxrate = yem_taxrate.multiply(new BigDecimal("100"));
                    BigDecimal sl = new BigDecimal("1").add(taxrate);
                    BigDecimal yem_price = yem_realitypricetax.divide(sl).setScale(6, BigDecimal.ROUND_HALF_UP);
                    materialinfo.set("yem_price", yem_price);
                    //（3）价税合计：含税单据*数量，2位；
                    BigDecimal yem_amttax = pricetax.multiply(materialinfo.getBigDecimal("yem_qty")).setScale(2, BigDecimal.ROUND_HALF_UP);
                    materialinfo.set("yem_amttax", yem_amttax);
                    //（4）金额=单价*数量，保留2位；
                    BigDecimal yem_amt = yem_price.multiply(materialinfo.getBigDecimal("yem_qty")).setScale(2, BigDecimal.ROUND_HALF_UP);
                    materialinfo.set("yem_amt", yem_amt);
                    //（5）税额=价税合计-金额；保留2位；
                    BigDecimal yem_amounttax = yem_amttax.subtract(yem_amt).setScale(2, BigDecimal.ROUND_HALF_UP);
                    materialinfo.set("yem_amounttax", yem_amounttax);
                    //（6）实际单价=单价；保留6位；
                    materialinfo.set("yem_realityprice", yem_price);
                    //（8）金额（本位币）=金额；    保留2位；
                    materialinfo.set("yem_locamt", yem_amt);
                    //（9）税额本位币=税额；保留2位；
                    materialinfo.set("yem_amountfield1", yem_amounttax);
                    //（10）价格合计本位币=价格合计；保留2位；
                    materialinfo.set("yem_baseamttax", yem_amttax);
                }
            }
        }
        /**
         * 计算表头金额 ，金额本位币
         */
        BigDecimal yem_amount = BigDecimal.ZERO;
        BigDecimal yem_amountbase = BigDecimal.ZERO;
        for (int i = 0; i < yem_es_materialinfo.size(); i++) {
            DynamicObject dynamicObject = yem_es_materialinfo.get(i);
            BigDecimal yem_amt = dynamicObject.getBigDecimal("yem_amt");
            BigDecimal yem_locamt = dynamicObject.getBigDecimal("yem_locamt");
            yem_amount = yem_amount.add(yem_amt);
            yem_amountbase = yem_amountbase.add(yem_locamt);
        }
        transferorder.set("yem_amount", yem_amount);
        transferorder.set("yem_amountbase", yem_amountbase);
        SaveServiceHelper.update(transferorder);
    }

    /**
     * 查询EAS视图
     *
     * @param entry
     * @return
     */
    public List<Map> getEASPrice(String entry) {
        String sql = "select distinct FNUMBER,FBIZDATE,CFPLMEID,MATERCODE,FTAXPRICE,FTAXRATE from  EAS2024.VIEW_IERP_PURIN_TAXPRICE  where CFPLMEID='" + entry + "'";
        List<Map> fromCmmp = RequestCmmp.getViewConfig(sql, "EAS2024");
        return fromCmmp;
    }


}
