package com.seeyon.apps.src_powerfeeinvoice.job;

import cn.hutool.log.Log;
import com.seeyon.apps.common.config.ICstConfigApi;
import com.seeyon.apps.common.plugin.vo.ConfigVo;
import com.seeyon.apps.ext.quartz.AbstractQuartzTask;
import com.seeyon.apps.src_hxinvoice.constants.HxinvoiceConstants;
import com.seeyon.apps.src_powerfeeinvoice.config.HttpFormRestApiConfig;
import com.seeyon.apps.src_powerfeeinvoice.config.PowerFeePluginConfigProvider;
import com.seeyon.apps.src_powerfeeinvoice.constants.PowerFeeInvoiceConstants;
import com.seeyon.apps.src_powerfeeinvoice.service.HxInvoiceInfoFillService;
import com.seeyon.apps.src_powerfeeinvoice.service.PowerFeeService;
import com.seeyon.apps.src_powerfeeinvoice.utils.ClauseFactor;
import com.seeyon.apps.src_powerfeeinvoice.utils.FormColumn;
import com.seeyon.apps.src_powerfeeinvoice.utils.FormDataOperator;
import com.seeyon.apps.src_powerfeeinvoice.utils.FormFieldVo;
import com.seeyon.apps.src_powerfeeinvoice.utils.FormWhereCondition;
import com.seeyon.apps.src_powerfeeinvoice.utils.FormUpdateField;
import com.seeyon.apps.src_powerfeeinvoice.vo.PowerFeeInvoiceInfo;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;

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

public class PowerFeePushJob extends AbstractQuartzTask {

    private static Log log = Log.get(PowerFeePushJob.class);
    @Autowired
    private PowerFeeService powerFeeService;
    private PowerFeePluginConfigProvider powerFeePluginConfigProvider = (PowerFeePluginConfigProvider) AppContext.getBean("powerFeePluginConfigProvider");

    @Override
    public String taskRun(String s) throws Exception {
        if(s == null) {
            s = new String("2025-03-01");
        }
        try {
            List<FormWhereCondition> conditions = new ArrayList<>();
            HxInvoiceInfoFillService fillService = new HxInvoiceInfoFillService();
            String secretKey = powerFeePluginConfigProvider.getBizConfigByKey(PowerFeeInvoiceConstants.hxSecretKey);
            String secretId = powerFeePluginConfigProvider.getBizConfigByKey(PowerFeeInvoiceConstants.hxSecretId);
            String url  = powerFeePluginConfigProvider.getBizConfigByKey(PowerFeeInvoiceConstants.hxPushInvoiceUrl);
            String formNo = powerFeePluginConfigProvider.getBizConfigByKey(PowerFeeInvoiceConstants.formNo);
//            conditions.add(FormQueryCondition.build().value("2025-01-01").clauseFactor(ClauseFactor.GE).display("支付日期"));
            conditions.add(FormWhereCondition.build().value(s).clauseFactor(ClauseFactor.GT).display("支付日期").index("TO_DATE(?,'YYYY-MM-DD')"));
            conditions.add(FormWhereCondition.build().clauseFactor(ClauseFactor.NULL).concatFactor(ClauseFactor.OR).startWithBracket(true).display("是否推送开票系统"));
            conditions.add(FormWhereCondition.build().value("否").clauseFactor(ClauseFactor.EQ).endWithBracket(true).display("是否推送开票系统"));
            conditions.add(FormWhereCondition.build().clauseFactor(ClauseFactor.NULL).concatFactor(ClauseFactor.OR).startWithBracket(true).display("是否已开票"));
            conditions.add(FormWhereCondition.build().value("否").clauseFactor(ClauseFactor.EQ).endWithBracket(true).display("是否已开票"));
            List<FormColumn> columns = powerFeeService.queryCondition(powerFeePluginConfigProvider.getBizConfigByKey(PowerFeeInvoiceConstants.formNo), null,conditions );
            PowerFeeInvoiceInfo invoiceInfo = null;
            if(columns != null && columns.size() > 0) {
                for (FormColumn column : columns) {
                    try {
                        invoiceInfo = new PowerFeeInvoiceInfo();
                        String formId = column.getId();
                        if(column.getVos() == null) {
                            continue;
                        }
                        Map<String, String> sellerInfo = null;
                        Map<String, String> invoicerInfo = null;
                        for (FormFieldVo vo : column.getVos()) {
                            if(vo.getDisplayName().equals("BIP公司编号")) {
                                sellerInfo = getSellerInfo(vo);
                            }
                            if(vo.getDisplayName().equals("OA一级公司")) {
                                invoicerInfo = getInvoicerInfo(vo);
                            }
                            fillInfo(vo,invoiceInfo);
                        }
                        //填充销方信息
                        invoiceInfo.setSellerName(sellerInfo.get("销售方名称"));
                        invoiceInfo.setSellerTaxNo(sellerInfo.get("销售方税号"));
                        invoiceInfo.setInvoicer(invoicerInfo.get("开票人"));
                        String ddqqlsh = "ZNDBLSH" + System.currentTimeMillis();
                        invoiceInfo.setOrderTradeNo(ddqqlsh);
                        if(invoiceInfo.getTotalPrice() != null) {
                            BigDecimal bigDecimal = new BigDecimal(invoiceInfo.getTotalPrice() + "");
                            if(bigDecimal.compareTo(BigDecimal.ZERO) == -1) {
                                throw new RuntimeException("金额为负数");
                            }
                        }
                        String param = fillService.getParam(invoiceInfo);
                        if(invoiceInfo.getBuyer() == null ||
                                invoiceInfo.getSellerName() == null ||
                                invoiceInfo.getSellerTaxNo() == null ||
                                invoiceInfo.getTotalPrice() == null ||
                                invoiceInfo.getPrice() == null ||
                        invoiceInfo.getBuyerPhone() == null ||
                        invoiceInfo.getOrderTradeNo() == null) {
                            throw new RuntimeException("某些必传参数为空，请检查金额、单价、手机号、订单请求流水号、纳税识别号等信息");
                        }

                        fillService.pushInvoiceInfo(param,secretKey,secretId,url);
                        List<FormUpdateField> updateFiels = new ArrayList<>();
                        updateFiels.add(FormUpdateField.build().display("是否推送开票系统").value("是"));
                        updateFiels.add(FormUpdateField.build().display("订单请求流水号").value(ddqqlsh));
                        List<FormWhereCondition> whereClause = new ArrayList<>();
                        whereClause.add(FormWhereCondition.build().display("ID").value(Long.parseLong(formId)).clauseFactor(ClauseFactor.EQ));
                        powerFeeService.updateForm(updateFiels,whereClause,formNo);
                    }catch (Exception e) {
                        log.error("推送失败,请求批次号为：" + invoiceInfo.getReqNo() + " ,失败原因为: "+ e.getMessage());
                        log.error(e);
                    }
                }
            }
        }catch (Exception e) {
            log.error("任务执行异常: "+e.getMessage());
            throw e;
        }
        return "";
    }

    private Map<String,String> getInvoicerInfo(FormFieldVo vo) throws BusinessException {
        FormDataOperator dataOperator = new FormDataOperator();
        List<FormWhereCondition> conditions = new ArrayList<>();
        conditions.add(FormWhereCondition.build().display("OA一级单位").value(vo.getValue()).clauseFactor(ClauseFactor.EQ));
        String formNo = powerFeePluginConfigProvider.getBizConfigByKey(PowerFeeInvoiceConstants.KPRDAFORMNO);
        List<FormColumn> columns = dataOperator.queryFormDataCondition(formNo, null, conditions);
        if(columns == null || columns.size() == 0) {
            throw new RuntimeException("开票人信息查询失败");
        }
        FormColumn column = columns.get(0);
        if(column.getVos().size() == 0 ) {
            throw new RuntimeException("开票人信息查询失败");
        }
        Map<String,String> map = new HashMap<>();
        for (FormFieldVo columnVo : column.getVos()) {
            if("开票人".equals(columnVo.getDisplayName())) {
                map.put("开票人",columnVo.getValue() + "");
            }
        }
        if(!map.containsKey("开票人") || map.get("开票人") == null) {
            throw new RuntimeException("开票人获取失败");
        }
        return map;
    }

    private Map<String,String> getSellerInfo(FormFieldVo vo) throws BusinessException {
        FormDataOperator dataOperator = new FormDataOperator();
        List<FormWhereCondition> conditions = new ArrayList<>();
        conditions.add(FormWhereCondition.build().display("ORGCODE").value(vo.getValue()).clauseFactor(ClauseFactor.EQ));
        String orgFormNo = powerFeePluginConfigProvider.getBizConfigByKey(PowerFeeInvoiceConstants.DAORGFORMNO);
        List<FormColumn> columns = dataOperator.queryFormDataCondition(orgFormNo, null, conditions);
        if(columns == null || columns.size() == 0) {
            throw new RuntimeException("销方信息查询失败");
        }
        FormColumn column = columns.get(0);
        if(column.getVos().size() == 0 ) {
            throw new RuntimeException("销方信息查询失败");
        }
        Map<String,String> map = new HashMap<>();
        for (FormFieldVo columnVo : column.getVos()) {
            if("ORGNAME".equals(columnVo.getDisplayName())) {
                map.put("销售方名称",columnVo.getValue() + "");
            }
            if("TAXID".equals(columnVo.getDisplayName())) {
                map.put("销售方税号",columnVo.getValue() + "");
            }
        }
        if(!map.containsKey("销售方名称") || map.get("销售方名称") == null) {
            throw new RuntimeException("销方名称获取失败");
        }
        if(!map.containsKey("销售方税号") || map.get("销售方税号") == null) {
            throw new RuntimeException("销方税号获取失败");
        }
        return map;
    }

    private void refreshRecord(String formNo,String formId) throws Exception {
        String formLoginName = powerFeePluginConfigProvider.getBizConfigByKey(PowerFeeInvoiceConstants.formInsertLoginName);
        ICstConfigApi cstConfigApi = (ICstConfigApi) AppContext.getBean("cstConfigApi");
        ConfigVo config = cstConfigApi.getConfig(HxinvoiceConstants.getPluginId());
        String restLoginName = config.getParamVal(HxinvoiceConstants.localRestName.name());
        String restPwd = config.getParamVal(HxinvoiceConstants.localRestPwd.name());
        String rightId = powerFeePluginConfigProvider.getBizConfigByKey(PowerFeeInvoiceConstants.dfRightId);
        String baseUrl = config.getParamVal(HxinvoiceConstants.localipport.name());
        String tokenUrl = baseUrl + config.getParamVal(HxinvoiceConstants.getTokenUrl.name());
        HttpFormRestApiConfig restApiConfig = new HttpFormRestApiConfig();
        restApiConfig.setRestPwd(restPwd);
        restApiConfig.setRestUserName(restLoginName);
        restApiConfig.setTokenUrl(tokenUrl);
        restApiConfig.setBaseUrl(baseUrl);
        restApiConfig.setRightId(rightId);
        powerFeeService.refreshForm(formNo,formId,formLoginName,restApiConfig);
    }

    private void fillInfo(FormFieldVo vo,PowerFeeInvoiceInfo invoiceInfo) {
        BigDecimal multipy = new BigDecimal("1.0000");
        if(vo.getDisplayName().equals("电费单价") && vo.getValue() != null) {
            BigDecimal bigDecimal = (BigDecimal)vo.getValue();
            invoiceInfo.setPrice(bigDecimal.multiply(multipy).setScale(4,BigDecimal.ROUND_HALF_UP).toString());
        }
        if(vo.getDisplayName().equals("交易号") && vo.getValue() != null) {
            invoiceInfo.setOrderNo(vo.getValue() + "");
            invoiceInfo.setReqNo(vo.getValue() + "");
        }
        if(vo.getDisplayName().equals("订单请求流水号") && vo.getValue() != null) {
            invoiceInfo.setOrderTradeNo(vo.getValue() + "");
        }
        if(vo.getDisplayName().equals("电表用户编码")) {
            invoiceInfo.setCustomerNo((String)vo.getValue());
        }
        if(vo.getDisplayName().equals("金额") && vo.getValue() != null) {
            BigDecimal bigDecimal = (BigDecimal)vo.getValue();
            invoiceInfo.setTotalPrice(bigDecimal.multiply(multipy).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        }
        if(vo.getDisplayName().equals("电表租户名称")) {
            invoiceInfo.setBuyer((String) vo.getValue());
        }
        if(vo.getDisplayName().equals("销方纳税人识别号")) {
            invoiceInfo.setSellerTaxNo((String)vo.getValue());
        }
        if(vo.getDisplayName().equals("购方纳税人识别号")) {
            invoiceInfo.setBuyerTaxNo((String)vo.getValue());
        }
        if(vo.getDisplayName().equals("手机号")) {
            invoiceInfo.setBuyerPhone((String)vo.getValue());
        }
        if(vo.getDisplayName().equals("开票人")) {
            invoiceInfo.setInvoicer((String) vo.getValue());
        }
        if(vo.getDisplayName().equals("销方公司名称")) {
            invoiceInfo.setSellerName((String)vo.getValue());
        }
        if(vo.getDisplayName().equals("支付日期")) {
            invoiceInfo.setDdsj(vo.getValue());
        }
    }

    @Override
    public String getName() {
        return "电费信息推送航信发票";
    }
}
