package com.api.htsc.browser;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.util.Util_DataMap;
import com.engine.htsc.payment.util.HttpUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StopWatch;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

/**
 * Author:DTY-PC
 * Description:
 * Copyright:上海泛微网络科技股份有限公司
 */
@Path("/esbBrowser")
public class ESBBrowser {

    private final Log log = LogFactory.getLog(ESBBrowser.class.getName());

    /**
     * 转换封装获取CRM信息
     *
     * @param workcode 工号
     * @param custNo   客户编号
     * @param custName 客户名称
     * @return
     */
    @GET
    @Path("/getCrmlist")
    @Produces(MediaType.TEXT_PLAIN)
    public String getCrmInfo(@QueryParam("workcode") String workcode,
                             @DefaultValue("") @QueryParam("custNo") String custNo,
                             @DefaultValue("") @QueryParam("custName") String custName,
                             @DefaultValue("0") @QueryParam("pageNo") String page,
                             @DefaultValue("10") @QueryParam("pagesize") String size) {
        Map<String, Object> apiDatas = new HashMap<>();
        try {
            BaseBean bb = new BaseBean();
            PropBean pb = new PropBean();
            String url = Util.null2String(pb.getPropName("crmurl"));
            String urlWithCondition = Util.null2String(pb.getPropName("crmurlWithCondition"));
            bb.writeLog("CRM接口请求url："+urlWithCondition);
            Map<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            HTUtil htUtil = new HTUtil();
            Map<String, String> appHeader = htUtil.getAppHeader();
            log.info("getAppHeader@" + appHeader + "@");
            //verify crm token
            header.putAll(appHeader);
            Map<String, String> params = new HashMap<>();
            params.put("userCode", workcode);
            params.put("custNo", custNo);
            params.put("custName", custName);
            params.put("page", page);
            params.put("size", size);
            //条件查询请求
            if (StringUtils.isNotBlank(custNo) || StringUtils.isNotBlank(custName)) {
                log.info("getCrmlist custNo:" + custNo + ", custName:" + custName);
                Map<String, String> map = new HashMap<>();
                map.put("userCode", workcode);
                map.put("custName", custName);
                map.put("custNo", custNo);
                String res = HttpUtil.postFormUrlEncode(urlWithCondition, map, appHeader);
                JSONObject oriObj = JSONObject.parseObject(res);//直接调的结果
                String code = Util.null2String(oriObj.get("code"));
                if ("100".equals(code)) {
                    JSONArray listArr = oriObj.getJSONObject("data").getJSONArray("custInfoList");
                    int total = Integer.parseInt(Util.null2String(oriObj.getJSONObject("data").get("total")));
                    apiDatas.put("datas", listArr);
                    apiDatas.put("code", code);
                    apiDatas.put("total", total);
                    apiDatas.put("api_status", true);
                    return JSONObject.toJSONString(apiDatas);
                }

            }
            bb.writeLog("CRM接口请求参数："+params);
            String res = HTUtil.httpPostForm(url, params, header, null);
            bb.writeLog("CRM接口响应："+res);
            JSONObject oriObj = JSONObject.parseObject(res);//直接调的结果
            String code = Util.null2String(oriObj.get("code"));
            if ("100".equals(code)) {
                JSONArray listArr = oriObj.getJSONObject("data").getJSONArray("custInfoList");
                int total = Integer.parseInt(Util.null2String(oriObj.getJSONObject("data").get("total")));
                apiDatas.put("datas", listArr);
                apiDatas.put("code", code);
                apiDatas.put("total", total);
            }
            apiDatas.put("api_status", true);
        } catch (Exception e) {
            log.error("get crm info error", e);
            apiDatas.put("api_status", false);
        }
        return JSONObject.toJSONString(apiDatas);
    }

    /**
     * 转换封装获取投行项目的接口
     *
     * @param workcode  工号
     * @param id      项目ID
     * @param shortName 项目简称
     * @return
     */
    @GET
    @Path("/getProlist")
    @Produces(MediaType.TEXT_PLAIN)
    public String getProInfo(@QueryParam("workcode") String workcode, @QueryParam("id") String id, @QueryParam("shortName") String shortName) {
        Map<String, Object> apiDatas = new HashMap<>();
        try {
            HTUtil ht = new HTUtil();
            Map<String, Object> para = new HashMap<>();
            para.put("userId", workcode);
            String res = ht.getProject(para);
            JSONArray oriArr = JSONArray.parseArray(res);//直接调的结果
            if (!"".equals(shortName)) {
                JSONArray arr = new JSONArray();
                for (int i = 0; i < oriArr.size(); i++) {
                    JSONObject jsonObject = oriArr.getJSONObject(i);
                    String orishortName = Util.null2String(jsonObject.get("shortName"));
                    if (orishortName.contains(shortName)) {
                        arr.add(jsonObject);
                        apiDatas.put("datas", arr);
                    }
                }
                if (!"".equals(id)) {
                    JSONArray arrCode = new JSONArray();//
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject jsonObject = arr.getJSONObject(i);
                        String oricode = Util.null2String(jsonObject.get("id"));
                        if (oricode.equals(id)) {
                            arr.add(jsonObject);
                            apiDatas.put("datas", arrCode);
                            break;
                        }
                    }
                }
            } else if (!"".equals(id)) {
                JSONArray arr = new JSONArray();//
                for (int i = 0; i < oriArr.size(); i++) {
                    JSONObject jsonObject = oriArr.getJSONObject(i);
                    String oricode = Util.null2String(jsonObject.get("id"));
                    if (oricode.equals(id)) {
                        arr.add(jsonObject);
                        apiDatas.put("datas", arr);
                        break;
                    }
                }
            } else {
                apiDatas.put("datas", oriArr);
            }
            apiDatas.put("api_status", true);
        } catch (Exception e) {
            e.printStackTrace();
            apiDatas.put("api_status", false);
        }
        return JSONObject.toJSONString(apiDatas);
    }


    /**
     * 转换封装获取投行项目的分页接口
     *
     * @param workcode
     * @param shortName
     * @param page
     * @param size
     * @return
     */
    @GET
    @Path("/getProlistByPage")
    @Produces(MediaType.TEXT_PLAIN)
    public String getProInfoByPage(@QueryParam("workcode") String workcode,
        @QueryParam("id") String id, @QueryParam("shortName") String shortName,
        @DefaultValue("0") @QueryParam("pageNo") String page,
        @DefaultValue("10") @QueryParam("pagesize") String size) {
        Map<String, Object> apiDatas = new HashMap<>();
        try {
            HTUtil ht = new HTUtil();
            JSONArray listArr = new JSONArray();
            int total = 0;
            Map<String, Object> params = new HashMap<>();
            if (StringUtils.isNotBlank(id)) {
                params.put("projectId", id);
                String res = ht.getProjectById(params);
                JSONObject oriObj = JSONObject.parseObject(res);
                listArr.add(oriObj);
                total = listArr.size();
            } else {
                params.put("userId", workcode);
                params.put("shortName", shortName);
                params.put("pageNum", page);
                params.put("pageSize", size);
                String res = ht.getProjectByPage(params);
                JSONObject oriObj = JSONObject.parseObject(res);
                listArr = oriObj.getJSONArray("data");
                total = oriObj.getIntValue("total");
            }
            apiDatas.put("datas", listArr);
            apiDatas.put("total", total);
            apiDatas.put("api_status", true);
        } catch (Exception e) {
            log.error(String
                .format("get project list by page error！workCode:%s, id:%s, pageNo:%s, pageSize:%s",
                    workcode, id, page, size), e);
            apiDatas.put("api_status", false);
        }
        return JSONObject.toJSONString(apiDatas);
    }

    /**
     * 获取云票夹信息
     *
     * @param UserCode    员工号
     * @param InvoiceType 发票类型 因为接口问题，这里传过来的类型是留着我自己重新处理数据用
     * @param pageNo      页码
     * @param pagesize    页大小
     * @param InvID  发票唯一主键
     * @return
     */
    @GET
    @Path("/getInvoiceInfo")
    @Produces(MediaType.TEXT_PLAIN)
    public String getInvoiceInfo(@QueryParam("UserCode") String UserCode,
        @QueryParam("InvoiceType") String InvoiceType, @QueryParam("pageNo") String pageNo,
        @QueryParam("pagesize") String pagesize, @QueryParam("InvID") String InvID,
        @QueryParam("InvoiceNum") String InvoiceNum, @QueryParam("InvoiceCode") String InvoiceCode,
        @QueryParam("JSHJ") String JSHJ) {
        StopWatch sw = new StopWatch();
        Map<String, Object> params = new HashMap<>();//参数集合
        params.put("UserCode", UserCode);
        params.put("InvoiceType", InvoiceType);//本身接口问题无法传具体类型，这边我在抓到数据后自己处理
        params.put("Page", pageNo);
        params.put("PageSize", pagesize);
        params.put("InvoiceNum", InvoiceNum);
        params.put("InvoiceCode", InvoiceCode);
        params.put("PriceAndTax", JSHJ);
        Map<String, Object> apiDatas = new HashMap<>();
        try {
            sw.start("get data");
            String cacheKey = String
                .format("%s_%s_%s_%s_%s_%s_%s", UserCode, InvoiceType, pageNo, pagesize, InvoiceNum,
                    InvoiceCode, JSHJ);
            String info = Util_DataMap.getValWithRedis(cacheKey);
            if (StringUtils.isNotBlank(info)) {
                log.info("cloud ticket folder esb get data from redis key: " + cacheKey);
            } else {
                HTUtil ht = new HTUtil();
                info = ht.queryInvoice(params);
                int expire = Util
                    .getIntValue(new PropBean().getPropName("query.invoice.expire"), 10);
                Util_DataMap.setValWithRedis(cacheKey, info, expire);
                log.info("cloud ticket folder esb get data from inteface");
            }
            sw.stop();

            sw.start("process data");
            // 号码_代码
            JSONObject infoObj = JSONObject.parseObject(info);//结果转JSONObject
            String ReCode = Util.null2String(infoObj.get("ReCode"));//状态码 1 成功
            String ReMsg = Util.null2String(infoObj.get("ReMsg"));//描述信息
            String TotalCount = Util.null2String(infoObj.get("TotalCount"));//总量
            JSONArray ReData = infoObj.getJSONArray("ReData");//数据集
            JSONArray cusArr = new JSONArray();
            if ("1".equals(ReCode)) {//成功
                for (int i = 0; i < ReData.size(); i++) {
                    JSONObject item = ReData.getJSONObject(i);//取出数据做当前发票类型过滤
                    String res_InvoiceType = Util.null2String(item.get("InvoiceType"));
                    String res_CheckStatus = Util
                        .null2String(item.get("CheckStatus"));//验真状态 0：未通过 1：通过 2：手工查验
                    String status = "";
                    if ("0".equals(res_CheckStatus)) {
                        status = "未通过";
                    } else if ("1".equals(res_CheckStatus)) {
                        status = "通过";
                    } else if ("2".equals(res_CheckStatus)) {
                        status = "手工查验";
                    }
                    item.put("CheckStatus", status);
                    item.put("FPType", translateFPType(Util.null2String(item.get("FPType"))));
                    String invoiceType = "";
                    switch (res_InvoiceType) {
                        case "1":
                            invoiceType = "增值税普通发票";
                            break;
                        case "2":
                            invoiceType = "增值税专用发票";
                            break;
                        case "11":
                            invoiceType = "增值税普通发票（卷式）";
                            break;
                        case "12":
                            invoiceType = "机动车销售统一发票";
                            break;
                        case "51":
                            invoiceType = "增值税电子普通发票";
                            break;
                        case "13":
                            invoiceType = "增值税电子专票";
                            break;
                        case "14":
                            invoiceType = "增值税电子普通发票（通行费）";
                            break;
                        case "31":
                            invoiceType = "汽车票";
                            break;
                        case "32":
                            invoiceType = "火车票";
                            break;
                        case "33":
                            invoiceType = "飞机票";
                            break;
                        case "21":
                            invoiceType = "进口增值税";
                            break;
                        case "22":
                            invoiceType = "进口关税";
                            break;
                        case "52":
                            invoiceType = "定额发票";
                            break;
                        case "55":
                            invoiceType = "普通发票";
                            break;
                        default:
                            invoiceType = "未明确类型";
                            break;
                    }
                    item.put("InvoiceType", invoiceType);
                    cusArr.add(item);
                }
                if (!"".equals(InvID)) {//主键
                    JSONArray filterArr = new JSONArray();
                    List<String> invidList = Util.splitString2List(InvID, ",");
                    for (int i = 0; i < cusArr.size(); i++) {
                        JSONObject item = cusArr.getJSONObject(i);//取出数据做当前发票类型过滤
                        String res_InvID = Util.null2String(item.get("InvID"));
                        if (invidList.contains(res_InvID)) {
                            filterArr.add(item);
                        }
                    }
                    cusArr = filterArr;
                    apiDatas.put("counts", cusArr.size());
                } else {
                    apiDatas.put("counts", TotalCount);
                }

                apiDatas.put("datas", cusArr);
            }
            apiDatas.put("code", ReCode);
            apiDatas.put("api_status", true);
            sw.stop();
            if ("1".equals(Util.null2String(new PropBean().getPropName("show.debug.log")))) {
                log.info(sw.prettyPrint());
            }
        } catch (Exception e) {
            apiDatas.put("api_status", false);
            log.error("cloud ticket folder esb error", e);
        }
        log.info("cloud ticket folder esb end!");
        return JSONObject.toJSONString(apiDatas);
    }

    /**
     * 转换发票分类
     *
     * @param type 入参
     * @return
     */
    private String translateFPType(String type) {
        String typeName = "";
        switch (type) {
            case "ZSFP":
                typeName = "住宿";
                break;
            case "CCJP":
                typeName = "车船";
                break;
            case "JTFP":
                typeName = "交通";
                break;
            case "TXFP":
                typeName = "通信";
                break;
            case "CYFP":
                typeName = "餐饮";
                break;
            case "YEFP":
                typeName = "娱乐";
                break;
            case "CGFP":
                typeName = "采购";
                break;
            case "JYPXFP":
                typeName = "教育";
                break;
            case "YLFP":
                typeName = "医疗";
                break;
            case "XZSYFP":
                typeName = "行政事业";
                break;
            case "JKSFP":
                typeName = "缴款书";
                break;
            default:
                typeName = "其他";
                break;
        }
        return typeName;
    }

}
