package com.ywt.outpatient.controllers.baiyun;

import com.fasterxml.jackson.databind.JsonNode;
import com.ywt.biz.common.util.Checker;
import com.ywt.biz.common.util.HttpUtil;
import com.ywt.biz.common.util.serializers.JsonSerializer;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.third.taihe.*;
import com.ywt.gapi.user.User;
import com.ywt.outpatient.api.req.GetPhyReportDetailReq;
import com.ywt.outpatient.config.ParameterConfigurer;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.core.utils.BizUtil;
import com.ywt.outpatient.core.utils.JwtUtil;
import com.ywt.outpatient.service.web.UserSrv;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * @author daiyihua
 * @create 2021-10-09 10:43
 * @program ywt-wapapi
 * @description 体检相关接口
 **/
@RestController("/baiyun/checkUp")
@RequestMapping(value = {"/baiyun/checkUp"}, method = RequestMethod.POST)
public class NfyyByfyCheckUpOrderController {
    private static Logger logger = LoggerFactory.getLogger(NfyyByfyCheckUpOrderController.class);

    @DubboReference
    private TaiheService taiheServiceBlockingStub;

    @Autowired
    private UserSrv userSrv;

    @Autowired
    private ParameterConfigurer parameterConfigurer;


    /**
     * 体检报告查询
     */
    @RequestMapping("/getPhyReportList")
    BaseResponse getNoPayOrderList() {
        BaseResponse response = new BaseResponse();
        int userId = userSrv.getCurrentUserId();
        if (userId <= 0) {
            return response.failedWithParameterError("请先授权登陆");
        }
        User user = userSrv.findByUserId();
        if (Checker.isNone(user) || Checker.isNone(user.getIdno())) {
            return response.failedWithParameterError("请先实名认证");
        }

        // 请求中控的接口，获取列表
        PhyReportListRequest request = PhyReportListRequest.newBuilder()
                .setIdNo(user.getIdno())
                .setHospitalId(BizUtil.getHospitalIdByTerminalId(BizUtil.getCurrentTerminalWrapped()))
                .build();
        PhyReportListResponse res = taiheServiceBlockingStub.phyReportList(request);
        if (res.getCode() == ResultCode.SUCCEED.getNumber()) {

            List itemList = new ArrayList();
            res.getListList().forEach(p -> {
                Map<String, Object> map = new HashMap<>();
                map.put("patientName", p.getPatientName());        //姓名
                map.put("sex", p.getSex());                        //性别
                map.put("age", p.getAge());                        //年龄
                map.put("examDate", p.getExamDate());           //体检日期
                map.put("company", p.getCompany());             //单位
                map.put("admId", p.getAdmId());                 //就诊ID
                map.put("reportStatus", p.getReportStatus());   //报告状态
                map.put("peStatus", p.getPeStatus());           //体检状态
                map.put("preDate", p.getPreDate());             //预约日期
                map.put("orderName", p.getOrderName());         //套餐名称
                map.put("hPNo", p.getHPNo());                   //FIXME
                itemList.add(map);
            });
            Map<String, Object> map = new HashMap<>();
            map.put("itemList", itemList);
            return response.succeed("处理成功", map);
        }
        return response.failedWithAppError("暂无报告，请稍后再试");
    }


    /**
     * 体检报告详情
     */
    @RequestMapping("/getPhyReportDetail")
    BaseResponse getPhyReportDetail(@RequestBody GetPhyReportDetailReq req) {
        BaseResponse response = new BaseResponse();
        String admId = req.getAdmId();
        if (Checker.isNone(admId)) {
            return response.failedWithParameterError("参数不能为空");
        }
        // 请求中控的接口
        PhyReportDetailRequest request = PhyReportDetailRequest.newBuilder()
                .setAdmId(admId)
                .setHospitalId(BizUtil.getHospitalIdByTerminalId(BizUtil.getCurrentTerminalWrapped()))
                .build();
        PhyReportDetailResponse res = taiheServiceBlockingStub.phyReportDetail(request);
        if (res.getCode() == ResultCode.SUCCEED.getNumber()) {
            // reportPdf 存放的是 pdf的名称,eg: aa.pdf
            Map map = new HashMap();
            map.put("fileName", res.getReportPdf());

            String url = parameterConfigurer.getByFtpUrl();
            String pdfUrl = getStaticPdfUrl(url, map);

            Map returnMap = new HashMap();
            returnMap.put("pdfUrl", pdfUrl);
            return response.succeed("处理成功", returnMap);
        }
        return response.failedWithAppError("暂无报告，请稍后再试");
    }

    /**
     * 获取静态PDF地址
     *
     * @param url  url路径
     * @param body 携带的参数
     * @return 静态PDF地址
     */
    private String getStaticPdfUrl(String url, Map<String, Object> body) {
        try {
            logger.info("--------------------------------------");
            String appId = parameterConfigurer.getByFtpAppid();
            String appSecret = parameterConfigurer.getByFtpAppsecret();
            logger.info(appId, "\t", appSecret);
            //String url = "https://api-qa.ywtinfo.com/v2/hospital/getCloudPlatformHospitalList";

            String dataStr = JsonSerializer.toJson(body);
            logger.info(dataStr);
            if (Checker.isNone(dataStr)) {
                return "";
            }

            // 创建token
            String token = JwtUtil.createJWT(dataStr, appId, appSecret);
            logger.info("生成的Token是:" + token);
            Map<String, String> headers = new HashMap<>(16);
            String authorization = "Bearer ".concat(token);
            headers.put("Authorization", authorization);
            headers.put("Content-Type", "application/json");

            logger.info(JsonSerializer.toJson(headers));
            // 进行http请求
            HttpUtil.Resp resp = HttpUtil.httpPost(url, JsonSerializer.toJson(body), headers, "UTF-8");
            if (!Checker.isNone(resp)) {
                JsonNode jsonNode = JsonSerializer.readToNode(resp.getContent());
                String data = jsonNode.get("data").toString();
                if (!Checker.isNone(data)) {
                    JsonNode listNode = JsonSerializer.readToNode(data);
                    String pdfUrl = listNode.get("url").asText();
                    return pdfUrl;
                }
                logger.info(JsonSerializer.toJson(resp.getContent()));
            }
            logger.info("++++++++++++++++++++++++++++++++++++++");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }
}
