package com.ywt.outpatient.controllers.taihe;

import com.ywt.biz.common.util.Checker;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.order.CreateCheckUpOrderRequest;
import com.ywt.gapi.order.CreateCheckUpOrderResponse;
import com.ywt.gapi.order.OrderService;
import com.ywt.gapi.third.taihe.*;
import com.ywt.outpatient.api.req.CreateCheckUpOrderReq;
import com.ywt.outpatient.api.req.GetNoPayCheckUpOrderListReq;
import com.ywt.outpatient.api.req.GetNoPayOrderDetailReq;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.core.utils.BizUtil;
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 2020-10-13 15:43
 * @program ywt-wapapi
 * @description 体检缴费订单相关接口
 **/
@RestController("/taihe/checkUp")
@RequestMapping(value = {"/taihe/checkUp"},method = RequestMethod.POST)
public class CheckUpOrderController {
    private static Logger logger = LoggerFactory.getLogger(CheckUpOrderController.class);
    @DubboReference
    private TaiheService taiheServiceBlockingStub;

    @DubboReference
    private OrderService orderServiceBlockingStub;

    @Autowired
    private UserSrv userSrv;

    /**
     * 查找待缴费记录
     */
    @RequestMapping("/getNoPayOrderList")
    BaseResponse getNoPayOrderList(@RequestBody GetNoPayCheckUpOrderListReq req) {
        BaseResponse response = new BaseResponse();
        String reqNo = req.getRegNo();
        if (Checker.isNone(reqNo)) {
            return response.failedWithParameterError("参数不能为空");
        }
        // 请求中控的接口
        PhyPayListRequest request = PhyPayListRequest.newBuilder().setRegNo(reqNo)
                .setHospitalId(BizUtil.getHospitalIdByTerminalId(BizUtil.getCurrentTerminalWrapped()))
                .build();
        PhyPayListResponse res = taiheServiceBlockingStub.phyPayList(request);
        if (res.getCode() == ResultCode.SUCCEED.getNumber()) {

            List itemList = new ArrayList();
            res.getListList().forEach(p -> {
                int totalFeeInt = Checker.getIntegerValue(p.getTotalFee());
                double totalFee = totalFeeInt / 100d;

                int amtInt = Checker.getIntegerValue(p.getAmt());
                double amt = amtInt / 100d;
                Map<String, Object> map = new HashMap<>();
                map.put("admId", p.getAdmId());
                map.put("checkDate", p.getCheckDate());
                String desc =  Checker.getStringValue(p.getSetsDesc());
                if (Checker.isNone(desc.trim())){
                    desc = "-";
                }
                map.put("setsDesc", desc);
                map.put("amt", amt);
                map.put("amtStr", String.format("%.2f元", amt));
                map.put("totalFee", totalFee);
                map.put("totalFeeStr", String.format("%.2f元", totalFee));
                itemList.add(map);
            });

            String patientName = res.getPatientName();
            String sex = res.getSex();

            Map<String, Object> map = new HashMap<>();
            map.put("patientName", patientName);
            map.put("sex", sex);
            map.put("itemList", itemList);
            return response.succeed("处理成功", map);
        }
        return response.failedWithAppError();
    }


    /**
     * 查找待缴费项目详情
     */
    @RequestMapping("/getNoPayOrderDetail")
    BaseResponse getNoPayOrderDetail(@RequestBody GetNoPayOrderDetailReq req) {
        BaseResponse response = new BaseResponse();
        String admId = req.getAdmId();
        if (Checker.isNone(admId)) {
            return response.failedWithParameterError("参数不能为空");
        }
        // 请求中控的接口
        PhyPayDetailRequest request = PhyPayDetailRequest.newBuilder()
                .setAdmId(admId)
                .setHospitalId(BizUtil.getHospitalIdByTerminalId(BizUtil.getCurrentTerminalWrapped()))
                .build();
        PhyPayDetailResponse res = taiheServiceBlockingStub.phyPayDetail(request);
        if (res.getCode() == ResultCode.SUCCEED.getNumber()) {

            List itemList = new ArrayList();
            res.getListList().forEach(p -> {
                int amtInt = Checker.getIntegerValue(p.getAmt());
                double amt = amtInt / 100d;
                Map<String, Object> map = new HashMap<>();
                map.put("arcmiDesc", p.getArcmiDesc());
                map.put("amt", amt);
                map.put("amtStr", String.format("%.2f元", amt));
                itemList.add(map);
            });
            Map<String, Object> map = new HashMap<>();
            map.put("itemList", itemList);
            return response.succeed("处理成功", map);
        }
        return response.failedWithAppError();
    }


    /**
     * 创建体检缴费订单
     */
    @RequestMapping("/createCheckUpOrder")
    BaseResponse createCheckUpOrder(@RequestBody CreateCheckUpOrderReq req) {
        BaseResponse response = new BaseResponse();
        int userId = userSrv.getCurrentUserIdWrapped();
        String admId = req.getAdmId();
        if (Checker.isNone(admId)) {
            return response.failedWithParameterError("参数不能为空");
        }
        int amount = 0;
        // 请求中控的接口，再获取详情金额，会更加稳妥
        PhyPayDetailRequest request = PhyPayDetailRequest.newBuilder()
                .setAdmId(admId)
                .setHospitalId(BizUtil.getHospitalIdByTerminalId(BizUtil.getCurrentTerminalWrapped()))
                .build();
        PhyPayDetailResponse res = taiheServiceBlockingStub.phyPayDetail(request);
        if (res.getCode() == ResultCode.SUCCEED.getNumber()) {
            amount = res.getListList().stream().mapToInt(PhyPayDetailItem::getAmt).sum();
        } else {
            return response.error("订单创建失败，请稍后再试");
        }
        CreateCheckUpOrderRequest createReq = CreateCheckUpOrderRequest.newBuilder()
                .setUserId(userId)                      // 用户ID
                .setPatientName(req.getPatientName())   // 患者姓名
                .setSex(req.getSex())                   // 性别
                .setRegNo(req.getRegNo())               // 登记号
                .setAdmId(admId)                        // 就诊ID
                .setAmount(amount)                      // 订单金额
                .setCheckDate(req.getCheckDate())       //体检日期
                .setSetsDesc(req.getSetsDesc())         //套餐描述
                .setHospitalId(BizUtil.getHospitalIdByTerminalId(userSrv.getCurrentTerminal()))
                .build();
        CreateCheckUpOrderResponse createRes = orderServiceBlockingStub.createCheckUpOrder(createReq);
        if (createRes.getCode() == ResultCode.SUCCEED.getNumber()) {
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", createRes.getOrderId());
            map.put("amount", amount);
            return response.succeed(map);
        }
        return response.failedWithAppError();
    }


}
