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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.api.model.config.Business;
import com.dxhy.api.model.config.Tax;
import com.dxhy.base.dao.BaseTDxRecordInvoiceDao;
import com.dxhy.base.entity.BaseTDxDkCount;
import com.dxhy.base.entity.BaseTDxRecordInvoice;
import com.dxhy.base.model.BaseSggxCxRespVO;
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.JsonUtils;
import com.dxhy.common.util.MathUtil;
import com.dxhy.common.util.StringHelper;
import com.dxhy.core.model.FpRzRespVO;
import com.dxhy.core.service.export.RzFpsgrzService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

/**
 * 发票手工认证
 *
 * @author user
 */
@SuppressWarnings({"AlibabaMethodTooLong", "DuplicatedCode"})
@Service("rzFpsgrzService")
@Slf4j

public class RzFpsgrzServiceImpl extends MpBaseServiceImpl<BaseTDxRecordInvoiceDao, BaseTDxRecordInvoice> implements RzFpsgrzService {
    @Resource
    private DictdetaServcice dictdetaServcice;

    @Override
    public JSONObject selectByPramsMap(Map<String, Object> pramsMap, int curr, int size) {
        DynamicContextHolder.push(pramsMap.get("dbName") + DbConstant.BUSINESS_READ);
        JSONObject json = new JSONObject();
        try {
            List<BaseSggxCxRespVO> voList = new ArrayList<>();
            List<String> gfshList = (List<String>)pramsMap.get("gfsh");
            String qsflag = (String)pramsMap.get("qsflag");
            List<String> gfshList1 = new ArrayList<>();
            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<FpRzRespVO>());
            } else {
                List<BaseTDxDkCount> curList = super.baseMapper.selectDksh(pramsMap);
                for (BaseTDxDkCount cur : curList) {
                    String skssq = cur.getSkssq();
                    String year = skssq.substring(0, 4);
                    String mon = skssq.substring(4);
                    LocalDate localDate = LocalDate.of(Integer.parseInt(year), Integer.parseInt(mon), 1);
                    LocalDate localDate1 = localDate.plusMonths(1);
                    LocalDate localDate2 = LocalDate.now();
                    if ("0".equals(cur.getTjStatus()) || "3".equals(cur.getTjStatus())
                            || localDate2.isBefore(localDate1)) {
                        gfshList1.add(cur.getTaxno());
                    }
                }


                List<BaseTDxRecordInvoice> pageList = super.baseMapper.selectSggxcx(pramsMap);
                PageInfo<BaseTDxRecordInvoice> pageInfo = new PageInfo<>(pageList);

                // 转化为页面展示对象
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (pageList.size() > 0) {
                    List<Tax> taxList = (List<Tax>)pramsMap.get("taxList");
                    List<String> taxnoList = new ArrayList<>();
                    if (taxList != null && taxList.size() > 0) {
                        for (Tax tax : taxList) {
                            String upgradeStatus = tax.getUpgradeStatus();
                            if ("1".equals(upgradeStatus)) {
                                taxnoList.add(tax.getTaxno());
                            }
                        }
                    }
//                    List<Business> businessList = (List<Business>)pramsMap.get("business");
                    List<Business> businessList = JsonUtils.getInstance().jsonToList(JsonUtils.getInstance().toJsonString(pramsMap.get("business")), Business.class);
                    int start = new Long(pageInfo.getStartRow()).intValue();
                    for (int i = 0; i < pageList.size(); i++) {
                        BaseSggxCxRespVO vo = new BaseSggxCxRespVO();
                        if (taxnoList.contains(pageList.get(i).getGfTaxNo())) {
                            vo.setUpgradeStatus("1");
                            if (pageList.get(i).getDkTaxAmount() != null) {
                                vo.setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getDkTaxAmount().toString())));
                            } else {
                                if(ObjectUtil.isNotEmpty(pageList.get(i).getTaxAmount())){
                                    vo.setDkse(AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount().toString())));
                                }
                            }
                        } else {
                            vo.setUpgradeStatus("0");
                            if (pageList.get(i).getDkTaxAmount() != null) {
                                vo.setDkse(AmountFormatUtil
                                        .fmtMicrometer(MathUtil.round(pageList.get(i).getDkTaxAmount().toString())));
                            } else {
                                if(ObjectUtil.isNotEmpty(pageList.get(i).getTaxAmount())){
                                    vo.setDkse(AmountFormatUtil
                                            .fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount().toString())));
                                }

                            }
                        }
                        String businessCode = pageList.get(i).getDeptId();
                        String businessName = this.getBusinessName(businessCode, businessList);

                        vo.setVoucherNumber(pageList.get(i).getVoucherNumber());
                        vo.setId(String.valueOf(pageList.get(i).getId()));
                        vo.setXh(String.valueOf(i + 1));
                        if(ObjectUtil.isNotEmpty(pageList.get(i).getInvoiceAmount())){
                            vo.setInvoiceAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getInvoiceAmount().toString())));
                        }
                        vo.setInvoiceCode(pageList.get(i).getInvoiceCode());
                        vo.setInvoiceDate(sdf.format(pageList.get(i).getInvoiceDate()));
                        vo.setInvoiceNo(pageList.get(i).getInvoiceNo());
                        vo.setSettlementNo(pageList.get(i).getSettlementNo());
                        if(ObjectUtil.isNotEmpty(pageList.get(i).getTaxAmount())){
                            vo.setTaxAmount(
                                    AmountFormatUtil.fmtMicrometer(MathUtil.round(pageList.get(i).getTaxAmount().toString())));
                        }
                        vo.setInvoiceStatus(dictdetaServcice.queryDictName(DictConstant.INVOICE_STATUS,pageList.get(i).getInvoiceStatus()));
                        vo.setInvoiceType(dictdetaServcice.queryDictName(DictConstant.INVOICE_TYPEALL, pageList.get(i).getInvoiceType()) );
                        // 签收方式为已经签收时展示签收信息
                        if ("1".equals(pageList.get(i).getQsStatus())) {
                            if (pageList.get(i).getQsDate() != null) {
                                vo.setQsrq(sdf.format(pageList.get(i).getQsDate()));
                            }
                            if (pageList.get(i).getQsType() != null) {
                                vo.setQsfs(dictdetaServcice.queryDictName(DictConstant.QS_TYPE,pageList.get(i).getQsType()));
                            }
                            vo.setQsr(pageList.get(i).getQsName());
                        }
                        if (pageList.get(i).getQsStatus() != null) {
                            vo.setQszt(dictdetaServcice.queryDictName(DictConstant.QS_STATUS,pageList.get(i).getQsStatus()));
                        }
//                    if ("1".equals(pageList.get(i).getPaymentStatus())) {
//                        vo.setPaymentStatus("已付款");
//                    } else if ("0".equals(pageList.get(i).getPaymentStatus())) {
//                        vo.setPaymentStatus("未付款");
//                    }
                        vo.setPaymentStatus(dictdetaServcice.queryDictName(DictConstant.FK_STATUS,pageList.get(i).getPaymentStatus()));
                        vo.setPaymentDate(pageList.get(i).getPaymentDate());
                        vo.setGfmc(pageList.get(i).getGfName());
                        vo.setXfmc(pageList.get(i).getXfName());
                        vo.setBusinessName(businessName);
                        vo.setEleInvoiceNo(pageList.get(i).getEleInvoiceNo());
                        String dkzt= dictdetaServcice.queryDictName(DictConstant.DK_STATUS,pageList.get(i).getInAccountStatus());
                        pageList.get(i).setInAccountStatus(dkzt);
                        vo.setInAccountStatus(dkzt);
                        vo.setSelect(true);
                        LinkedHashSet<String> bkgxtsList = new LinkedHashSet<>();
                        if (!"1".equals(pageList.get(i).getAuthStatus())) {
                            bkgxtsList.add("非已勾选未确认");
                            vo.setSelect(false);
                        }
                        String invoiceStatus="07";
                        if ( !invoiceStatus.contains(pageList.get(i).getInvoiceStatus())) {
                            bkgxtsList.add("发票状态异常");
                            vo.setSelect(false);
                            vo.setUpgradeStatus("0");
                        }
                        if(ObjectUtil.isNotEmpty(pageList.get(i).getInvoiceAmount())&&pageList.get(i).getInvoiceAmount().compareTo(new BigDecimal(0)) < 0){
                            bkgxtsList.add("负数发票");
                            vo.setSelect(false);
                            vo.setUpgradeStatus("0");
                        }
                        if(ObjectUtil.isNotEmpty(pageList.get(i).getTaxAmount())&&pageList.get(i).getTaxAmount().compareTo(new BigDecimal(0)) < 0){
                            bkgxtsList.add("负数发票");
                            vo.setSelect(false);
                            vo.setUpgradeStatus("0");
                        }

                        if (!gfshList1.contains(pageList.get(i).getGfTaxNo())) {
                            vo.setSelect(false);
                            bkgxtsList.add("当前属期已统计");
                        }
                        if ("1".equals(qsflag) && !"1".equals(pageList.get(i).getQsStatus())) {
                            vo.setSelect(false);
                            bkgxtsList.add("该发票未签收");
                        }
                        if(bkgxtsList.size()>0){
                            vo.setBkgxts(String.join("，", bkgxtsList));
                        }
                        voList.add(vo);
                    }
                }
                json.put("datalist", voList);
            }
        } catch (Exception e) {
            // 统一设置操作异常标识
            json = super.errorResult(e);
        }

        return json;
    }

    /**
     * 根据businessCode获取对应名称用于页面显示
     *
     * @param businessCode
     *            业务单元
     * @param businessList
     *            业务单元list
     * @return 返回
     *
     */
    private String getBusinessName(String businessCode, List<Business> businessList) {
        String businessName = "";
        if (!StringHelper.isBlank(businessCode) && businessList != null && businessList.size() > 0) {
            for (Business business : businessList) {
                if (!StringHelper.isBlank(business.getBusinessCode())
                        && business.getBusinessCode().equals(businessCode)) {
                    businessName = StringHelper.trim(business.getBusinessName(), "");
                    break;
                }
            }
        }
        return businessName;
    }

}
