package com.dxhy.erp.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.erp.dao.InvoiceImgDao;
import com.dxhy.erp.dao.SysDeptDao;
import com.dxhy.erp.entity.InvoiceImgQueryVo;
import com.dxhy.erp.entity.SysDeptEntity;
import com.dxhy.erp.service.ElectronService;
import com.dxhy.erp.utils.ZipUtils;
import com.dxhy.oss.model.FileModel;
import com.dxhy.oss.service.FileService;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author dxhy
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Controller
@RequestMapping("/elector")
@Slf4j
public class ElectronController {

    @Resource
    private ElectronService electronService;

    @Value("${pro.yl.gfTaxNo}")
    private String yLgfTaxNo;

    @Resource
    private InvoiceImgDao imgDao;

    @Resource
    private SysDeptDao sysDeptDao;
    @Resource
    private FileService fileService;

    @ResponseBody
    @RequestMapping(value = "/uploadinvoice")
    public Map getById(String key) {

        Map<String, Object> returnMap = new HashMap<>(16);
        Map<String, String> map = new HashMap<>(16);
        log.info("加密报文：{}", key);

        if (StringUtils.isNotBlank(key)) {
            Map<String, String> resMap = JSONObject.parseObject(Base64.decodeStr(key), Map.class);
            String text = resMap.get("text");
            log.info("文件参数：{} ", text);
            if (StringUtils.isBlank(text) || (!"pdf".equals(text) && !"ofd".equals(text))) {
                map.put("returnCode", "9999");
                map.put("returnMessage", "文件类型参数有误");
                map.put("request_id", resMap.get("request_id"));
                return map;
            }
            // else if (!"pdf".equals(text) && !"ofd".equals(text)) {
            // map.put("returnCode", "9999");
            // map.put("returnMessage", "文件类型参数有误");
            // map.put("request_id", resMap.get("request_id"));
            // return map;
            // }
            if (StringUtils.isBlank(resMap.get("pdf"))) {
                map.put("returnCode", "9999");
                map.put("returnMessage", "文件流为空");
                map.put("request_id", resMap.get("request_id"));
                return map;
            }
            // 解析Base64Encoding
            try {
                map = electronService.electronEvent(key);
            } catch (Exception e) {
                map.put("returnCode", "9999");
                map.put("returnMessage", "处理失败");
                map.put("request_id", "");
                e.printStackTrace();
            }
        } else {
            map.put("returnCode", "9999");
            map.put("returnMessage", "参数为空");
            map.put("request_id", "");
        }
        returnMap.put("responseStatus", map);
        return returnMap;

    }

    @ResponseBody
    @RequestMapping(value = "/downloaninvoice")
    public List<Map<String, String>> downloaninvoice(String key) {
        List<Map<String, String>> mapList = new ArrayList<>();
        Map<String, Object> requestMap = new HashMap<>(16);
        if (StringUtils.isNotBlank(key)) {
            // 解析Base64Encoding
            try {
                requestMap = JSONObject.parseObject(Base64.decodeStr(key), Map.class);
            } catch (Exception e) {
                requestMap.put("returnCode", "9999");
                requestMap.put("returnMessage", "查验失败， 请稍后重试");
                e.printStackTrace();
            }
            mapList = electronService.getScanMsg(requestMap);
        }
        return mapList;
    }

    @RequestMapping("getpdf")
    public void getImg(String scanId, HttpServletResponse response) {

        InvoiceImgQueryVo img;
        String downLondFile = "";
        try {
            DynamicContextHolder.push(DbConstant.BASICS_READ);
            SysDeptEntity deptEntity = sysDeptDao.getOrg(yLgfTaxNo);
            String dbName = null;
            if (deptEntity != null && deptEntity.getDbName() != null) {
                dbName = deptEntity.getDbName();
            }
            DynamicContextHolder.push(dbName + DbConstant.BUSINESS_READ);
            img = this.imgDao.getImg(scanId);

            if (null != img) {
                String[] fileAccount = null;
                if (img.getImagePath() != null) {
                    fileAccount = img.getImagePath().split("/");
                }
                String name = fileAccount[fileAccount.length - 1];
                downLondFile =
                    fileService.getLocalPathDefault() + "img/" + new SimpleDateFormat("yyyyMMdd").format(new Date())
                        + "/" + new File(img.getImagePath()).getName();
                FileModel fileModel = fileService.downFile(img.getImagePath(), downLondFile);
                byte[] zipFile;

                if (name.contains(".zip")) {
                    zipFile = ZipUtils.readZipFile(fileModel.getFilePath());
                } else {

                    zipFile = ZipUtils.readInputStream(new FileInputStream(fileModel.getFilePath()));
                }
                // 从网盘下载照片的流
                InputStream in = new ByteArrayInputStream(zipFile);

                // 声明输出流，但是要从HttpServletResponse中获取才管用
                BufferedOutputStream bout = new BufferedOutputStream(response.getOutputStream());
                // 从输入流到输出流
                byte[] b = new byte[1024];
                int len = in.read(b);
                while (len > 0) {
                    bout.write(b, 0, len);
                    len = in.read(b);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (StringUtils.isNotBlank(downLondFile)) {
                    String path = new File(downLondFile).getParent();
                    FileUtil.del(new File(path));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
