package com.dxhy.erp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.FplxEnum;
import com.dxhy.common.util.NumberToCN;
import com.dxhy.common.util.ScanIdUtils;
import com.dxhy.common.util.StringHelper;
import com.dxhy.erp.entity.TdxCheckInvoiceDetail;
import com.dxhy.erp.entity.TdxCheckRecordInvoice;
import com.dxhy.erp.entity.TdxCheckVehicleSale;
import com.dxhy.erp.service.SignCheckRecordInvoiceDetailService;
import com.dxhy.erp.service.SignCheckRecordService;
import com.dxhy.erp.service.SignCheckVehicleSaleInvoiceService;
import com.dxhy.erp.service.SignSaveCheckInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * 保存查验结果到查验相关记录表业务处理实现类
 *
 * @author ld
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Service("signSaveCheckInfoService")
@Slf4j

public class SignSaveCheckInfoServiceImpl implements SignSaveCheckInfoService {

    @Resource
    private ScanIdUtils scanIdUtils;

    @Resource
    private SignCheckRecordService signCheckRecordService;

    @Resource
    private SignCheckVehicleSaleInvoiceService signCheckVehicleSaleInvoiceService;


    @Resource
    private SignCheckRecordInvoiceDetailService signCheckRecordInvoiceDetailService;

    @Override
    public void saveCheckInfo(JSONObject queryInvoiceResult, String userid, String dbName) {
        String resultCode = queryInvoiceResult.getString("resultCode");
        // 查验成功，结果一致
        /*
         * 查验成功状态码
         */
        String querySuccCode = "0001";
        if (querySuccCode.equals(resultCode)) {
            TdxCheckRecordInvoice checkRecord = getRecordInvoice(queryInvoiceResult, userid);
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            TdxCheckRecordInvoice checkRecordTmp = signCheckRecordService.getCheckInvoiceByUuid(checkRecord.getUuid());
            if (checkRecordTmp != null) {
                if (StringUtils.isNotBlank(checkRecordTmp.getCycs())) {
                    int cycs = Integer.parseInt(checkRecordTmp.getCycs()) + 1;
                    checkRecord.setCycs(String.valueOf(cycs));
                } else {
                    checkRecord.setCycs("1");
                }
            } else {
                checkRecord.setCycs("1");
            }
            TdxCheckVehicleSale checkVehicleSale = getVehicleSaleInvoice(queryInvoiceResult);
            List<TdxCheckInvoiceDetail> checkRecordDetailList = getRecordInvoiceDetail(queryInvoiceResult);
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_WRITE);
            // 保存查验信息
            saveCheckMxxx(checkRecord, checkVehicleSale, checkRecordDetailList);
        }
    }

    public TdxCheckVehicleSale getVehicleSaleInvoice(JSONObject queryInvoiceResult) {
        String invoiceType = queryInvoiceResult.getString("invoiceType");
        if (FplxEnum.JDC.getFplxDm().equals(invoiceType)) {
            String invoiceCode = queryInvoiceResult.getString("invoiceCode");
            String invoiceNo = queryInvoiceResult.getString("invoiceNo");
            String uuid = invoiceCode + invoiceNo;
            TdxCheckVehicleSale vehicleSaleInvoice = new TdxCheckVehicleSale();
            vehicleSaleInvoice.setUuid(uuid);
            vehicleSaleInvoice.setBuyerIdNum(queryInvoiceResult.getString("buyerIDNum"));
            vehicleSaleInvoice.setVehicleType(queryInvoiceResult.getString("vehicleType"));
            vehicleSaleInvoice.setFactoryModel(queryInvoiceResult.getString("factoryModel"));
            vehicleSaleInvoice.setProductPlace(queryInvoiceResult.getString("productPlace"));
            vehicleSaleInvoice.setCertificate(queryInvoiceResult.getString("certificate"));
            vehicleSaleInvoice.setCertificateImport(queryInvoiceResult.getString("certificateImport"));
            vehicleSaleInvoice.setInspectionNum(queryInvoiceResult.getString("inspectionNum"));
            vehicleSaleInvoice.setEngineNo(queryInvoiceResult.getString("engineNo"));
            vehicleSaleInvoice.setVehicleNo(queryInvoiceResult.getString("vehicleNo"));
            vehicleSaleInvoice.setTaxBureauCode(queryInvoiceResult.getString("taxBureauCode"));
            vehicleSaleInvoice.setTaxBureauName(queryInvoiceResult.getString("taxBureauName"));
            vehicleSaleInvoice.setTaxRecords(queryInvoiceResult.getString("taxRecords"));
            vehicleSaleInvoice.setTonnage(queryInvoiceResult.getString("tonnage"));
            vehicleSaleInvoice.setLimitPeople(queryInvoiceResult.getString("limitPeople"));
            vehicleSaleInvoice.setTaxRate(queryInvoiceResult.getString("taxRate"));
            return vehicleSaleInvoice;
        }else if(FplxEnum.ESC.getFplxDm().equals(invoiceType)){
            String invoiceCode = queryInvoiceResult.getString("invoiceCode");
            String invoiceNo = queryInvoiceResult.getString("invoiceNo");
            String uuid = invoiceCode + invoiceNo;

            TdxCheckVehicleSale vehicleSaleInvoice = new TdxCheckVehicleSale();
            vehicleSaleInvoice.setUuid(uuid);
            vehicleSaleInvoice.setPlateNo(queryInvoiceResult.getString("licensePlate"));
            vehicleSaleInvoice.setRegistrationNo(queryInvoiceResult.getString("registrationNo"));
            if(StringUtils.isNotBlank(queryInvoiceResult.getString("vehicleType"))){
                vehicleSaleInvoice.setVehicleType(queryInvoiceResult.getString("vehicleType"));
            }
            if(StringUtils.isNotBlank(queryInvoiceResult.getString("bandModel"))){
                vehicleSaleInvoice.setFactoryModel(queryInvoiceResult.getString("bandModel"));
            }
            if(StringUtils.isNotBlank(queryInvoiceResult.getString("vehicleIdentificationNo"))){
                vehicleSaleInvoice.setVehicleNo(queryInvoiceResult.getString("vehicleIdentificationNo"));
            }
            vehicleSaleInvoice.setCarPrice(queryInvoiceResult.getString("carPrice"));
            vehicleSaleInvoice.setVehicleAdminOffice(queryInvoiceResult.getString("vehicleAdminOffice"));
            vehicleSaleInvoice.setBuyerUnit(queryInvoiceResult.getString("buyerUnitOrIndividual"));
            vehicleSaleInvoice.setBuyerUnitCode(queryInvoiceResult.getString("buyerUnitCodeOrIdNo"));
            vehicleSaleInvoice.setBuyerUnitAddress(queryInvoiceResult.getString("buyerUnitOrIndividualAddress"));
            vehicleSaleInvoice.setBuyerPhone(queryInvoiceResult.getString("buyerPhone"));
            vehicleSaleInvoice.setSellerUnit(queryInvoiceResult.getString("sellerUnitOrIndividual"));
            vehicleSaleInvoice.setSellerUnitCode(queryInvoiceResult.getString("sellerUnitCodeOrIdNo"));
            vehicleSaleInvoice.setSellerUnitAddress(queryInvoiceResult.getString("sellerUnitOrIndividualAddress"));
            vehicleSaleInvoice.setSellerPhone(queryInvoiceResult.getString("sellerPhone"));
            vehicleSaleInvoice.setAuctionUnit(queryInvoiceResult.getString("businessUnit"));
            vehicleSaleInvoice.setAuctionAddress(queryInvoiceResult.getString("businessUnitAddress"));
            vehicleSaleInvoice.setAuctionTaxNo(queryInvoiceResult.getString("businessUnitTaxNo"));
            vehicleSaleInvoice.setAuctionBank(queryInvoiceResult.getString("businessUnitBankAndAccount"));
            vehicleSaleInvoice.setAuctionPhone(queryInvoiceResult.getString("businessUnitPhone"));
            vehicleSaleInvoice.setCarMarket(queryInvoiceResult.getString("lemonMarket"));
            vehicleSaleInvoice.setCarMarketTaxNo(queryInvoiceResult.getString("lemonMarketTaxNo"));
            vehicleSaleInvoice.setCarMarketAddress(queryInvoiceResult.getString("lemonMarketAddress"));
            vehicleSaleInvoice.setCarMarketBank(queryInvoiceResult.getString("lemonMarketBankAndAccount"));
            vehicleSaleInvoice.setCarMarketPhone(queryInvoiceResult.getString("lemonMarketPhone"));
            return vehicleSaleInvoice;
        } else {
            return null;
        }
    }

    public List<TdxCheckInvoiceDetail> getRecordInvoiceDetail(JSONObject queryInvoiceResult) {
        if (queryInvoiceResult.containsKey("detailList")) {
            JSONArray dataArray = queryInvoiceResult.getJSONArray("detailList");
            if (dataArray != null && dataArray.size() > 0) {
                String invoiceType = queryInvoiceResult.getString("invoiceType");
                String invoiceCode = queryInvoiceResult.getString("invoiceCode");
                String invoiceNo = queryInvoiceResult.getString("invoiceNo");
                String uuid = invoiceCode + invoiceNo;
                List<TdxCheckInvoiceDetail> invoiceDetailList = new ArrayList<>(dataArray.size());
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject invoiceDetailQuery = dataArray.getJSONObject(i);
                    TdxCheckInvoiceDetail invoiceDetail = new TdxCheckInvoiceDetail();
                    invoiceDetail.setUuid(uuid);
                    invoiceDetail.setDetailNo(invoiceDetailQuery.getString("detailNo"));
                    invoiceDetail.setGoodsName(invoiceDetailQuery.getString("goodsName"));
                    invoiceDetail.setModel(invoiceDetailQuery.getString("specificationModel"));
                    invoiceDetail.setUnit(invoiceDetailQuery.getString("unit"));
                    invoiceDetail.setNum(invoiceDetailQuery.getString("num"));
                    invoiceDetail.setUnitPrice(invoiceDetailQuery.getString("unitPrice"));
                    invoiceDetail.setDetailAmount(invoiceDetailQuery.getString("detailAmount"));
                    invoiceDetail.setTaxRate(invoiceDetailQuery.getString("taxRate"));
                    invoiceDetail.setTaxAmount(invoiceDetailQuery.getString("taxAmount"));
                    if (FplxEnum.TXF.getFplxDm().equals(invoiceType)) {
                        // 通行费发票
                        invoiceDetail.setCph(invoiceDetailQuery.getString("cph"));
                        invoiceDetail.setLx(invoiceDetailQuery.getString("lx"));
                        invoiceDetail.setTxrqq(invoiceDetailQuery.getString("txrqq"));
                        invoiceDetail.setTxrqz(invoiceDetailQuery.getString("txrqz"));
                    }
                    invoiceDetailList.add(invoiceDetail);
                }
                return invoiceDetailList;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    public TdxCheckRecordInvoice getRecordInvoice(JSONObject queryInvoiceResult, String userid) {
        TdxCheckRecordInvoice invoice = new TdxCheckRecordInvoice();

        String invoiceType = queryInvoiceResult.getString("invoiceType");
        String invoiceCode = queryInvoiceResult.getString("invoiceCode");
        String invoiceNo = queryInvoiceResult.getString("invoiceNo");
        String uuid = invoiceCode + invoiceNo;

        invoice.setCyjgCode(queryInvoiceResult.getString("resultCode"));
        invoice.setCyjgTip(queryInvoiceResult.getString("resultTip"));
        invoice.setCycs(queryInvoiceResult.getString("checkCount"));
        invoice.setFpzl(invoiceType);
        if("31".equals(invoiceType) || "32".equals(invoiceType)){
            invoice.setFphm(uuid);
        }else {
            invoice.setFpdm(invoiceCode);
            invoice.setFphm(invoiceNo);
        }
        invoice.setUuid(uuid);
        invoice.setGfsh(queryInvoiceResult.getString("buyerTaxNo"));
        invoice.setGfmc(queryInvoiceResult.getString("buyerName"));
        invoice.setGfdzdh(queryInvoiceResult.getString("buyerAddressPhone"));
        invoice.setGfyhzh(queryInvoiceResult.getString("buyerAccount"));
        invoice.setXfdzdh(queryInvoiceResult.getString("salerAddressPhone"));
        invoice.setXfyhzh(queryInvoiceResult.getString("salerAccount"));
        invoice.setXfmc(queryInvoiceResult.getString("salerName"));
        invoice.setXfsh(queryInvoiceResult.getString("salerTaxNo"));
        invoice.setJe(queryInvoiceResult.getString("invoiceAmount"));
        try {
            new BigDecimal(queryInvoiceResult.getString("taxAmount"));
            invoice.setSe(queryInvoiceResult.getString("taxAmount"));
        } catch (Exception e) {
            invoice.setSe("0");
        }
        invoice.setJshj(queryInvoiceResult.getString("totalAmount"));
        if(FplxEnum.ESC.getFplxDm().equals(invoiceType)){
            invoice.setJe(queryInvoiceResult.getString("carPrice"));
            invoice.setJshj(queryInvoiceResult.getString("carPrice"));
            invoice.setGfmc(queryInvoiceResult.getString("buyerUnitOrIndividual"));
            invoice.setGfsh(queryInvoiceResult.getString("buyerUnitCodeOrIdNo"));
            invoice.setGfdzdh(queryInvoiceResult.getString("buyerUnitOrIndividualAddress"));
            invoice.setXfmc(queryInvoiceResult.getString("sellerUnitOrIndividual"));
            invoice.setXfsh(queryInvoiceResult.getString("sellerUnitCodeOrIdNo"));
            invoice.setXfdzdh(queryInvoiceResult.getString("sellerUnitOrIndividualAddress"));
        }
        invoice.setKprq(queryInvoiceResult.getString("invoiceDate"));
        invoice.setJqbh(queryInvoiceResult.getString("machineNo"));
        invoice.setBz(queryInvoiceResult.getString("remark"));
        invoice.setJym(queryInvoiceResult.getString("checkCode"));
        invoice.setTxfbz(queryInvoiceResult.getString("txfbz"));
        invoice.setCreateDate(new Date());
        invoice.setCheckUser(userid);
        invoice.setScanId(queryInvoiceResult.getString("scanId"));
        invoice.setZfbz(queryInvoiceResult.getString("isCancelled"));
        invoice.setCompany(queryInvoiceResult.getString("company"));
        invoice.setPdfMd5(Long.valueOf(scanIdUtils.createSerialNum()));
        return invoice;
    }


    /**
     * 保存查验信息
     *
     * @param checkRecord
     *            请求参数
     * @param checkVehicleSale
     *            请求参数
     * @param checkRecordDetailList
     *            请求参数
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveCheckMxxx(TdxCheckRecordInvoice checkRecord, TdxCheckVehicleSale checkVehicleSale,
                              List<TdxCheckInvoiceDetail> checkRecordDetailList) {
        String uuid = checkRecord.getUuid();
        {
            // 删除重复数据，防止重复的操作
            QueryWrapper<TdxCheckRecordInvoice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uuid", uuid);
            signCheckRecordService.remove(queryWrapper);
            // 保存数据
            signCheckRecordService.save(checkRecord);
        }

        if (checkVehicleSale != null) {
            // 删除重复数据，防止重复的操作
            QueryWrapper<TdxCheckVehicleSale> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uuid", uuid);
            signCheckVehicleSaleInvoiceService.remove(queryWrapper);
            // 保存数据
            signCheckVehicleSaleInvoiceService.save(checkVehicleSale);
        }

        if (checkRecordDetailList != null && checkRecordDetailList.size() > 0) {
            // 删除重复数据，防止重复的操作
            QueryWrapper<TdxCheckInvoiceDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uuid", uuid);
            signCheckRecordInvoiceDetailService.remove(queryWrapper);
            // 保存数据
            /*
             * 批量操作的大小
             */
            int batchSize = 500;
            signCheckRecordInvoiceDetailService.saveBatch(checkRecordDetailList, batchSize);
        }
    }

}
