package com.ywt.outpatient.service.rpc;

import com.ywt.biz.common.util.Checker;
import com.ywt.biz.common.util.DateUtil;
import com.ywt.biz.common.util.serializers.JsonSerializer;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.checkup_booking.*;
import com.ywt.outpatient.api.checkup_booking.RegCheckupItemResp;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.core.utils.AESUtil;
import com.ywt.outpatient.domain.entity.center.*;
import com.ywt.outpatient.domain.models.config.CloudFilmConfig;
import com.ywt.outpatient.service.rpc.common.WeChatMsgProvider;
import com.ywt.outpatient.service.rpc.common.WxProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


@Service
public class CheckupBookingService {
    private static Logger logger = LoggerFactory.getLogger(CheckupBookingService.class);

    @Autowired
    private CheckupBookingAnnouncementRepository checkupBookingAnnouncementRepository;
    @Autowired
    private CheckupBookingOrderRepository checkupBookingOrderRepository;
    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private WxProvider wxProvider;

    @Autowired
    private CheckupBookingNoticeRepository checkupBookingNoticeRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private WeChatMsgProvider weChatMsgProvider;


    public GetAnnouncementResponse showCheckupAnnouncement(int hospitalId) {
        GetAnnouncementResponse.Builder response = GetAnnouncementResponse.newBuilder();
        if (hospitalId <= 0) {
            response.setCode(ResultCode.PARAMETER_ERROR_VALUE).setInfo("参数有误");
            return response.build();
        }
        CheckupBookingAnnouncement ca = checkupBookingAnnouncementRepository.findOneByHospitalId(hospitalId);
        response.setContent(ca.getContent())
                .setTitle(ca.getTitle())
                .setCode(ResultCode.SUCCEED_VALUE)
                .setInfo("");
        return response.build();
    }

    // 预约记录生成订单
    public CreateOrderResponse createOrder(RegRecord regRecord, int userId, int hospitalId, int subHospitalId, String medCardNo) {
        CreateOrderResponse.Builder response = CreateOrderResponse.newBuilder();
        CheckupBookingOrder order = new CheckupBookingOrder();
        order.setUserId(userId);
        order.setPatientName(regRecord.getPatientName());
        order.setPatientMobile(regRecord.getPhoneNo());
        order.setMedicalCardNo(medCardNo);
        order.setHisPatientId(regRecord.getPatientRegNo());
        order.setDeptName(regRecord.getLocDesc());
        order.setDeptCode(regRecord.getLocId());
        // 生成 orderNo
        String orderNo = idGenerator.generateOrderNo(CloudFilmConfig.Constants.ORDER_NO_BIZ_PREFIX_CHECKUP_BOOKING_ORDER);
        order.setOrderNo(orderNo);
        order.setHospitalId(hospitalId);
        order.setSubHospitalId(subHospitalId);
        order.setTotalPrice(regRecord.getTotalAmount());
        order.setStatus(Checker.parseInt(regRecord.getStatus()));
        Date regExamDate = DateUtil.parseDate(regRecord.getRegExamDate(), DateUtil.DADE_FROMAT_YMD);
        if (regExamDate == null) {
            logger.error("CheckupBookingService#createOrder(regExamDate = {}): 日期格式化错误！", regRecord.getRegExamDate());
        }
        order.setRegExamDate(regExamDate == null ? new Date() : regExamDate);
        order.setRegExamTime(regRecord.getRegExamTime());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setDeleted(false);
        order.setRegId(regRecord.getRegId());
        order.setIdCard(regRecord.getPatientIdNo());
        order.setCanCancel(0);
        order.setAdmId(regRecord.getAdmId());
        order.setPreIadm(regRecord.getPreIADM());
        order.setPmType(regRecord.getPmType());
        order.setPeId(regRecord.getPeId());
        order.setCanModifyFlag(regRecord.getCanModifyFlag());
        order.setPreWay(regRecord.getPreWay());
        String ordSetsId = regRecord.getOrdSetsId();
        order.setOrdSetsId(ordSetsId);
        order.setRegCheckupItems(JsonSerializer.toJson(regRecord.getRegCheckupItemList().stream()
                .map(i -> {
                    RegCheckupItemResp r = new RegCheckupItemResp();
                    String itemId = i.getItemId();
                    r.setItemId(itemId);
                    r.setItemDesc(i.getItemDesc());
                    r.setPreIOrdDr(i.getPreIOrdDr());
                    r.setNetPreItemDr(i.getNetPreItemDr());
                    r.setOrdSetsDr(i.getOrdSetsDr());
                    r.setOrdSetsDesc(i.getOrdSetsDesc());
                    r.setItemCategoryDesc(i.getItemCategoryDesc());
                    r.setPrice(i.getPrice());
                    r.setInPackage(i.getInPackage());
                    return r;
                })
                .collect(Collectors.toList())));
        checkupBookingOrderRepository.save(order);
        SnsUserInfo snsUserInfo = userService.getByUserId(userId, 21);
        if(Checker.isNone(snsUserInfo) || (!Checker.isNone(snsUserInfo) && Checker.isNone(snsUserInfo.getOpenId()))){
            snsUserInfo = userService.getByUserId(userId, 20);
            String openId = snsUserInfo.getOpenId();

            String idNo = AESUtil.encrypt(regRecord.getPatientIdNo());
            String templateId = "oc7voZXzm5s4UYQp-6LKSPfAjUIV9RW-B8rmTDx1DUU";
            String page = String.format(CloudFilmConfig.Constants.CHECK_UP_BOOKING_DETAIL, orderNo, hospitalId, 0, idNo, 0);
            Map<String, String> keywordMap = new HashMap();
            keywordMap.put("thing22", regRecord.getPatientName());
            keywordMap.put("character_string11", medCardNo);
            keywordMap.put("thing5", order.getDeptName());
            keywordMap.put("thing19",  "-");
            String timeStr = (regRecord.getRegExamDate()).replace("-", "") + "" + regRecord.getRegExamTime();
            logger.info("createOrder, timeSrt: {}, size: {}", timeStr, timeStr.length());
            keywordMap.put("thing16",  timeStr);
            weChatMsgProvider.sendMPSubscribeMessage(20, openId, templateId, page, keywordMap);
        }

        wxProvider.sendCheckupBooking(userId, orderNo, hospitalId, medCardNo, order.getIdCard(), order.getPatientName(), order.getDeptName(), regRecord.getRegExamDate(), regRecord.getRegExamTime(), order.getHisPatientId());
        response.setOrderNo(orderNo).setCreateTime(DateUtil.convertToString(order.getCreateTime()));
        return response.build();
    }

    public BaseResponse cancelOrder(String regId, int hospitalId) {
        BaseResponse response = new BaseResponse();
        if (Checker.isNone(regId)) {
            return response.parameterErrorFailed();
        }
        if (hospitalId < 0) {
            return response.failed(1, "网上预约医院不存在");
        }
        CheckupBookingOrder checkupBookingOrder = checkupBookingOrderRepository.findByRegId(regId, hospitalId);
        if (Checker.isNone(checkupBookingOrder)) {
            return response.failed(1, "网上预约订单不存在");
        }
        checkupBookingOrder.setStatus(2);
        checkupBookingOrder.setUpdateTime(new Date());
        checkupBookingOrderRepository.save(checkupBookingOrder);

        return response.succeed("成功取消订单");
    }


    //获取订单列表
    public GetOrderListResponse gerOrderList(String idCard, int hospitalId) {
        GetOrderListResponse.Builder response = GetOrderListResponse.newBuilder();
        List<CheckupBookingOrder> list = checkupBookingOrderRepository.findByIdNo(idCard, hospitalId);
        response.addAllOrderItem(list.stream()
                .map(p -> OrderItem.newBuilder()
                        .setOrderNo(Checker.getStringValue(p.getOrderNo()))
                        .setCreateTime(DateUtil.convertToString(p.getCreateTime()))
                        .setRegId(Checker.getStringValue(p.getRegId()))
                        .setRegCheckupItems(Checker.getStringValue(p.getRegCheckupItems()))
                        .setTotalPrice(Checker.getIntegerValue(p.getTotalPrice()))
                        .build()

                )
                .collect(Collectors.toList()));
        response.setCode(BaseResponse.SUCCEED);
        response.setInfo("");
        return response.build();
    }

    public GetNoticeResponse getNotice (String ordSetsId, int hospitalId) {
        GetNoticeResponse.Builder response = GetNoticeResponse.newBuilder();
        if (hospitalId <= 0) {
            response.setCode(ResultCode.PARAMETER_ERROR_VALUE).setInfo("参数有误");
            return response.build();
        }
        CheckupBookingNotice notice = checkupBookingNoticeRepository.findByOrdSetsId(ordSetsId, hospitalId);
        if (Checker.isNone(notice)){
            response.setCode(ResultCode.SUCCEED_VALUE)
                    .setInfo("")
                    .setShow(0);
            return response.build();
        } else {
            if (notice.getNotice().equals("")){
                response.setCode(ResultCode.SUCCEED_VALUE)
                        .setInfo("")
                        .setShow(0);
                return response.build();
            } else {
                response.setCode(ResultCode.SUCCEED_VALUE)
                        .setInfo("")
                        .setNotice(notice.getNotice())
                        .setShow(1);
                return response.build();
            }
        }
    }
}
