package com.dxhy.core.service.export.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.api.model.cpy.cpyInvoice.TDxRecordInvoiceCpyVo;
import com.dxhy.api.model.db.TdxRecordInvoiceEntity;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.service.DictdetaServcice;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.core.service.export.CpyGxExportService;
import com.dxhy.jxpt.baseService.cpyAuthInvoice.dao.CpyRecordInvoiceDao;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Description 成品油勾选导出
 * @Author wangruwei
 * @Date 2024/7/17 16:33
 **/
@SuppressWarnings("AlibabaMethodTooLong")
@Service("cpyGxExportService")
@Slf4j
public class CpyGxExportServiceImpl extends MpBaseServiceImpl<CpyRecordInvoiceDao, TdxRecordInvoiceEntity> implements CpyGxExportService {

    @Resource
    private DictdetaServcice dictdetaServcice;

    @Override
    public JSONObject selectByPramsMap(Map<String, Object> pramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        try {
            List<String> gfshList = (List<String>)pramsMap.get("gfsh");
            if (gfshList.size() == 0) {
                // 未从getUserInfo()获取到购方税号信息
                json.put("hjsl", "0");
                json.put("hjje", "0.00");
                json.put("hjse", "0.00");
                json.put("total", "0");
                json.put("datalist", new ArrayList<TDxRecordInvoiceCpyVo>());
            } else {
                PageHelper.startPage(curr, size);
                List<TDxRecordInvoiceCpyVo> pageList = super.baseMapper.selectAuthPageList(pramsMap);
                PageInfo<TDxRecordInvoiceCpyVo> pageInfo = new PageInfo<>(pageList);
                //List<TDxRecordInvoiceCpyVo> resultList = pageInfo.getList();
                json.put("hasNext", pageInfo.isHasNextPage());
                json.put("nextPage", pageInfo.getNextPage());
                // 用于页面返回list对象
                if (pageList != null && pageList.size() > 0) {
                    List<TDxRecordInvoiceCpyVo> resultList = pageInfo.getList();
                    // 用于页面返回list对象
                    if (resultList.size() > 0) {
                        int start = (int)pageInfo.getStartRow();
                        for (int i = 0; i < resultList.size(); i++) {
                            resultList.get(i).setXh(String.valueOf(i + start));

                            pageList.get(i)
                                    .setSelect(true);
                            //设置是否可勾选
                            String notAllowCheck = getCheckedStatus(resultList.get(i));
                            if(StringUtils.isNotBlank(notAllowCheck)){
                                pageList.get(i)
                                        .setSelect(false);
                                pageList.get(i)
                                        .setNotAllowCheckStr(notAllowCheck);
                            }

                            if(ObjectUtil.isNotEmpty(resultList.get(i).getInvoiceAmount())){
                                resultList.get(i).setInvoiceAmountStr(
                                        AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getInvoiceAmount().toString()) ));
                            }
                            if(ObjectUtil.isNotEmpty(resultList.get(i).getTaxAmount())){
                                resultList.get(i)
                                        .setTaxAmountStr(AmountFormatUtil.fmtMicrometer(MathUtil.round(resultList.get(i).getTaxAmount().toString())));
                            }
                            //发票类型
                            resultList.get(i)
                                    .setInvoiceType(dictdetaServcice.queryDictName(DictConstant.INVOICE_TYPEALL, resultList.get(i).getInvoiceType()));
                            //发票状态
                            resultList.get(i)
                                    .setInvoiceStatus(dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS, resultList.get(i).getInvoiceStatus()));
                            //发票风险等级
                            String glzt = resultList.get(i).getGlzt();
                            resultList.get(i).setGlzt(dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
                            //红字锁定标识
                            resultList.get(i).setLqHzsdbs(dictdetaServcice.queryDictName(DictConstant.HZSDZT, resultList.get(i).getLqHzsdbs()));
                            //成品油异常标识
                            resultList.get(i).setLqCpyycbs(dictdetaServcice.queryDictName(DictConstant.CPY_YCBS, resultList.get(i).getLqCpyycbs()));
                            //消费税用途
                            resultList.get(i).setLqXfsyt(dictdetaServcice.queryDictName(DictConstant.XFSYT, resultList.get(i).getLqXfsyt()));
                            //用途处理状态
                            resultList.get(i).setGxclzt(dictdetaServcice.queryDictName(DictConstant.CPY_GXCLZT, resultList.get(i).getGxclzt()));

                        }
                    }
                    // 设置记录总数
                    json.put("total", pageInfo.getTotal());
                    json.put("datalist", resultList);
                }
            }
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }

        return json;
    }

    /**
     * @Description 获取当前发票可勾选状态
     * @param tDxRecordInvoiceCpyVo
     * @Return void
     * @Author wangruwei
     * @Date 2024/7/15 17:59
     **/
    private String getCheckedStatus(TDxRecordInvoiceCpyVo tDxRecordInvoiceCpyVo) {
        //不可选原因
        List<String> notSelMsg = new LinkedList();

        /*1可勾选成品油消费税发票判断条件如下：
        1.1判断发票为蓝字发票
        1.2校验发票类型：
        1.2.1增值税专用发票 特殊票种标识为08、18：成品油
        1.2.2增值税电子专用发票 特殊票种标识为08、18：成品油
        1.2.3电子发票（增值税专用发票） 特定要素为01：成品油
        1.2.4纸质发票（增值税专用发票） 特定要素为01：成品油
        1.3校验发票中是否含有成品油商品编码，只要含有范围内的编码才允许勾选
        1.1~1.3为发票是否可以在经销企业页发票库存中是否可以看到这张发票。
        上述在取票时候就已筛选

        1.4~1.7 判断发票是否可勾选（复选框是否禁用）
        1.1判断发票为蓝字发票
        1.4校验发票状态：发票状态为正常、部分红冲
        1.5校验红字锁定标识：未锁定
        1.6校验异常凭证状态：非异常凭证（正常、疑似异常凭证）
        1.7校验成品油异常标识：正常*/
        if(ObjectUtil.isNotEmpty(tDxRecordInvoiceCpyVo.getInvoiceAmount())){
            if(tDxRecordInvoiceCpyVo.getInvoiceAmount()<0){
                notSelMsg.add("负数发票");
            }
        }else{
            //如果金额为空。判断红蓝票标识
            if("1".equals(tDxRecordInvoiceCpyVo.getIsRed())){
                notSelMsg.add("负数发票");
            }
        }

        //1.4校验发票状态：发票状态为正常、部分红冲
        if("0".equals(tDxRecordInvoiceCpyVo.getInvoiceStatus())||"7".equals(tDxRecordInvoiceCpyVo.getInvoiceStatus())){

        }else{
            notSelMsg.add("发票状态异常");
        }
        //1.5校验红字锁定标识：未锁定
        if("N".equals(tDxRecordInvoiceCpyVo.getLqHzsdbs())){

        }else{
            notSelMsg.add("红字锁定");
        }
        //1.6校验异常凭证状态：非异常凭证（正常、疑似异常凭证）
        if("0".equals(tDxRecordInvoiceCpyVo.getGlzt())||"2".equals(tDxRecordInvoiceCpyVo.getGlzt())){

        }else{
            notSelMsg.add("发票风险等级异常");
        }
        //1.7校验成品油异常标识：正常
        if("9".equals(tDxRecordInvoiceCpyVo.getLqCpyycbs())){

        }else{
            notSelMsg.add("成品油标识异常");
        }

        String showStr = String.join(",", notSelMsg);
        if(StringUtils.isNotBlank(showStr)){
            showStr+="。不允许勾选库存";
        }
        return showStr;
    }
}
