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

import com.alibaba.fastjson.JSONObject;
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.TabulateRedisService;
import com.dxhy.common.service.impl.MpBaseServiceImpl;
import com.dxhy.common.util.AmountFormatUtil;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.UserInfoUtil;
import com.dxhy.common.vo.DictdetaModel;
import com.dxhy.core.dao.ViolationLogDao;
import com.dxhy.core.entity.EnterpriseInfoModel;
import com.dxhy.core.entity.ExtTdxRecordInvoice;
import com.dxhy.core.entity.ViolationLogModel;
import com.dxhy.core.job.entity.ExtBbfpzhcxRespVO;
import com.dxhy.core.job.entity.SNSAPObject;
import com.dxhy.core.job.entity.SupplierRisk;
import com.dxhy.core.job.service.SupplierRiskService;
import com.dxhy.core.model.RiskSupplierVO;
import com.dxhy.core.util.HttpRequestUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Gy Chen
 * @date 2020/12/31
 */
@Slf4j
@Service("SupplierRiskService")
public class SupplierRiskServiceImpl extends MpBaseServiceImpl<ViolationLogDao, ViolationLogModel>
        implements SupplierRiskService {

    @Value("${sdny.snYxUrl}")
    private String snYxUrl;

    @Value("${po.userName}")
    private String userName;

    @Value("${po.password}")
    private String password;

    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    DictdetaServcice dictdetaServcice;


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

            PageHelper.startPage(curr, size);
            List<ViolationLogModel> pageList = this.baseMapper.selectViolation(company, (String) pramsMap.get("xfName"));
            PageInfo<ViolationLogModel> pageInfo = new PageInfo<>(pageList);
            List<ViolationLogModel> resultList = pageInfo.getList();
            // 用于页面返回list对象
            if (resultList != null && resultList.size() > 0) {

                int start = (int) pageInfo.getStartRow();
                for (int i = 0; i < resultList.size(); i++) {
                    resultList.get(i).setXh(String.valueOf(i + (curr - 1) * size + 1));
                }
            }

            // 设置记录总数
            json.put("total", pageInfo.getTotal());
            json.put("datalist", resultList);

        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }

        return super.responseResult(json);
    }

    @Override
    public String selectRiskSupplier(Map<String, Object> pramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        try {
            String[] titlelist = {"序号", "供应商税号", "供应商名称", "发票张数", "总金额"};

            String[] titleprop = {"xh", "taxNo", "taxName", "invoiceNum", "invoiceAmount"};
            // 需要设置返回列表标题时调用
            json = super.setTitleList(titlelist, titleprop);
            List<String> gfshList = (List<String>) pramsMap.get("gfsh");
            if (gfshList == null || gfshList.size() == 0) {
                return super.responseResult(json);
            }

            PageHelper.startPage(curr, size);
            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjfp = "0";
                String hjje = "0";
                RiskSupplierVO countVo = super.baseMapper.selectRiskSupplierCount(pramsMap);
                if (countVo != null) {
                    if (countVo.getSupplierNum() != null && !"0".equals(countVo.getSupplierNum())) {
                        hjfp = AmountFormatUtil.fmtMicrometer(countVo.getInvoiceNum());
                        hjje = AmountFormatUtil.fmtMicrometer(MathUtil.round(countVo.getInvoiceAmount()));
                    }
                }

                json.put("hjsl", hjsl);
                json.put("hjje", hjje);
                json.put("hjfp", hjfp);
            }
            PageHelper.startPage(curr, size);
            List<RiskSupplierVO> pageList = super.baseMapper.selectRiskSupplier(pramsMap);
            PageInfo<RiskSupplierVO> pageInfo = new PageInfo<>(pageList);
            // 用于页面返回list对象
            if (pageList.size() > 0) {

                int start = (int) pageInfo.getStartRow();
                for (int i = 0; i < pageList.size(); i++) {
                    pageList.get(i).setXh(String.valueOf(i + start));
                    pageList.get(i).setInvoiceAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getInvoiceAmount())));
                    pageList.get(i).setInvoiceNum(AmountFormatUtil.fmtMicrometer(pageList.get(i).getInvoiceNum()));
                }
            }

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

    @Override
    public String selectRiskSupplier2(Map<String, Object> pramsMap) {

        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        //获取购方税号对应的供应商风险信息
        String result = "";
        log.info("请求供应商风险的参数为:{}",pramsMap);
        List<RiskSupplierVO> pageList = super.baseMapper.selectRiskSupplier(pramsMap);

        log.info("pageList:{}",pageList);
        for (RiskSupplierVO risk : pageList) {
            String taxNo = risk.getTaxNo();
            Map<String, Object> prams = new HashMap<>();
            prams.put("taxNo", taxNo);

            List<ViolationLogModel> violationLogModels = super.baseMapper.selectRiskSupplierInfo(prams);

            log.info("返回违规信息为:{}",violationLogModels);
            //构建FI870参数
            SNSAPObject object = new SNSAPObject();
            object.setSYSID("FPXT");
            object.setIFYWID("FI870");
            object.setBSKEY(UUID.randomUUID().toString().replace("-", ""));
            object.setZFILED5("300");

            List<SupplierRisk> risks = new ArrayList<>();

            if (violationLogModels != null && violationLogModels.size() > 0) {
                for (ViolationLogModel violation : violationLogModels) {
                    SupplierRisk riskInfo = new SupplierRisk();

                    riskInfo.setTAXNUM(violation.getXfTaxNo());
                    riskInfo.setZCFSJ(violation.getInputDate());
                    riskInfo.setZWFSD(violation.getBreakLawMethod());
                    riskInfo.setZWGLX(violation.getBreakLawType());

                    risks.add(riskInfo);
                }

                object.setZDATA(JSONObject.toJSONString(risks));
                JSONObject request = new JSONObject();
                request.put("IS_INPUT", object);

                //将信息推送到影像系统
                log.info("获取请求参数：{} , 请求地址：{}", request.toJSONString(), snYxUrl);
                result = HttpRequestUtils.sendPo(snYxUrl, request.toJSONString(), userName, password);
                log.info("获取返回信息：{}", result);
            }
        }


        return result;
    }

    @Override
    public String selectRiskSupplierInfo(Map<String, Object> pramsMap) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        try {
            String[] titlelist = {"处罚时间", "违规类型", "违法手段"};

            String[] titleprop = {"penalizeDate", "breakLawType", "breakLawMethod"};
            // 需要设置返回列表标题时调用
            json = super.setTitleList(titlelist, titleprop);
            List<ViolationLogModel> pageList = super.baseMapper.selectRiskSupplierInfo(pramsMap);
            List<ViolationLogModel> resultList = new ArrayList<>();
            // 设置记录总数
            json.put("datalist", pageList);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }
        return super.responseResult(json);
    }

    @Override
    public String selectRiskInvoice(Map<String, Object> pramsMap, int curr, int size) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        try {
            String[] titlelist = {"序号", "风险类别", "发票类型", "发票代码", "发票号码", "发票状态", "管理状态", "开票日期", "销方名称", "销方税号", "金额",
                    "税额", "价税合计", "备注", "抵扣税额", "认证状态", "认证类型"};

            String[] titleprop = {"xh", "fxlx", "invoiceType", "invoiceCode", "invoiceNo", "invoiceStatus", "glzt",
                    "invoiceDate", "xfmc", "xfsh", "invoiceAmount", "taxAmount", "totalAmount", "remark", "dkTaxAmount",
                    "rzzt", "bdkStatus"};
            // 需要设置返回列表标题时调用
            json = super.setTitleList(titlelist, titleprop);
            List<String> gfshList = (List<String>) pramsMap.get("gfsh");
            if (gfshList == null || gfshList.size() == 0) {
                return super.responseResult(json);
            }
            PageHelper.startPage(curr, size);
            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjse = "0";
                String hjje = "0";
                ExtTdxRecordInvoice countVo = super.baseMapper.selectRiskInvoiceCount(pramsMap);
                if (countVo != null) {
                    if (countVo.getId() != null && countVo.getId() > 0) {
                        hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(countVo.getTaxAmount().toPlainString()));
                        hjje =
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(countVo.getInvoiceAmount().toPlainString()));
                    }
                }

                json.put("hjsl", hjsl);
                json.put("hjje", hjje);
                json.put("hjfp", hjse);
            }
            PageHelper.startPage(curr, size);
            List<ExtTdxRecordInvoice> pageList = super.baseMapper.selectRiskInvoice(pramsMap);
            PageInfo<ExtTdxRecordInvoice> pageInfo = new PageInfo<>(pageList);
            List<ExtBbfpzhcxRespVO> returnList = new ArrayList<>();
            // 用于页面返回list对象
            if (pageList.size() > 0) {
                List<DictdetaModel> fplxModels = dictdetaServcice.selectDictdeta("INVOICE_TYPE");
                List<DictdetaModel> fpztModels = dictdetaServcice.selectDictdeta("INVOICE_STATUS");
                List<DictdetaModel> glztModels = dictdetaServcice.selectDictdeta("GLZT");
                List<DictdetaModel> rzlxModels = dictdetaServcice.selectDictdeta("BDK_STATUS");
                List<DictdetaModel> rzztModels = dictdetaServcice.selectDictdeta("rzhYesorno");
                List<DictdetaModel> qsztModels = dictdetaServcice.selectDictdeta("qsStatus");
                List<DictdetaModel> accountModels = dictdetaServcice.selectDictdeta("INACCOUNTSTATUS");
                int start = (int) pageInfo.getStartRow();
                for (int i = 0; i < pageList.size(); i++) {
                    ExtTdxRecordInvoice record = pageList.get(i);
                    ExtBbfpzhcxRespVO vo = new ExtBbfpzhcxRespVO();
                    vo.setXh(String.valueOf(i + start));
                    StringBuffer sb = new StringBuffer("");
                    boolean flag = false;
                    if (!"0".equals(record.getInvoiceStatus())) {
                        flag = true;
                        sb.append("发票状态异常");
                    }
                    if ("1".equals(record.getGlzt()) || "2".equals(record.getGlzt())) {
                        if (flag) {
                            sb.append("；管理状态异常");
                        } else {
                            flag = true;
                            sb.append("管理状态异常");
                        }
                    }
                    if ("1".equals(record.getIllegalSupplier())) {
                        if (flag) {
                            sb.append("；供应商违规");
                        } else {
                            flag = true;
                            sb.append("供应商违规");
                        }
                    }
                    if ("1".equals(record.getIllegalEnterprise())) {
                        if (flag) {
                            sb.append("；触发企业管控规则");
                        } else {
                            sb.append("触发企业管控规则");
                        }
                    }
                    vo.setFxlx(sb.toString());
                    vo.setInvoiceType(dictdetaServcice.queryDictName(DictConstant.INVOICE_TYPE_VAT, record.getInvoiceType()));
//                    if (fplxModels != null) {
//                        for (DictdetaModel model : fplxModels) {
//                            if (model.getDictcode().equals(record.getInvoiceType())) {
//                                vo.setInvoiceType(model.getDictname());
//                            }
//                        }
//                    }
                    vo.setInvoiceCode(record.getInvoiceCode());
                    vo.setInvoiceNo(record.getInvoiceNo());
                    if (fpztModels != null) {
                        for (DictdetaModel model : fpztModels) {
                            if (model.getDictcode().equals(record.getInvoiceStatus())) {
                                vo.setInvoiceStatus(model.getDictname());
                            }
                        }
                    }
                    if (glztModels != null) {
                        for (DictdetaModel model : glztModels) {
                            if (model.getDictcode().equals(record.getGlzt())) {
                                vo.setGlzt(model.getDictname());
                            }
                        }
                        if (StringUtils.isBlank(vo.getGlzt())) {
                            vo.setGlzt("正常");
                        }
                    }
                    vo.setInvoiceDate(record.getInvoiceDate() == null ? ""
                            : new SimpleDateFormat("yyyy-MM-dd").format(record.getInvoiceDate()));
                    vo.setXfmc(record.getXfName());
                    vo.setXfsh(record.getXfTaxNo());
                    vo.setInvoiceAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(record.getInvoiceAmount().toPlainString())));
                    vo.setTaxAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(record.getTaxAmount().toPlainString())));
                    vo.setTotalAmount(
                            AmountFormatUtil.fmtMicrometer(MathUtil.round(record.getTotalAmount().toPlainString())));
                    vo.setRemark(record.getRemark());
                    try {
                        vo.setDkTaxAmount(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(record.getDkTaxAmount().toPlainString())));
                    } catch (Exception e) {
                        vo.setDkTaxAmount(
                                AmountFormatUtil.fmtMicrometer(MathUtil.round(record.getTaxAmount().toPlainString())));
                    }
                    if (rzztModels != null) {
                        for (DictdetaModel model : rzztModels) {
                            if (model.getDictcode().equals(record.getRzhYesorno())) {
                                vo.setRzzt(model.getDictname());
                            }
                        }
                    }
                    if (record.getRzhDate() != null) {
                        vo.setRzrq(new SimpleDateFormat("yyyy-MM-dd").format(record.getRzhDate()));
                    }
                    if (record.getQsDate() != null) {
                        vo.setQsrq(new SimpleDateFormat("yyyy-MM-dd").format(record.getQsDate()));
                    }
                    if (record.getInAccountDate() != null) {
                        vo.setInvoiceAmount(new SimpleDateFormat("yyyy-MM-dd").format(record.getInAccountDate()));
                    }
                    if (record.getCollectDate() != null) {
                        vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd").format(record.getCollectDate()));
                    }
                    if (qsztModels != null) {
                        for (DictdetaModel model : qsztModels) {
                            if (model.getDictcode().equals(record.getQsStatus())) {
                                vo.setQszt(model.getDictname());
                            }
                        }
                    }
                    if (accountModels != null) {
                        for (DictdetaModel model : accountModels) {
                            if (model.getDictcode().equals(record.getInAccountStatus())) {
                                vo.setInAccountStatus(model.getDictname());
                            }
                        }
                    }
                    if (rzlxModels != null) {
                        for (DictdetaModel model : rzlxModels) {
                            if (model.getDictcode().equals(record.getBdkStatus())) {
                                vo.setBdkStatus(model.getDictname());
                            }
                        }
                    }
                    vo.setUuid(record.getUuid());
                    returnList.add(vo);
                }
            }

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

    @Override
    public String selectEnterpriseInfo(Map<String, Object> pramsMap) {
        JSONObject json = new JSONObject();
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        try {
            String[] titlelist = {"序号", "违规信息", "控制方式"};

            String[] titleprop = {"xh", "ruleMessage", "isForce"};
            // 需要设置返回列表标题时调用
            json = super.setTitleList(titlelist, titleprop);
            List<EnterpriseInfoModel> resultList = super.baseMapper.selectEnterpriseInfo(pramsMap);
            if (resultList.size() > 0) {
                for (int i = 0; i < resultList.size(); i++) {
                    resultList.get(i).setXh(String.valueOf(i + 1));
                    resultList.get(i).setIsForce(dictdetaServcice.queryDictName(DictConstant.IS_FORCE, resultList.get(i).getIsForce()));
                }
            }
            // 设置记录总数
            json.put("datalist", resultList);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }
        return super.responseResult(json);
    }
}
