package com.dxhy.customs.service.impl;

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

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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.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.NumberToCN;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.customs.dao.CustomsCollectDao;
import com.dxhy.customs.dao.CustomsCustomsDetailDao;
import com.dxhy.customs.dao.CustomsJkszhcxDao;
import com.dxhy.customs.entity.TdxCustomsDetail;
import com.dxhy.customs.entity.TdxCustomsFile;
import com.dxhy.customs.entity.TdxCustomsRecord;
import com.dxhy.customs.model.JkszhcxRespVO;
import com.dxhy.customs.service.CustomsFileService;
import com.dxhy.customs.service.CustomsJkszhcxService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 海关缴款书综合查询
 *
 * @author dxhy
 */
@SuppressWarnings({"AlibabaMethodTooLong", "AlibabaUndefineMagicConstant"})
@Service("customsJkszhcxService")
@Slf4j
public class CustomsCustomsJkszhcxServiceImpl extends MpBaseServiceImpl<CustomsJkszhcxDao, JkszhcxRespVO>
    implements CustomsJkszhcxService {

    @Resource
    private DictdetaServcice dictdetaServcice;
    @Resource
    private CustomsCollectDao customsCollectDao;
    @Resource
    private CustomsCustomsDetailDao customsCustomsDetailDao;
    @Resource
    private CustomsFileService customsFileService;
    @Resource
    private TabulateRedisService tabulateRedisService;

    /**
     * 缴款书综合查询接口
     *
     * @author 陈刚扬
     * @date 2020/8/10
     * @param pramsMap
     * @param curr
     * @param size
     * @return java.lang.String
     */
    @Override
    public String selectByPramsMap(Map<String, Object> pramsMap, int curr, int size) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);

        JSONObject json =
            tabulateRedisService.getTabulateMenu(pramsMap.get("company").toString(), pramsMap.get("menuId").toString());
        try {

            if (CollectionUtils.isEmpty((List<String>)pramsMap.get("gfsh"))) {
                json.put("total", "0");
                json.put("datalist", new ArrayList<>());
                return super.responseResult(json);
            }

            // 合计信息,仅第一页时需要统计，减少数据库压力
            if (curr == 1) {
                String hjsl = "0";
                String hjse = "0";
                Map<String, Object> hjxx = super.baseMapper.selectHjxx(pramsMap);
                if (hjxx != null) {
                    hjsl = (long)hjxx.get("hjsl") + "";
                    if (!"0".equals(hjsl)) {
                        hjsl = AmountFormatUtil.fmtMicrometer(hjsl);
                        hjse = AmountFormatUtil.fmtMicrometer(MathUtil.round(hjxx.get("hjse") + ""));
                    }
                }
                json.put("hjsl", hjsl);
                json.put("hjse", hjse);
            }
            PageHelper.startPage(curr, size);
            List<JkszhcxRespVO> pageList = super.baseMapper.selectByPramsMap(pramsMap);
            PageInfo<JkszhcxRespVO> pageInfo = new PageInfo<>(pageList);
            // 用于页面返回list对象
            if (pageList.size() > 0) {
                int start = new Long(pageInfo.getStartRow()).intValue();

                for (int i = 0; i < pageList.size(); i++) {
                    pageList.get(i).setXh(String.valueOf(i + start));
                    pageList.get(i)
                        .setTaxAmount(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount())));
                    pageList.get(i).setYxTaxAmount(
                        AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getYxTaxAmount())));

                    // 字典值转换
                    String inaccountStatus = pageList.get(i).getInaccountStatus();
                    if ("1".equals(inaccountStatus)){
                        pageList.get(i).setInaccountStatus("已入账");
                    }else if ("0".equals(inaccountStatus)) {
                        pageList.get(i).setInaccountStatus("未入账");
                    }
                     String auditStatus = pageList.get(i).getAuditStatus();
                    pageList.get(i)
                        .setAuditStatus(dictdetaServcice.queryDictName(DictConstant.AUDIT_STATUS, auditStatus));
                    String applyCheck = pageList.get(i).getApplyCheck();
                    pageList.get(i).setApplyCheck(dictdetaServcice.queryDictName(DictConstant.APPLY_CHECK, applyCheck));
                    String checkStatus = pageList.get(i).getCheckStatus();
                    pageList.get(i)
                        .setCheckStatus(dictdetaServcice.queryDictName(DictConstant.CHECK_STATUS, checkStatus));
                    if ("0".equals(pageList.get(i).getBdkStatus())) {
                        pageList.get(i).setBdkStatus("");
                    } else {
                        String bdkStatus = pageList.get(i).getBdkStatus();
                        pageList.get(i)
                            .setBdkStatus(dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, bdkStatus));
                    }
                    String glzt = pageList.get(i).getGlzt();
                    pageList.get(i).setGlzt(dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
                    String qsStatus = pageList.get(i).getQsStatus();
                    pageList.get(i).setQsStatus(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, qsStatus));
                    String authStatus = pageList.get(i).getAuthStatus();
                    pageList.get(i)
                        .setAuthStatus(dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, authStatus));
                    String qsType = pageList.get(i).getQsType();
                    pageList.get(i).setQsType(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsType));
                    String rzhYesorno = pageList.get(i).getRzhYesorno();
                    pageList.get(i).setRzhYesorno(dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, rzhYesorno));
                }
            }
            // 设置记录总数
            json.put("total", pageInfo.getTotal());
            List<JkszhcxRespVO> resultList = pageInfo.getList();
            json.put("datalist", CollectionUtils.isEmpty(resultList) ? new ArrayList<>() : resultList);
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }
        return super.responseResult(json);
    }

    /**
     * 缴款书票样查询
     *
     * @author 陈刚扬
     * @date 2020/8/10
     * @param pramsMap
     * @return java.lang.String
     */
    @Override
    public String getCustomsInfo(Map<String, String> pramsMap) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        QueryWrapper<TdxCustomsRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customs_code", pramsMap.get("customsCode"));
        TdxCustomsRecord record = customsCollectDao.selectOne(queryWrapper);
        if (record != null) {
            return super.responseResult(this.createCustomsInfo(record, pramsMap.get("dbName")));
        } else {
            return null;
        }
    }

    /**
     * 封装缴款书票样信息
     *
     * @author 陈刚扬
     * @date 2020/8/10
     * @param record
     * @param dbName
     * @return com.alibaba.fastjson.JSONObject
     */
    private JSONObject createCustomsInfo(TdxCustomsRecord record, String dbName) {

        List<TdxCustomsDetail> detailList = null;
        DynamicContextHolder.push(dbName + DbConstant.DETAIL_READ);
        QueryWrapper<TdxCustomsDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customs_code", record.getCustomsCode());
        detailList = customsCustomsDetailDao.selectList(queryWrapper);
        JSONObject info = this.createCheckInfo(record, detailList, dbName);
        return info;
    }

    private JSONObject createCheckInfo(TdxCustomsRecord record, List<TdxCustomsDetail> detailList, String dbName) {

        JSONObject checkInfo = new JSONObject();
        JkszhcxRespVO checkRecordVo = this.convertToCheckRecordVo(record, dbName);

        // 取发票上的价税合计
        String taxAmount = checkRecordVo.getTaxAmount();
        // 税款金额小写
        checkInfo.put("taxAmount", taxAmount);
        // 税款金额大写
        checkInfo.put("stringTaxAmount", NumberToCN.number2CNMontrayUnit(new BigDecimal(taxAmount)));
        // 发票票面信息
        checkInfo.put("customsSubjectList", JSON.toJSON(checkRecordVo));
        String se = "";
        // 发票明细
        if (detailList != null && detailList.size() > 0) {
            int count = detailList.size();

            JSONArray detail = new JSONArray(count);
            for (TdxCustomsDetail tdxCustomsDetail : detailList) {
                TdxCustomsDetail checkRecordDetailVo = this.convertToRecordDetailVo(tdxCustomsDetail);
                // 明细框 税额合计
                detail.add(JSON.toJSON(checkRecordDetailVo));
                try {
                    Double.parseDouble(checkRecordDetailVo.getTaxAmount());
                } catch (Exception e) {
                    se = checkRecordDetailVo.getTaxAmount();
                }
            }
            checkInfo.put("invoiceDetails", detail);
        } else {
            checkInfo.put("invoiceDetails", new JSONArray());
        }

        return checkInfo;
    }

    public JkszhcxRespVO convertToCheckRecordVo(TdxCustomsRecord record, String dbName) {
        JkszhcxRespVO vo = new JkszhcxRespVO();
        vo.setCustomsCode(record.getCustomsCode());
        // 双税号调整为逗号拼接
        if (StringUtils.isNotBlank(record.getPayerTwoName())) {
            vo.setPayerOneName(record.getPayerOneName() + "," + record.getPayerTwoName());
        } else {
            vo.setPayerOneName(record.getPayerOneName());
        }
        if (StringUtils.isNotBlank(record.getPayerTwoTaxno())) {
            vo.setPayerOneTaxno(record.getPayerOneTaxno() + "," + record.getPayerTwoTaxno());
        } else {
            vo.setPayerOneTaxno(record.getPayerOneTaxno());
        }

        vo.setPayerTwoTaxno(record.getPayerTwoTaxno());
        vo.setPayerTwoName(record.getPayerTwoName());
        vo.setFillInDate(record.getFillInDate() == null ? "" : DateUtils.dateToStr(record.getFillInDate()));
        vo.setTaxAmount(record.getTaxAmount());
        vo.setYxTaxAmount(record.getYxTaxAmount());
        vo.setImportPortCode(record.getImportPortCode());
        vo.setIncomeOffice(record.getIncomeOffice());
        vo.setApplicantCode(record.getApplicantCode());
        vo.setBillCode(record.getBillCode());
        vo.setModeType(record.getModeType());
        vo.setBudgetCode(record.getBudgetCode());
        vo.setTreasuryCode(record.getTreasuryCode());
        vo.setContractCode(record.getContractCode());
        vo.setMeansTransport(record.getMeansTransport());
        vo.setPaymentPeriod(record.getPaymentPeriod());
        vo.setDeliveryCode(record.getDeliveryCode());
        vo.setCreateDate(record.getCreateDate() == null ? "" : DateUtils.dateToStr(record.getCreateDate()));
        vo.setUpdateDate(record.getUpdateDate() == null ? "" : DateUtils.dateToStr(record.getUpdateDate()));

        // 字典值转换
        String dataSources = record.getDataSources();
        vo.setDataSources(dictdetaServcice.queryDictName(DictConstant.JKSCJFS, dataSources));
        String auditStatus = record.getAuditStatus();
        vo.setAuditStatus(dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, auditStatus));
        String applyCheck = record.getApplyCheck();
        vo.setApplyCheck(dictdetaServcice.queryDictName(DictConstant.APPLY_CHECK, applyCheck));
        String checkStatus = record.getCheckStatus();
        vo.setCheckStatus(dictdetaServcice.queryDictName(DictConstant.CHECK_STATUS, checkStatus));
        String qsStatus = record.getQsStatus();
        vo.setQsStatus(dictdetaServcice.queryDictName(DictConstant.QS_STATUS, qsStatus));
        String qsType = record.getQsType();
        vo.setQsType(dictdetaServcice.queryDictName(DictConstant.QS_TYPE, qsType));
        String rzhType = record.getRzhType();
        vo.setRzhType(dictdetaServcice.queryDictName(DictConstant.DEDU_TYPE, rzhType));
        String rzhYesorno = record.getRzhYesorno();
        vo.setRzhYesorno(dictdetaServcice.queryDictName(DictConstant.DEDU_STATUS, rzhYesorno));
        String authStatus = record.getAuthStatus();
        vo.setAuthStatus(dictdetaServcice.queryDictName(DictConstant.AUTH_STATUS_ALL, authStatus));
        String glzt = record.getGlzt();
        vo.setGlzt(dictdetaServcice.queryDictName(DictConstant.GLZT, glzt));
        String bdkStatus = record.getBdkStatus();
        vo.setBdkStatus(dictdetaServcice.queryDictName(DictConstant.BDK_STATUS, bdkStatus));
        String entryDiscrepancy = record.getEntryDiscrepancy();
        vo.setEntryDiscrepancy(dictdetaServcice.queryDictName(DictConstant.ENTRY_DISCREPANCY, entryDiscrepancy));

        vo.setQsDate(record.getQsDate() == null ? "" : DateUtils.dateToStr(record.getQsDate()));
        vo.setQsUser(record.getQsUser());
        vo.setRzhDate(record.getRzhDate() == null ? "" : DateUtils.dateToStr(record.getRzhDate()));
        vo.setRzhBelongDate(record.getRzhBelongDate());
        vo.setConfirmDate(record.getConfirmDate() == null ? "" : DateUtils.dateToStr(record.getConfirmDate()));
        vo.setSendDate(record.getSendDate() == null ? "" : DateUtils.dateToStr(record.getSendDate()));
        vo.setConfirmUser(record.getConfirmUser());
        vo.setDeptId(record.getDeptId());
        vo.setDeptName(record.getDeptName());
        vo.setCustomsScanId(record.getCustomsScanId());
        vo.setEntryDate(record.getEntryDate() == null ? "" : DateUtils.dateToStr(record.getEntryDate()));
        vo.setEntryUser(record.getEntryUser());
        if (StringUtils.isNotBlank(record.getCustomsScanId())) {
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            TdxCustomsFile file = customsFileService.selectByCustomsScanId(record.getCustomsScanId());
            if (file != null) {
                String imgPath = file.getImagePath();
                if (StringUtils.isNotBlank(imgPath)) {
                    vo.setFilePath(imgPath.substring(imgPath.lastIndexOf("/") + 1));
                }
            }
        }
        // 入账时间，入账状态
        if (StringUtils.isNotBlank(record.getInAccountDate()) && record.getInAccountDate().trim().length() > 11) {
            vo.setInAccountDate(record.getInAccountDate().substring(0, 11));
        } else {
            vo.setInAccountDate(null);
        }
        if ("0".equals(record.getInAccountStatus())) {
            vo.setInaccountStatus("未入账");
        } else if ("1".equals(record.getInAccountStatus())) {
            vo.setInaccountStatus("已入账");
        } else {
            vo.setInaccountStatus("未入账");
        }
        return vo;
    }

    private TdxCustomsDetail convertToRecordDetailVo(TdxCustomsDetail detail) {
        TdxCustomsDetail checkRecordDetailVo = new TdxCustomsDetail();
        if (StringHelper.trimEnter(detail.getTaxRate()).matches("[0-9]{1,}")) {
            checkRecordDetailVo.setTaxRate(StringHelper.trimEnter(detail.getTaxRate()) + "%");
        } else {
            checkRecordDetailVo.setTaxRate(StringHelper.trimEnter(detail.getTaxRate()));
        }
        checkRecordDetailVo.setCustomsCode(StringHelper.trimEnter(detail.getCustomsCode()));
        checkRecordDetailVo.setDetailAmount(StringHelper.trimEnter(detail.getDetailAmount()));
        checkRecordDetailVo.setTaxno(StringHelper.trimEnter(detail.getTaxno()));
        checkRecordDetailVo.setGoodsName(StringHelper.trimEnter(detail.getGoodsName()));
        checkRecordDetailVo.setNum(StringHelper.trimEnter(detail.getNum()));
        checkRecordDetailVo.setTaxAmount(StringHelper.trimEnter(detail.getTaxAmount()));

        checkRecordDetailVo.setUnit(StringHelper.trimEnter(detail.getUnit()));
        checkRecordDetailVo.setDataSources(StringHelper.trimEnter(detail.getDataSources()));
        return checkRecordDetailVo;
    }

}
