package com.dxhy.customs.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.DictConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.enums.DataSourceEnum;
import com.dxhy.common.service.CustomsLogService;
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.StringHelper;
import com.dxhy.common.utils.DateUtils;
import com.dxhy.common.vo.CustomsLog;
import com.dxhy.common.vo.Tax;
import com.dxhy.common.vo.UserInfo;
import com.dxhy.customs.constants.ApplyCheckEnum;
import com.dxhy.customs.constants.CollectUploadStatusEnum;
import com.dxhy.customs.constants.DicProp;
import com.dxhy.customs.constants.GlztEnum;
import com.dxhy.customs.dao.CustomsRecordDao;
import com.dxhy.customs.dao.CustomsScanLogDao;
import com.dxhy.customs.entity.TdxCustomsRecord;
import com.dxhy.customs.entity.TdxScanCustomsLog;
import com.dxhy.customs.model.CustomsInsertImpotVO;
import com.dxhy.customs.model.ResultData;
import com.dxhy.customs.model.TdxCustomsRecordDTO;
import com.dxhy.customs.service.CustomsRecordService;
import com.dxhy.customs.utils.DateUtil;
import com.dxhy.customs.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author dxhy
 */
@SuppressWarnings("AlibabaMethodTooLong")
@Service("customsRecordService")
@Slf4j
public class CustomsRecordServiceImpl extends MpBaseServiceImpl<CustomsRecordDao, TdxCustomsRecord>
    implements CustomsRecordService {

    private static final String PATTERN_JUDGE_DATE =
        "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
    /**
     * 判断小数点后2位的数字的正则表达式
     */
    private static final String PATTERN_JUDGE_AMOUNT = "^(([1-9]\\d*)|([0]))(\\.(\\d){0,2})?$";
    private static final ResultData<?> RESULT_DATA = new ResultData<>();
    @Resource
    private CustomsLogService customsLogService;
    @Resource
    private TabulateRedisService tabulateRedisService;
    @Resource
    private DictdetaServcice dictdetaServcice;

    @Resource
    private CustomsScanLogDao scanLogDao;

    /**
     * 查询海关缴款书列表
     *
     * @param page
     *            分页
     * @param entity
     *            实体
     * @param userInfo
     *            用户信息
     * @return java.lang.String
     * @author 陈刚扬
     * @date 2020/8/10
     */
    @Override
    public String query(Page<?> page, TdxCustomsRecordDTO entity, UserInfo userInfo) {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        entity.setParam(page);
        if (StringUtils.isEmpty(entity.getGfTaxNo())) {
            entity.setBuyTaxNoFromUser(userInfo);
        }
        Map<String, Object> data = new HashMap<>(16);

        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(entity.getCompany(), entity.getMenuId());
        RESULT_DATA.putTabulateMenu(tabulateMenu);

        if (StringUtils.isBlank(entity.getGfTaxNo()) && CollectionUtils.isEmpty(entity.getGfTaxNoList())) {
            data.put("taxAmountSum", "0");
            return RESULT_DATA.getPageData(null).toJsonBase();
        } else {
            if (entity.getCurr() == 1) {
                data = this.baseMapper.sumTaxAmount(entity);
                if (data != null) {
                    data.put("taxAmountSum",
                        AmountFormatUtil.fmtMicrometer(ObjectUtil.fixNull(data.get("taxAmountSum"))));
                } else {
                    data = new HashMap<>(16);
                    data.put("taxAmountSum", "0");
                }
            }
        }
        Page<Map<String, String>> result = this.baseMapper.queryCollect(page, entity);
        if (ResultData.isEmpty(result)) {
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, String> map = result.getRecords().get(i);
                map.put("index",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));
                map.put("taxSum", AmountFormatUtil.fmtMicrometer(ObjectUtil.fixNull(map.get("taxSum"))));
                map.put("gfName", getGfmcByGfsh(ObjectUtil.fixNull(map.get("gfTaxNo")), userInfo.getOrg()));
            }
        }

        return RESULT_DATA.getPageData(result).putData(data).toJsonBase();
    }

    private String getGfmcByGfsh(String gfsh, List<Tax> orgList) {
        String gfmc = "";
        for (Tax org : orgList) {
            if (gfsh.equals(org.getTaxno())) {
                gfmc = org.getTaxname();
                if (StringHelper.isBlank(gfmc)) {
                    gfmc = "";
                }
                break;
            }
        }
        return gfmc;
    }

    /**
     * 缴款书采集列表查看详情
     *
     * @param page
     *            分页
     * @param entity
     *            入参
     * @param userInfo
     *            用户信息
     * @return java.lang.String
     * @author 陈刚扬
     * @date 2020/8/10
     */
    @Override
    public String detail(Page<?> page, TdxCustomsRecordDTO entity, UserInfo userInfo) {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        entity.setParam(page);
        Page<Map<String, String>> result = this.baseMapper.queryCollectDetail(page, entity);
        if (ResultData.isEmpty(result)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, String> map = result.getRecords().get(i);
                map.put("index",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));
                if (map.get("fillInDate") != null) {
                    map.put("fillInDate",map.get("fillInDate"));
                }
                map.put("taxAmount", AmountFormatUtil.fmtMicrometer(ObjectUtil.fixNull(map.get("taxAmount"))));
            }
        }
        return RESULT_DATA.getPageData(result)
            .putTitleList(DicProp.CUSTOMS_COLLECT_DETAIL_TITLE, DicProp.CUSTOMS_COLLECT_DETAIL_PROP).toJsonBase();
    }

    /**
     * 缴款书录入列表查询
     *
     * @param page
     *            分页
     * @param entity
     *            入参
     * @param userInfo
     *            用户信息
     * @return java.lang.String
     * @author 陈刚扬
     * @date 2020/8/10
     */
    @Override
    public String insertQuery(Page<?> page, TdxCustomsRecordDTO entity, UserInfo userInfo) {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        entity.setParam(page);
        if (StringUtils.isEmpty(entity.getGfTaxNo())) {
            entity.setBuyTaxNoFromUser(userInfo);
        }
        JSONObject tabulateMenu = tabulateRedisService.getTabulateMenu(entity.getCompany(), entity.getMenuId());
        RESULT_DATA.putTabulateMenu(tabulateMenu);
        //格式化入参
        if (entity.getCreateDateBegin()!= null && !"".equals(entity.getCreateDateBegin())) {
            entity.setCreateDateBegin(DateUtils.getMorning(DateUtils.strToDate(entity.getCreateDateBegin())));
        }
        if (entity.getCreateDateEnd() != null && !"".equals(entity.getCreateDateEnd())) {
            entity.setCreateDateEnd(DateUtils.getNight(DateUtils.strToDate(entity.getCreateDateEnd())));
        }
        if(entity.getFillInDateBegin()!=null && !"".equals(entity.getFillInDateBegin())){
            entity.setFillInDateBegin(DateUtils.getMorning(DateUtils.strToDate(entity.getFillInDateBegin())));
        }
        if(entity.getFillInDateEnd()!=null && !"".equals(entity.getFillInDateEnd())){
            entity.setFillInDateEnd(DateUtils.getNight(DateUtils.strToDate(entity.getFillInDateEnd())));
        }
        Map<String, Object> data = new HashMap<>(16);
        if (StringUtils.isBlank(entity.getGfTaxNo()) && entity.getGfTaxNoList().size() <= 0) {
            data.put("taxAmountSum", "0.00");
            return RESULT_DATA.getPageData(null).putData(data).toJsonBase();
        } else {
            if (entity.getCurr() == 1) {
                entity.setEntryFlag("1");
                data = this.baseMapper.sumTaxAmount(entity);
                if (data != null) {
                    if (data.get("taxAmountSum") == null) {
                        data.put("taxAmountSum", "0.00");
                    } else {
                        data.put("taxAmountSum",
                            AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(data.get("taxAmountSum")))
                                .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                    }

                }
            }
        }
        Page<Map> result = this.baseMapper.insertQuery(page, entity);
        if (ResultData.isEmpty(result)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = result.getRecords().get(i);
                map.put("index",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));
                if (StringUtils.isBlank((String)map.get("taxAmount"))) {
                    map.put("taxAmount", "0.00");
                } else {
                    map.put("taxAmount",
                        AmountFormatUtil.fmtMicrometer(new BigDecimal(ObjectUtil.fixNull(map.get("taxAmount")))
                            .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                }
                if ("3".equals(map.get("collectUploadStatus")) || "0".equals(map.get("collectUploadStatus"))) {
                    map.put("delState", true);
                    map.put("editState", true);
                } else if ("2".equals(map.get("collectUploadStatus"))) {
                    if ("0".equals(map.get("applyCheck")) && "1".equals(map.get("auditStatus"))) {
                        map.put("delState", false);
                        map.put("editState", false);
                    } else if ("1".equals(map.get("applyCheck")) && "0".equals(map.get("checkStatus"))) {
                        map.put("delState", false);
                        map.put("editState", false);
                    } else {
                        map.put("delState", true);
                        map.put("editState", true);
                    }
                } else {
                    map.put("delState", false);
                    map.put("editState", false);
                }
                map.put("sczt", map.get("collectUploadStatus"));

                map.put("failReason",dictdetaServcice.queryDictName(DictConstant.JKSSCSBYY,(String)map.get("failReason")));
                map.put("auditStatus",dictdetaServcice.queryDictName(DictConstant.AUDIT_STATUS,(String)map.get("auditStatus")));
                map.put("applyCheck",dictdetaServcice.queryDictName(DictConstant.APPLY_CHECK,(String)map.get("applyCheck")));
                map.put("checkStatus",dictdetaServcice.queryDictName(DictConstant.CHECK_STATUS,(String)map.get("checkStatus")));
                map.put("dataSources",dictdetaServcice.queryDictName(DictConstant.JKSCJFS,(String)map.get("dataSources")));
                map.put("collectUploadStatus",dictdetaServcice.queryDictName(DictConstant.JKSSCZT,(String)map.get("collectUploadStatus")));

                if (map.get("fillInDate") != null) {
                    map.put("fillInDate", map.get("fillInDate"));
                }
                if (map.get("entryDate") != null) {
                    map.put("entryDate", map.get("entryDate"));
                }
            }
        }

        return RESULT_DATA.getPageData(result).putData(data).toJsonBase();
    }

    /**
     * 缴款书手工录入入库
     *
     * @param entity
     *            海关缴款书信息
     * @param userInfo
     *            用户信息
     * @return java.lang.String
     * @author 陈刚扬
     * @date 2020/8/10
     */
    @Override
    public String insert(TdxCustomsRecord entity, UserInfo userInfo) {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        Map<String, Object> data = new HashMap<>(16);

        if (StringUtils.isBlank(entity.getGfTaxNo())) {
            data.put("code", "-1");
            data.put("msg", "购方税号不能为空");
            return RESULT_DATA.putData(data).toJsonBase();
        }

        if (StringUtils.isBlank(entity.getCustomsCode())) {
            data.put("code", "-1");
            data.put("msg", "缴款书号码不能为空");
            return RESULT_DATA.putData(data).toJsonBase();
        }
        if (entity.getFillInDate() == null) {
            data.put("code", "-1");
            data.put("msg", "填发日期不能为空");
            return RESULT_DATA.putData(data).toJsonBase();
        }
        Pattern pattern = Pattern.compile(PATTERN_JUDGE_DATE);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Matcher match = pattern.matcher(sdf.format(entity.getFillInDate()));
        if (!match.matches()) {
            return "填发日期格式错误";
        }

        if (StringUtils.isBlank(entity.getTaxAmount())) {
            data.put("code", "-1");
            data.put("msg", "税款金额不能为空");
            return RESULT_DATA.putData(data).toJsonBase();
        }

        Pattern pattern2 = Pattern.compile(PATTERN_JUDGE_AMOUNT);
        Matcher match2 = pattern2.matcher(entity.getTaxAmount());
        if (!match2.matches()) {
            return "税款金额格式错误";
        }

        LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TdxCustomsRecord::getCustomsCode, entity.getCustomsCode());
        TdxCustomsRecord query = this.getOne(wrapper);
        if (query != null) {
            data.put("code", "-1");
            data.put("msg", "已有缴款书信息！");
            return RESULT_DATA.putData(data).toJsonBase();
        }

        if (StringUtils.isBlank(entity.getGfName())) {
            entity.setGfName(getGfmcByGfsh(entity.getGfTaxNo(), userInfo.getOrg()));
        }
        entity.setPayerOneTaxno(entity.getGfTaxNo());
        entity.setPayerOneName(getGfmcByGfsh(entity.getGfTaxNo(), userInfo.getOrg()));
        entity.setYxTaxAmount(entity.getTaxAmount());
        entity.setDataSources(DataSourceEnum.B.getKey());
        entity.setCreateDate(new Date());
        entity.setDataType("17");
        entity.setCollectUploadStatus(CollectUploadStatusEnum.A.getKey());
        entity.setGlzt(GlztEnum.A.getKey());
        entity.setApplyCheck(ApplyCheckEnum.A.getKey());
        entity.setEntryDate(new Date());
        entity.setEntryUser(userInfo.getUsername());
        entity.setCompany(userInfo.getCompany());
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_WRITE);
        this.baseMapper.insert(entity);
        data.put("code", "0");
        data.put("msg", "录入成功");
        List<CustomsLog> logList = new ArrayList<>();
        CustomsLog customsLog = new CustomsLog();
        customsLog.setCustomsCode(entity.getCustomsCode());
        customsLog.setInputStatus("20");
        customsLog.setInputName(userInfo.getLoginname());
        customsLog.setCreateDate(new Date());
        customsLog.setType("10");
        logList.add(customsLog);
        customsLogService.toCustomsLog(logList);
        return RESULT_DATA.putData(data).toJsonBase();
    }

    /**
     * 缴款书手工录入修改入库
     *
     * @param entity
     * @param userInfo
     * @return java.lang.String
     * @author 陈刚扬
     * @date 2020/8/10
     */
    @Override
    public String editCustoms(TdxCustomsRecord entity, UserInfo userInfo) throws Exception {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        Map<String, Object> data = new HashMap();
        if (entity.getId() == null) {
            data.put("code", "-1");
            data.put("msg", "id不能为空");
            return new ResultData().putData(data).toJsonBase();
        }
        if (StringUtils.isBlank(entity.getGfTaxNo())) {
            data.put("code", "-1");
            data.put("msg", "购方税号不能为空");
            return new ResultData().putData(data).toJsonBase();
        }

        if (StringUtils.isBlank(entity.getCustomsCode())) {
            data.put("code", "-1");
            data.put("msg", "缴款书号码不能为空");
            return new ResultData().putData(data).toJsonBase();
        }
        if (entity.getFillInDate() == null) {
            data.put("code", "-1");
            data.put("msg", "填发日期不能为空");
            return new ResultData().putData(data).toJsonBase();
        }
        Pattern pattern = Pattern.compile(PATTERN_JUDGE_DATE);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Matcher match = pattern.matcher(sdf.format(entity.getFillInDate()));
        if (!match.matches()) {
            data.put("code", "-1");
            data.put("msg", "填发日期格式错误");
            return new ResultData().putData(data).toJsonBase();
        }

        if (StringUtils.isBlank(entity.getTaxAmount())) {
            data.put("code", "-1");
            data.put("msg", "税款金额不能为空");
            return new ResultData().putData(data).toJsonBase();
        }

        Pattern pattern2 = Pattern.compile(PATTERN_JUDGE_AMOUNT);
        Matcher match2 = pattern2.matcher(entity.getTaxAmount());
        if (!match2.matches()) {
            data.put("code", "-1");
            data.put("msg", "税款金额格式错误");
            return new ResultData().putData(data).toJsonBase();
        }

        LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper();
        wrapper.eq(TdxCustomsRecord::getCustomsCode, entity.getCustomsCode());
        wrapper.ne(TdxCustomsRecord::getId, entity.getId());
        TdxCustomsRecord query = this.getOne(wrapper);
        if (query != null) {
            data.put("code", "-1");
            data.put("msg", "已有缴款书信息！");
            return new ResultData().putData(data).toJsonBase();
        }
        LambdaQueryWrapper<TdxCustomsRecord> recordWrapper = new LambdaQueryWrapper();
        recordWrapper.eq(TdxCustomsRecord::getId, entity.getId());
        TdxCustomsRecord record = this.getOne(recordWrapper);
        if ("1".equals(record.getCollectUploadStatus())) {
            data.put("code", "-1");
            data.put("msg", "缴款书不符合修改条件");
            return new ResultData().putData(data).toJsonBase();
        } else if ("2".equals(record.getCollectUploadStatus())) {
            if ("0".equals(record.getApplyCheck()) && "1".equals(record.getAuditStatus())) {
                data.put("code", "-1");
                data.put("msg", "缴款书不符合修改条件");
                return new ResultData().putData(data).toJsonBase();
            } else if ("1".equals(record.getApplyCheck()) && "0".equals(record.getCheckStatus())) {
                data.put("code", "-1");
                data.put("msg", "缴款书不符合修改条件");
                return new ResultData().putData(data).toJsonBase();
            }
        }
        if (StringUtils.isBlank(entity.getGfName())) {
            entity.setGfName(getGfmcByGfsh(entity.getGfTaxNo(), userInfo.getOrg()));
        }
        entity.setPayerOneTaxno(entity.getGfTaxNo());
        entity.setPayerOneName(getGfmcByGfsh(entity.getGfTaxNo(), userInfo.getOrg()));
        entity.setYxTaxAmount(entity.getTaxAmount());
        entity.setDataSources(DataSourceEnum.B.getKey());
        entity.setCreateDate(new Date());
        entity.setDataType("17");
        entity.setCollectUploadStatus(CollectUploadStatusEnum.A.getKey());
        entity.setGlzt(GlztEnum.A.getKey());
        entity.setApplyCheck(ApplyCheckEnum.A.getKey());
        entity.setEntryDate(new Date());
        entity.setEntryUser(userInfo.getUsername());
        entity.setCompany(userInfo.getCompany());
        entity.setAuditStatus("");
        entity.setCheckStatus("");
        entity.setFailReason("");
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_WRITE);
        this.baseMapper.updateById(entity);
        data.put("code", "0");
        data.put("msg", "修改成功");
        List<CustomsLog> logList = new ArrayList<>();
        CustomsLog customsLog = new CustomsLog();
        customsLog.setCustomsCode(entity.getCustomsCode());
        customsLog.setInputStatus("20");
        customsLog.setInputName(userInfo.getLoginname());
        customsLog.setCreateDate(new Date());
        customsLog.setType("10");
        logList.add(customsLog);
        customsLogService.toCustomsLog(logList);
        return new ResultData().putData(data).toJsonBase();
    }

    @Override
    public String deleteCustoms(TdxCustomsRecord entity, UserInfo userInfo) throws Exception {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        Map<String, Object> data = new HashMap();
        if (entity.getId() == null) {
            data.put("code", "-1");
            data.put("msg", "id不能为空");
            return new ResultData().putData(data).toJsonBase();
        }
        TdxCustomsRecord query = this.getById(entity.getId());
        if (query == null) {
            data.put("code", "-1");
            data.put("msg", "无缴款书信息！");
            return new ResultData().putData(data).toJsonBase();
        } else if ("1".equals(query.getCollectUploadStatus())) {
            data.put("code", "-1");
            data.put("msg", "缴款书不符合删除条件");
            return new ResultData().putData(data).toJsonBase();
        } else if ("2".equals(query.getCollectUploadStatus())) {
            if ("0".equals(query.getApplyCheck()) && "1".equals(query.getAuditStatus())) {
                data.put("code", "-1");
                data.put("msg", "缴款书不符合删除条件");
                return new ResultData().putData(data).toJsonBase();
            } else if ("1".equals(query.getApplyCheck()) && "0".equals(query.getCheckStatus())) {
                data.put("code", "-1");
                data.put("msg", "缴款书不符合删除条件");
                return new ResultData().putData(data).toJsonBase();
            }
        }
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_WRITE);
        this.baseMapper.deleteById(entity.getId());
        data.put("code", "0");
        data.put("msg", "删除成功");
        return new ResultData().putData(data).toJsonBase();
    }

    /**
     * excel导入校验
     *
     * @param pramsMap
     *            pramsMap
     * @return java.lang.String
     * @author 陈刚扬
     * @date 2020/8/10
     */
    @Override
    public String importCustoms(Map<String, Object> pramsMap) {
        String[] titlelist = {"序号", "错误提示", "缴款单位税号", "缴款书号码", "填发日期", "税款金额"};
        String[] titleprop = {"xh", "cwts", "jkdwsh", "jkshm", "tfrq", "skje"};
        DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(pramsMap.get("dbName")), "business")
            + DbConstant.BUSINESS_READ);
        // 需要设置返回列表标题时调用
        JSONObject json = super.setTitleList(titlelist, titleprop);

        List<Object> returnList = new ArrayList<>();
        String datalist = (String)pramsMap.get("datalist");
        List<String> list = (List<String>)pramsMap.get("gfsh");
        JSONObject listjson = JSONObject.parseObject(datalist);
        // 首先把字符串转成 JSONArray 对象
        JSONArray jsonArray = JSONArray.parseArray(listjson.getString("datalist"));

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            CustomsInsertImpotVO vo = jsonObject.toJavaObject(CustomsInsertImpotVO.class);
            if (list != null && list.size() > 0 && !list.contains(vo.getJkdwsh())) {
                vo.setCwts("不可操作此税号!");
                returnList.add(vo);
                continue;
            }
            if (StringUtils.isBlank(vo.getJkdwsh())) {
                vo.setCwts("购方税号不能为空");
                returnList.add(vo);
                continue;
            } else {
                vo.setJkdwsh(vo.getJkdwsh().trim());
            }

            if (StringUtils.isBlank(vo.getJkshm())) {
                vo.setCwts("缴款书号码不能为空");
                returnList.add(vo);
                continue;
            } else {
                vo.setJkshm(vo.getJkshm().trim());
            }
            if (vo.getTfrq() == null) {
                vo.setCwts("填发日期不能为空");
                returnList.add(vo);
                continue;
            } else {
                vo.setTfrq(vo.getTfrq().trim());
            }
            Pattern pattern = Pattern.compile(PATTERN_JUDGE_DATE);
            Matcher match = pattern.matcher(vo.getTfrq());
            if (!match.matches()) {
                vo.setCwts("填发日期格式错误");
                returnList.add(vo);
                continue;
            }
            LocalDate today = LocalDate.now();
            DateTimeFormatter stf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(vo.getTfrq(), stf);
            if (date.isAfter(today)) {
                vo.setCwts("填发日期错误");
                returnList.add(vo);
                continue;
            }
            if (StringUtils.isBlank(vo.getSkje())) {
                vo.setCwts("税款金额不能为空");
                returnList.add(vo);
                continue;
            } else {
                vo.setSkje(vo.getSkje().trim());
            }

            Pattern pattern2 = Pattern.compile(PATTERN_JUDGE_AMOUNT);
            Matcher match2 = pattern2.matcher(vo.getSkje());
            if (!match2.matches()) {
                vo.setCwts("税款金额格式错误");
                returnList.add(vo);
                continue;
            }
            vo.setSkje(AmountFormatUtil
                .fmtMicrometer(new BigDecimal(vo.getSkje()).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
            LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TdxCustomsRecord::getCustomsCode, vo.getJkshm());
            TdxCustomsRecord query = this.getOne(wrapper);
            if (query != null) {
                vo.setCwts("已有缴款书信息!");
                returnList.add(vo);
                continue;
            }

            returnList.add(vo);
        }
        json.put("datalist", returnList);
        return this.responseResult(json);
    }

    /**
     * 批量提交录入接口
     *
     * @param pramsMap
     *            pramsMap
     * @param userInfo
     *            userInfo
     * @return java.lang.String
     * @author 陈刚扬
     * @date 2020/8/10
     */
    @Override
    public String submitImportCustoms(Map<String, Object> pramsMap, UserInfo userInfo) {
        DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(pramsMap.get("dbName")), "business")
            + DbConstant.BUSINESS_READ);
        String datalist = (String)pramsMap.get("datalist");
        List<String> list = (List<String>)pramsMap.get("gfsh");
        JSONObject listjson = JSONObject.parseObject(datalist);
        // 首先把字符串转成 JSONArray 对象
        JSONArray jsonArray = JSONArray.parseArray(listjson.getString("datalist"));

        int suc = 0, fail = 0;
        double sucSkje = 0, failSkje = 0;
        Pattern pattern = Pattern.compile(PATTERN_JUDGE_DATE);
        Pattern pattern2 = Pattern.compile(PATTERN_JUDGE_AMOUNT);
        List<CustomsLog> logList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            CustomsInsertImpotVO vo = jsonObject.toJavaObject(CustomsInsertImpotVO.class);
            if (StringUtils.isBlank(vo.getSkje())) {
                fail++;
                continue;
            }
            Matcher match2 = pattern2.matcher(vo.getSkje());
            if (!match2.matches()) {
                fail++;
                continue;
            }
            if (list != null && list.size() > 0 && !list.contains(vo.getJkdwsh())) {
                vo.setCwts("不可操作此税号!");
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }
            if (StringUtils.isBlank(vo.getJkdwsh())) {
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }

            if (StringUtils.isBlank(vo.getJkshm())) {
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }
            if (StringUtils.isBlank(vo.getTfrq())) {
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }
            Matcher match = pattern.matcher(vo.getTfrq());
            if (!match.matches()) {
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }

            LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TdxCustomsRecord::getCustomsCode, vo.getJkshm());
            TdxCustomsRecord query = this.getOne(wrapper);
            if (query != null) {
                fail++;
                continue;
            }
            TdxCustomsRecord record = new TdxCustomsRecord();
            record.setPayerOneTaxno(vo.getJkdwsh());
            record.setPayerOneName(getGfmcByGfsh(vo.getJkdwsh(), userInfo.getOrg()));
            record.setYxTaxAmount(vo.getSkje());
            if (StringUtils.isBlank(vo.getSjly())) {
                record.setDataSources(DataSourceEnum.C.getKey());
            } else {
                record.setDataSources(DataSourceEnum.F.getKey());
            }
            record.setCreateDate(new Date());
            record.setDataType("17");
            record.setCollectUploadStatus(CollectUploadStatusEnum.A.getKey());
            record.setGlzt(GlztEnum.A.getKey());
            record.setApplyCheck(ApplyCheckEnum.A.getKey());
            record.setGfTaxNo(vo.getJkdwsh());
            record.setGfName(record.getPayerOneName());
            record.setCustomsCode(vo.getJkshm());
            record.setFillInDate(DateUtil.strToDate(vo.getTfrq()));
            record.setTaxAmount(vo.getSkje());
            record.setEntryDate(new Date());
            record.setEntryUser(userInfo.getUsername());
            record.setCompany(userInfo.getCompany());
            DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(pramsMap.get("dbName")), "business")
                + DbConstant.BUSINESS_WRITE);
            this.baseMapper.insert(record);
            suc++;
            sucSkje += Double.parseDouble(vo.getSkje());
            CustomsLog customsLog = new CustomsLog();
            customsLog.setCustomsCode(record.getCustomsCode());
            customsLog.setInputStatus("20");
            customsLog.setInputName(userInfo.getUsername());
            customsLog.setCreateDate(new Date());
            customsLog.setType("10");
            logList.add(customsLog);
        }
        String sucAmount = AmountFormatUtil
            .fmtMicrometer(new BigDecimal(sucSkje).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        String failAmount = AmountFormatUtil
            .fmtMicrometer(new BigDecimal(failSkje).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        if (logList.size() > 0) {
            customsLogService.toCustomsLog(logList);
        }
        return "录入成功" + suc + "条,税款金额:" + sucAmount + "，录入失败" + fail + "条,税款金额:" + failAmount;
    }

    /**
     * 异常教款书采集页面查看详情
     *
     * @param page
     *            page
     * @param entity
     *            entity
     * @param userInfo
     *            userInfo
     * @return java.lang.String
     * @author 陈刚扬
     * @date 2020/8/10
     */
    @Override
    public String exceptionDetail(Page<?> page, TdxCustomsRecordDTO entity, UserInfo userInfo) {
        DynamicContextHolder.push(userInfo.getDbName() + DbConstant.BUSINESS_READ);
        entity.setParam(page);
        Page<Map<String, String>> result = this.baseMapper.queryExcptionDetail(page, entity);

        if (ResultData.isEmpty(result)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            List<DictdetaModel> jhModels = dictdetaServcice.selectDictdeta("AUDIT_STATUS");
//            List<DictdetaModel> hcjgModels = dictdetaServcice.selectDictdeta("CHECK_STATUS");
//            List<DictdetaModel> glztModels = dictdetaServcice.selectDictdeta("GLZT");
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, String> map = result.getRecords().get(i);
                map.put("xh",
                    String.valueOf((((page.getCurrent() == 0 ? 1 : page.getCurrent()) - 1) * page.getSize()) + i + 1));
                map.put("taxAmount", AmountFormatUtil.fmtMicrometer(ObjectUtil.fixNull(map.get("taxAmount"))) );
                //字典转换
                map.put("auditStatus", dictdetaServcice.queryDictName(DictConstant.AUDIT_STATUS,map.get("auditStatus")));
                map.put("checkStatus", dictdetaServcice.queryDictName(DictConstant.CHECK_STATUS,map.get("checkStatus")));
                map.put("glzt", dictdetaServcice.queryDictName(DictConstant.GLZT,map.get("glzt")));

                if (map.get("fillInDate") != null) {
                    map.put("fillInDate", map.get("fillInDate"));
                }
                if (map.get("statusUpdateDate") != null) {
                    map.put("statusUpdateDate", map.get("statusUpdateDate"));
                }

            }
        }
        return RESULT_DATA.getPageData(result)
            .putTitleList(DicProp.CUSTOMS_EXCEPTION_QUERY_TITLE, DicProp.CUSTOMS_EXCEPTION_QUERY_PORP).toJsonBase();

    }

    @Override
    public String scanCollect(Map<String, Object> pramsMap) {
        String[] titlelist = {"序号", "错误提示", "缴款单位税号", "缴款书号码", "填发日期", "税款金额"};
        String[] titleprop = {"xh", "cwts", "jkdwsh", "jkshm", "tfrq", "skje"};
        DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(pramsMap.get("dbName")), "business")
            + DbConstant.BUSINESS_READ);
        // 需要设置返回列表标题时调用
        JSONObject json = super.setTitleList(titlelist, titleprop);

        List<Object> returnList = new ArrayList<>();

        String pch = (String)pramsMap.get("pch");
        String gfsh = (String)pramsMap.get("gfsh");
        List<TdxScanCustomsLog> scanCustomsLogs = scanLogDao.getScanLog(pch);
        if (scanCustomsLogs != null && scanCustomsLogs.size() > 0) {

            for (int i = 0; i < scanCustomsLogs.size(); i++) {
                TdxScanCustomsLog scanCustomsLog = scanCustomsLogs.get(i);
                CustomsInsertImpotVO vo = new CustomsInsertImpotVO();
                vo.setJkdwsh(gfsh);
                vo.setJkshm(scanCustomsLog.getCustomsCode());
                vo.setSkje(scanCustomsLog.getAmount());
                vo.setTfrq(DateUtils.dateToStr(scanCustomsLog.getFillInDate()));
                if (StringUtils.isBlank(scanCustomsLog.getCustomsCode())) {
                    vo.setCwts("缴款书号码不能为空");
                    returnList.add(vo);
                    continue;
                } else {
                    vo.setJkshm(vo.getJkshm().trim());
                }
                if (vo.getTfrq() == null) {
                    vo.setCwts("填发日期不能为空");
                    returnList.add(vo);
                    continue;
                } else {
                    vo.setTfrq(vo.getTfrq().trim());
                }

                if (StringUtils.isBlank(vo.getSkje())) {
                    vo.setCwts("税款金额不能为空");
                    returnList.add(vo);
                    continue;
                } else {
                    vo.setSkje(vo.getSkje().trim());
                }

                vo.setSkje(AmountFormatUtil
                    .fmtMicrometer(new BigDecimal(vo.getSkje()).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()));
                LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TdxCustomsRecord::getCustomsCode, vo.getJkshm());
                TdxCustomsRecord query = this.getOne(wrapper);
                if (query != null) {
                    vo.setCwts("已有缴款书信息!");
                    returnList.add(vo);
                    continue;
                }

                returnList.add(vo);
            }
        }
        json.put("datalist", returnList);
        return this.responseResult(json);
    }

    @Override
    public String scanCollectSubmit(Map<String, Object> pramsMap, UserInfo userInfo) {
        DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(pramsMap.get("dbName")), "business")
            + DbConstant.BUSINESS_READ);
        String datalist = (String)pramsMap.get("datalist");
        List<String> list = (List<String>)pramsMap.get("gfsh");
        JSONObject listjson = JSONObject.parseObject(datalist);
        // 首先把字符串转成 JSONArray 对象
        JSONArray jsonArray = JSONArray.parseArray(listjson.getString("datalist"));

        int suc = 0, fail = 0;
        double sucSkje = 0, failSkje = 0;
        Pattern pattern = Pattern.compile(PATTERN_JUDGE_DATE);
        Pattern pattern2 = Pattern.compile(PATTERN_JUDGE_AMOUNT);
        List<CustomsLog> logList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            CustomsInsertImpotVO vo = jsonObject.toJavaObject(CustomsInsertImpotVO.class);
            if (StringUtils.isBlank(vo.getSkje())) {
                fail++;
                continue;
            }
            Matcher match2 = pattern2.matcher(vo.getSkje());
            if (!match2.matches()) {
                fail++;
                continue;
            }
            if (list != null && list.size() > 0 && !list.contains(vo.getJkdwsh())) {
                vo.setCwts("不可操作此税号!");
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }
            if (StringUtils.isBlank(vo.getJkdwsh())) {
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }

            if (StringUtils.isBlank(vo.getJkshm())) {
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }
            if (StringUtils.isBlank(vo.getTfrq())) {
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }
            Matcher match = pattern.matcher(vo.getTfrq());
            if (!match.matches()) {
                fail++;
                failSkje += Double.parseDouble(vo.getSkje());
                continue;
            }

            LambdaQueryWrapper<TdxCustomsRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TdxCustomsRecord::getCustomsCode, vo.getJkshm());
            TdxCustomsRecord query = this.getOne(wrapper);
            if (query != null) {
                fail++;
                continue;
            }
            TdxCustomsRecord record = new TdxCustomsRecord();
            record.setPayerOneTaxno(vo.getJkdwsh());
            record.setPayerOneName(getGfmcByGfsh(vo.getJkdwsh(), userInfo.getOrg()));
            record.setYxTaxAmount(vo.getSkje());
            if (StringUtils.isBlank(vo.getSjly())) {
                record.setDataSources(DataSourceEnum.C.getKey());
            } else {
                record.setDataSources(DataSourceEnum.F.getKey());
            }
            record.setCreateDate(new Date());
            record.setDataType("17");
            record.setCollectUploadStatus(CollectUploadStatusEnum.A.getKey());
            record.setGlzt(GlztEnum.A.getKey());
            record.setApplyCheck(ApplyCheckEnum.A.getKey());
            record.setGfTaxNo(vo.getJkdwsh());
            record.setGfName(record.getPayerOneName());
            record.setCustomsCode(vo.getJkshm());
            record.setFillInDate(DateUtil.strToDate(vo.getTfrq()));
            record.setTaxAmount(vo.getSkje());
            record.setEntryDate(new Date());
            record.setEntryUser(userInfo.getUsername());
            record.setCompany(userInfo.getCompany());
            DynamicContextHolder.push(StringUtils.defaultString(ObjectUtil.fixNull(pramsMap.get("dbName")), "business")
                + DbConstant.BUSINESS_WRITE);
            this.baseMapper.insert(record);
            suc++;
            sucSkje += Double.parseDouble(vo.getSkje());
            CustomsLog customsLog = new CustomsLog();
            customsLog.setCustomsCode(record.getCustomsCode());
            customsLog.setInputStatus("20");
            customsLog.setInputName(userInfo.getUsername());
            customsLog.setCreateDate(new Date());
            customsLog.setType("10");
            logList.add(customsLog);
        }
        String sucAmount = AmountFormatUtil
            .fmtMicrometer(new BigDecimal(sucSkje).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        String failAmount = AmountFormatUtil
            .fmtMicrometer(new BigDecimal(failSkje).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        if (logList.size() > 0) {
            customsLogService.toCustomsLog(logList);
        }
        return "录入成功" + suc + "条,税款金额:" + sucAmount + "，录入失败" + fail + "条,税款金额:" + failAmount;
    }
}
