package com.dxhy.core.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.dxhy.core.dao.ExtMessageControlDao;
import com.dxhy.core.entity.ExtSysMessagecontrolVo;
import com.dxhy.core.feign.IFeginWebsocket;
import com.dxhy.core.service.ExtMessageControlService;
import com.dxhy.core.service.export.IExcelExportService;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.CommonConstants;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.util.StringHelper;
import com.dxhy.common.util.UserInfoUtil;
import com.dxhy.common.utils.R;
import com.dxhy.common.vo.Tax;
import com.dxhy.core.entity.TDxExcelExportlog;
import com.dxhy.core.rabbitmq.Sender;
import com.dxhy.core.service.singletable.IExcelExportlogService;

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

/**
 * excel服务接口
 *
 * @author jiaohongyang
 */
@SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaMethodTooLong", "DuplicatedCode"})
@RestController
@RequestMapping("excel")
@Slf4j

public class ExcelController extends AbstractController {

    @Resource
    private IExcelExportlogService exportlogService;

    @Resource
    private IExcelExportService excelExportService;

    @Resource
    private ExtMessageControlService messageControlService;

    @Resource
    private ExtMessageControlDao extMessageControlDao;

    @Resource
    private Sender sender;

    /**
     * excel导出申请接口
     *
     * @return 返回
     *
     */
    @PostMapping("/apply")
    @ResponseBody
    public ResponseEntity<?> excelExportApply(@RequestBody Map<String, Object> map) {
        String serviceType = String.valueOf(map.get("serviceType"));
        String condition = JSON.toJSONString(map.get("condition"));
        // 入参统一在入口处理
        Map<String, Object> pramsMap = new HashMap<>(16);
        pramsMap.put("userAccount", getUserId());
        pramsMap.put("userId", getUserId());
        pramsMap.put("userName", getUserName());
        pramsMap.put("loginName", getLoginName());
        pramsMap.put("dbName", getUserInfo().getDbName());
        pramsMap.put("gfTaxNo", StringHelper.listToString(UserInfoUtil.getGfshAll(getUserInfo().getOrg())));

        if (StringUtils.isNotBlank(serviceType)) {
            pramsMap.put("serviceType", serviceType);
        } else {
            return ResponseEntity.ok(R.error("业务类型不能为空！"));
        }
        if (StringUtils.isNotBlank(condition)) {
            JSONObject prams = JSONObject.parseObject(condition);
            String gfsh = prams.getString("gfsh");
            prams.put("business", getUserInfo().getBusiness());
            // 非查验综合查询、查验明细导出处理
            if (!"30".equals(serviceType) && !"29".equals(serviceType)) {

                // 判断购方税号是否为全部
                if ("99".equals(gfsh)) {
                    StringBuffer newGfsh = new StringBuffer();
                    List<Tax> list = getUserInfo().getOrg();
                    for (int i = 0; i < list.size(); i++) {
                        Tax tax = list.get(i);
                        if (i == list.size() - 1) {
                            newGfsh.append(tax.getTaxno());
                        } else {
                            newGfsh.append(tax.getTaxno()).append(",");
                        }
                    }
                    prams.put("gfsh", newGfsh);
                    prams.put("gfshFlag", "99");
                    String newCondition = prams.toString();
                    pramsMap.put("conditions", newCondition);
                } else if ("".equals(gfsh) || gfsh == null) {
                    StringBuffer newGfsh = new StringBuffer();
                    List<Tax> list = getUserInfo().getOrg();
                    for (int i = 0; i < list.size(); i++) {
                        Tax tax = list.get(i);
                        if (i == list.size() - 1) {
                            newGfsh.append(tax.getTaxno());
                        } else {
                            newGfsh.append(tax.getTaxno()).append(",");
                        }
                    }
                    prams.put("gfsh", newGfsh);
                    String newCondition = prams.toString();
                    pramsMap.put("conditions", newCondition);
                } else {
                    String gfmc = "";
                    List<Tax> org = getUserInfo().getOrg();
                    if (org != null && org.size() > 0) {
                        for (Tax tax : org) {
                            if (tax.getTaxno().equals(gfsh)) {
                                gfmc = tax.getTaxname();
                            }
                        }
                    }
                    prams.put("gfmc", gfmc);
                    String newCondition = prams.toString();
                    pramsMap.put("conditions", newCondition);
                }
            } else {
                pramsMap.put("conditions", condition);
            }
        } else {
            return ResponseEntity.ok(R.error("导出条件不能为空！"));
        }

        log.debug("pramsMap-" + pramsMap);
        try {
            // 保存导出日志记录
            TDxExcelExportlog tdxExcelExprortlog = exportlogService.excelExportApply(pramsMap);
            pramsMap.put("id", tdxExcelExprortlog.getId());
            pramsMap.put("createDate", new Date());
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(pramsMap));
            String json = responseResult(jsonObject);
            // 启动mq发送导出文件请求
            sender.sendToExcel(json);
            return ResponseEntity.ok(R.ok().put("data", "申请导出成功，请在消息列表中下载导出文件。"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    /**
     * excel导出申请接口
     *
     * @return 返回
     *
     */
    @PostMapping("/applyForSDNY")
    @ResponseBody
    public ResponseEntity<?> excelExportApplyForSDNY(@RequestBody Map<String, Object> map) {
        String serviceType = String.valueOf(map.get("serviceType"));
        String condition = JSON.toJSONString(map.get("condition"));
        // 入参统一在入口处理
        Map<String, Object> pramsMap = new HashMap<>(16);
        pramsMap.put("userAccount", getUserId());
        pramsMap.put("userId", getUserId());
        pramsMap.put("userName", getUserName());
        pramsMap.put("loginName", getLoginName());
        pramsMap.put("dbName", getUserInfo().getDbName());
        pramsMap.put("gfTaxNo", StringHelper.listToString(UserInfoUtil.getGfshAll(getUserInfo().getOrg())));

        if (StringUtils.isNotBlank(serviceType)) {
            pramsMap.put("serviceType", serviceType);
        } else {
            return ResponseEntity.ok(R.error("业务类型不能为空！"));
        }
        if (StringUtils.isNotBlank(condition)) {
            JSONObject prams = JSONObject.parseObject(condition);
            String gfsh = prams.getString("gfsh");
            prams.put("business", getUserInfo().getBusiness());
            // 非查验综合查询、查验明细导出处理
            if (!"30".equals(serviceType) && !"29".equals(serviceType)) {

//                String companyCode = prams.getString("companyCode");
//                if (StringHelper.isNotBlank(companyCode) && "99".equals(companyCode)){
//                    pramsMap.put("companyCodes",getUserInfo().getCompanyCodes());
//                    log.info("组织机构====>{}",pramsMap.get("companyCodes"));
//                }
                prams.put("companyCodes",getUserInfo().getCompanyCodes());

                // 判断购方税号是否为全部
                if ("99".equals(gfsh)) {
                    StringBuffer newGfsh = new StringBuffer();
                    List<Tax> list = getUserInfo().getOrg();
                    for (int i = 0; i < list.size(); i++) {
                        Tax tax = list.get(i);
                        if (i == list.size() - 1) {
                            newGfsh.append(tax.getTaxno());
                        } else {
                            newGfsh.append(tax.getTaxno()).append(",");
                        }
                    }
                    prams.put("gfsh", newGfsh);
                    prams.put("gfshFlag", "99");
                    String newCondition = prams.toString();
                    pramsMap.put("conditions", newCondition);
                } else if ("".equals(gfsh) || gfsh == null) {
                    StringBuffer newGfsh = new StringBuffer();
                    List<Tax> list = getUserInfo().getOrg();
                    for (int i = 0; i < list.size(); i++) {
                        Tax tax = list.get(i);
                        if (i == list.size() - 1) {
                            newGfsh.append(tax.getTaxno());
                        } else {
                            newGfsh.append(tax.getTaxno()).append(",");
                        }
                    }
                    prams.put("gfsh", newGfsh);
                    String newCondition = prams.toString();
                    pramsMap.put("conditions", newCondition);
                } else {
                    String gfmc = "";
                    List<Tax> org = getUserInfo().getOrg();
                    if (org != null && org.size() > 0) {
                        for (Tax tax : org) {
                            if (tax.getTaxno().equals(gfsh)) {
                                gfmc = tax.getTaxname();
                            }
                        }
                    }
                    prams.put("gfmc", gfmc);
                    String newCondition = prams.toString();
                    pramsMap.put("conditions", newCondition);
                }
            } else {
                pramsMap.put("conditions", condition);
            }
        } else {
            return ResponseEntity.ok(R.error("导出条件不能为空！"));
        }

        log.debug("pramsMap-" + pramsMap);

        try {
            // 保存导出日志记录
            TDxExcelExportlog tdxExcelExprortlog = exportlogService.excelExportApply(pramsMap);
            Long id = tdxExcelExprortlog.getId();
            pramsMap.put("id", id);
            pramsMap.put("createDate", new Date());
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(pramsMap));
//            String json = responseResult(jsonObject);
            // 启动mq发送导出文件请求
//            sender.sendToExcel(json);

            excelExportService.exportExcel(jsonObject.toJSONString());
            waitResult(id);

            Map<String, Object> returnMap = new HashMap<>(2);
            returnMap.put("id",tdxExcelExprortlog.getId());
            if("64".equals(serviceType)){
                returnMap.put("serviceType","2");
                returnMap.put("isPdf","1");
            }else{
                returnMap.put("serviceType","2");
            }

            return ResponseEntity.ok(R.ok().put("data", returnMap));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("", e);
            return ResponseEntity.ok(R.error(CommonConstants.MSG_ERR_DEFAULT));
        }
    }

    private void waitResult(Long id) throws InterruptedException {
        for(int i = 0;i<200;i++) {
            TDxExcelExportlog tDxExcelExportlog = exportlogService.selectById(id);
            if(tDxExcelExportlog != null) {
                String filepath = tDxExcelExportlog.getFilepath();
                log.info("filepath={}",filepath);
                if (filepath != null && StringUtils.isNotBlank(filepath)) {
                    break;
                }
            }
            Thread.sleep(1000);
        }
    }

    /**
     * 给jsonObject base64加密成字符串
     *
     * @param json
     *            json数据
     * @return base64 数据
     */
    private String responseResult(JSONObject json) {
        String jsonString = null;
        if (json != null) {
            log.debug("返回结果：{}", json.toJSONString());
            jsonString = Base64.encode(json.toJSONString());
        }
        return jsonString;
    }
}
