package com.jianshui.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.jianshui.common.constant.InvoiceCommonConstants;
import com.jianshui.common.constant.WebServiceConstant;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.core.domain.entity.SysUser;
import com.jianshui.common.utils.SecurityUtils;
import com.jianshui.common.utils.jcsk.ApiHttp;
import com.jianshui.invoice.domain.Invoice;
import com.jianshui.invoice.domain.dto.HXResponse;
import com.jianshui.invoice.domain.dto.api.elephant.FileAcquisitionTwoDTO;
import com.jianshui.invoice.mapper.InvoiceMapper;
import com.jianshui.platform.dto.DownLoadDTO;
import com.jianshui.platform.service.InvoiceDownloadService;
import com.jianshui.platform.utils.BatchDownloadUtils;
import com.jianshui.platform.utils.InvoiceAllYhdjUtils;
import com.jianshui.platform.vo.DownLoadErrorVO;
import com.jianshui.system.domain.InvoiceAllYhdj;
import com.jianshui.system.mapper.CompanyserviceMapper;
import com.jianshui.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: kane
 * @Description: 发票下载业务层
 * @CreateTime: 2023-06-08  14:36
 * @Version: 1.0
 **/
@Service
@Slf4j
public class InvoiceDownloadServiceImpl implements InvoiceDownloadService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private CompanyserviceMapper companyServiceMapper;

    @Autowired
    private InvoiceMapper invoiceMapper;

    /**
     * 功能描述: 发票（pfd版）下载
     * @param ids
     * @param response
     * @return : java.lang.Object
     */
    @Override
    public Object dowmLoadPdf(Long[] ids, HttpServletResponse response) {
        //判空
        if (ids == null) {
            return AjaxResult.error(InvoiceCommonConstants.INVOICEINFORMATIONISEMPTY);
        }
        //获取用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id获取用户信息
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        //根据企业id获取企业信息
        Companyservice companyservice = companyServiceMapper.selectCompanyserviceByCompanyid(sysUser.getCompanyId());
        if (companyservice == null){
            return AjaxResult.error(InvoiceCommonConstants.NOTCOMPANYINFO);
        }
        //获取登记用户信息
        InvoiceAllYhdjUtils invoiceAllYhdjUtils = new InvoiceAllYhdjUtils();
        InvoiceAllYhdj userInfo = invoiceAllYhdjUtils.getUserInfo(companyservice);
        if (BeanUtil.isEmpty(userInfo)) {
            return AjaxResult.error(InvoiceCommonConstants.NOINFORMATIONISFOUND);
        }
        //pfd文件集合
        List<DownLoadDTO> pdfDownLoad = new ArrayList<>();
        //下载失败集合
        List<DownLoadErrorVO> errorList = new ArrayList<>();
        for (Long id : ids) {
            //下载传输类
            DownLoadDTO downLoadDTO = new DownLoadDTO();
            //发票实体类
            Invoice invoice = invoiceMapper.selectInvoiceById(id);
            //判断有无该发票
            if (invoice == null){
                return AjaxResult.error(InvoiceCommonConstants.NOTINVOICEINFO);
            }
            //获取发票pdf地址
            String invoicePdfUrl = invoice.getInvoicePdfUrl();
            if (invoicePdfUrl != null) {
                //设置下载地址类
                downLoadDTO.setUrl(invoicePdfUrl);
                downLoadDTO.setFphm(invoice.getFphm());
                pdfDownLoad.add(downLoadDTO);
            } else {
                //封装请求实体类
                FileAcquisitionTwoDTO fileAcquisitionDTO = new FileAcquisitionTwoDTO();
                //发送同步请求
                fileAcquisitionDTO.setAsync(InvoiceCommonConstants.SYNC);
                fileAcquisitionDTO.setNsrsbh(userInfo.getNsrsbh());
                fileAcquisitionDTO.setBsrysfzjhm(userInfo.getBsrysfzjhm());
                fileAcquisitionDTO.setDqbm(userInfo.getDqbm());
                Map<String, Object> map = new JSONObject();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(InvoiceCommonConstants.DATEFORMAT);
                map.put(InvoiceCommonConstants.FPHM, invoice.getFphm());
                Date kprq = invoice.getKprq();
                //修改日期格式（请求接口要求）
                String kprqFormat = simpleDateFormat.format(kprq);
                map.put(InvoiceCommonConstants.KPRQ, kprqFormat);
                fileAcquisitionDTO.setJsonData(map);
                //下载失败信息类
                DownLoadErrorVO downLoadErrorVO = new DownLoadErrorVO();
                cn.hutool.json.JSONObject result = null;
                try {
                    result = ApiHttp.request(WebServiceConstant.FPEWMXZ, WebServiceConstant.URL, fileAcquisitionDTO, companyservice);
                    String code = result.get(InvoiceCommonConstants.CODE) != null ? result.get(InvoiceCommonConstants.CODE).toString() : "";
                    String msg = result.get(InvoiceCommonConstants.MSG) != null ? result.get(InvoiceCommonConstants.MSG).toString() : "";
                    String data = result.get(InvoiceCommonConstants.DATA) != null ? result.get(InvoiceCommonConstants.DATA).toString() : "";
                    if (InvoiceCommonConstants.SUCCESSCODE.equals(code) && StrUtil.isNotEmpty(data)) {
                        cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                        String pdfUrl = json.get(InvoiceCommonConstants.PDFURL) != null ? json.get(InvoiceCommonConstants.PDFURL).toString() : "";
                        downLoadDTO.setFphm(invoice.getFphm());
                        downLoadDTO.setUrl(pdfUrl);
                        pdfDownLoad.add(downLoadDTO);
                    } else {
                        //设置错误信息
                        downLoadErrorVO.setFphm(invoice.getFphm());
                        downLoadErrorVO.setMsg(msg);
                        errorList.add(downLoadErrorVO);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("【金四服务类】【获取发票下载地址】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
                    //设置错误信息
                    downLoadErrorVO.setFphm(invoice.getFphm());
                    downLoadErrorVO.setMsg(e.getMessage());
                    errorList.add(downLoadErrorVO);
                }
            }
        }
        if (errorList.size() > 0){
            //下载pdf文件集合
            BatchDownloadUtils.downloadAndZipFiles(pdfDownLoad,InvoiceCommonConstants.PDFSTATUS,response);
            return AjaxResult.error(errorList);
        }else {
            //下载pdf文件集合;
            BatchDownloadUtils.downloadAndZipFiles(pdfDownLoad,InvoiceCommonConstants.PDFSTATUS,response);
            return AjaxResult.success(InvoiceCommonConstants.DOWNLOADSUCCESSCODE);
        }
    }

    /**
     * 功能描述: 发票（ofd版）下载
     * @param ids
     * @param response
     * @return : java.lang.Object
     */
    @Override
    public Object dowmLoadOfd(Long[] ids, HttpServletResponse response) {
        //判空
        if (ids == null) {
            return AjaxResult.error(InvoiceCommonConstants.INVOICEINFORMATIONISEMPTY);
        }
        //获取用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id获取用户信息
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        //根据企业id获取企业信息
        Companyservice companyservice = companyServiceMapper.selectCompanyserviceByCompanyid(sysUser.getCompanyId());
        if (companyservice == null){
            return AjaxResult.error(InvoiceCommonConstants.NOTCOMPANYINFO);
        }
        //获取登记用户信息
        InvoiceAllYhdjUtils invoiceAllYhdjUtils = new InvoiceAllYhdjUtils();
        InvoiceAllYhdj userInfo = invoiceAllYhdjUtils.getUserInfo(companyservice);
        if (BeanUtil.isEmpty(userInfo)) {
            return new HXResponse(InvoiceCommonConstants.NOINFORMATIONISFOUND);
        }
        //ofd文件集合
        List<DownLoadDTO> ofdDownLoad = new ArrayList<>();
        //下载失败集合
        List<DownLoadErrorVO> errorList = new ArrayList<>();
        for (Long id : ids) {
            Invoice invoice = invoiceMapper.selectInvoiceById(id);
            DownLoadDTO downLoadDTO = new DownLoadDTO();
            if (invoice == null){
                return AjaxResult.error(InvoiceCommonConstants.NOTINVOICEINFO);
            }
            String invoiceOfdUrl = invoice.getcOfdUrl();
            if (invoiceOfdUrl != null) {
                downLoadDTO.setUrl(invoiceOfdUrl);
                downLoadDTO.setFphm(invoice.getFphm());
                ofdDownLoad.add(downLoadDTO);
            } else {
                //获取ofd下载地址
                //封装请求实体类
                FileAcquisitionTwoDTO fileAcquisitionDTO = new FileAcquisitionTwoDTO();
                //发送同步请求
                fileAcquisitionDTO.setAsync(InvoiceCommonConstants.SYNC);
                fileAcquisitionDTO.setNsrsbh(userInfo.getNsrsbh());
                fileAcquisitionDTO.setBsrysfzjhm(userInfo.getBsrysfzjhm());
                fileAcquisitionDTO.setDqbm(userInfo.getDqbm());
                Map<String, Object> map = new JSONObject();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(InvoiceCommonConstants.DATEFORMAT);
                map.put(InvoiceCommonConstants.FPHM, invoice.getFphm());
                Date kprq = invoice.getKprq();
                //修改日期格式（请求接口要求）
                String kprqFormat = simpleDateFormat.format(kprq);
                map.put(InvoiceCommonConstants.KPRQ, kprqFormat);
                fileAcquisitionDTO.setJsonData(map);
                //下载失败信息类
                DownLoadErrorVO downLoadErrorVO = new DownLoadErrorVO();
                cn.hutool.json.JSONObject result = null;
                try {
                    result = ApiHttp.request(WebServiceConstant.FPEWMXZ, WebServiceConstant.URL, fileAcquisitionDTO, companyservice);
                    String code = result.get(InvoiceCommonConstants.CODE) != null ? result.get(InvoiceCommonConstants.CODE).toString() : "";
                    String msg = result.get(InvoiceCommonConstants.MSG) != null ? result.get(InvoiceCommonConstants.MSG).toString() : "";
                    String data = result.get(InvoiceCommonConstants.DATA) != null ? result.get(InvoiceCommonConstants.DATA).toString() : "";
                    if (InvoiceCommonConstants.SUCCESSCODE.equals(code) && StrUtil.isNotEmpty(data)) {
                        cn.hutool.json.JSONObject json = JSONUtil.parseObj(data);
                        String ofdUrl = json.get(InvoiceCommonConstants.OFDURL) != null ? json.get(InvoiceCommonConstants.OFDURL).toString() : "";
                        downLoadDTO.setFphm(invoice.getFphm());
                        downLoadDTO.setUrl(ofdUrl);
                        ofdDownLoad.add(downLoadDTO);
                    } else {
                        //设置错误信息
                        downLoadErrorVO.setFphm(invoice.getFphm());
                        downLoadErrorVO.setMsg(msg);
                        errorList.add(downLoadErrorVO);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("【金四服务类】【获取发票下载地址】API请求异常，外部报文返回code非0000。错误信息:{}", e.getMessage());
                    //设置错误信息
                    downLoadErrorVO.setFphm(invoice.getFphm());
                    downLoadErrorVO.setMsg(e.getMessage());
                    errorList.add(downLoadErrorVO);
                }
            }
        }
        if (errorList.size() > 0){
            //下载ofd文件集合
            BatchDownloadUtils.downloadAndZipFiles(ofdDownLoad,InvoiceCommonConstants.OFDSTATUS,response);
            return AjaxResult.error(errorList);
        }else {
            //下载ofd文件集合
            BatchDownloadUtils.downloadAndZipFiles(ofdDownLoad,InvoiceCommonConstants.OFDSTATUS,response);
            return AjaxResult.success(InvoiceCommonConstants.DOWNLOADSUCCESSCODE);
        }
    }


}
