package com.ywt.alipaympapi.service.impl;

import com.ywt.alipaympapi.core.utils.BizUtil;
import com.ywt.alipaympapi.core.utils.Checker;
import com.ywt.alipaympapi.core.utils.DateUtil;
import com.ywt.alipaympapi.core.utils.JsonSerializer;
import com.ywt.alipaympapi.models.enums.SexEnum;
import com.ywt.alipaympapi.service.IsvRegisterService;
import com.ywt.core.exception.AppMessageException;
import com.ywt.gapi.Result;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.system.Dept;
import com.ywt.gapi.system.*;
import com.ywt.gapi.taihe.register.CancelRegisteredRequest;
import com.ywt.gapi.taihe.register.CancelRegisteredResponse;
import com.ywt.gapi.taihe.register.TaiheRegisterServiceGrpc;
import com.ywt.gapi.third.taihe.*;
import com.ywt.model.PageVO;
import com.ywt.model.Pagination;
import com.ywt.request.queue.QueryQueueListRequest;
import com.ywt.request.register.*;
import com.ywt.response.queue.QueryQueueListResponse;
import com.ywt.response.register.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
public class IsvRegisterServiceImpl implements IsvRegisterService {

    @Autowired
    private TaiheRegisterServiceGrpc.TaiheRegisterServiceBlockingStub taiheRegisterServiceBlockingStub;

    @Autowired
    private SystemServiceGrpc.SystemServiceBlockingStub systemServiceBlockingStub;

    @Autowired
    private TaiheServiceGrpc.TaiheServiceBlockingStub taiheServiceBlockingStub;

    @Override
    public List<QueryDepartmentListResponseData> queryDepartmentList(QueryDepartmentListRequest request) throws Exception {
        log.info("IsvRegisterServiceImpl#queryDepartmentList--QueryDepartmentListRequest：{}", JsonSerializer.toJson(request));
        int hospitalId = BizUtil.getCurrentHospitalId();
        String hospitalDistrictId = request.getHospitalDistrictId();
        int subHospitalId = 0;
        if (!Checker.isNone(hospitalDistrictId)) {
            subHospitalId = Integer.parseInt(hospitalDistrictId);
        }
        List<HospitalDept> deptList = null;
        HospitalDeptListRequest req = HospitalDeptListRequest.newBuilder()
                .setHospitalId(hospitalId)
                .setSubHospitalId(subHospitalId)
                .build();
        HospitalDeptListResponse res = systemServiceBlockingStub.getHospitalDeptList(req);
        Result result = res.getResult();
        if (result.getCode() == ResultCode.SUCCEED) {
            deptList = res.getHospitalDeptListList();
        }
        if (deptList == null) {
            throw new AppMessageException("科室不存在");
        }
        String parentId = request.getParentId();
        int deptParentId = 0;
        if (!Checker.isNone(parentId)) {
            deptParentId = Integer.parseInt(parentId);
        }
        List<QueryDepartmentListResponseData> lst = new LinkedList<>();
        for (HospitalDept d : deptList) {
            if (deptParentId == 0) {
                QueryDepartmentListResponseData map = new QueryDepartmentListResponseData();
                map.setDepartmentId(d.getDeptId() + "");
                map.setName(d.getDeptName());
                map.setHasChildren(d.getDeptListList().size() > 0);
                map.setRemain(0);
                //院区id
                map.setHospitalDistrictId(hospitalDistrictId);
                lst.add(map);
            } else {
                if (deptParentId == d.getDeptId()) {
                    for (Dept secDept : d.getDeptListList()) {
                        QueryDepartmentListResponseData map = new QueryDepartmentListResponseData();
                        map.setDepartmentId(secDept.getDeptId() + "");
                        map.setName(secDept.getDeptName());
                        map.setHasChildren(false);
                        map.setRemain(0);
                        map.setHospitalDistrictId(hospitalDistrictId);
                        lst.add(map);
                    }
                }
            }
        }
        return lst;
    }

    @Override
    public List<QueryDepOrderSourceRemainResponseData> queryDepOrderSourceRemain(QueryDepOrderSourceRemainRequest request) {
        return null;
    }

    @Override
    public PageVO<QueryDepDoctorListResponseData> queryDepDoctorList(QueryDepDoctorListRequest request) {
        return null;
    }

    @Override
    public List<QueryDoctorOrderSourceListResponseData> queryDoctorOrderSourceList(QueryDoctorOrderSourceListRequest request) {
        return null;
    }

    @Override
    public OrderConfirmResponseData orderConfirm(OrderConfirmRequest request) {
        log.info("IsvRegisterServiceImpl#orderConfirm--OrderConfirmRequest：{}", JsonSerializer.toJson(request));
        int userId = Integer.parseInt(Checker.getStringValue(request.getUserId(), "0"));//用户唯一识别号
        String doctorId = request.getDoctorId();//医生唯一识别号
        String orderSourceId = request.getOrderSourceId();//号源id
        String cardNum = request.getCardNum();//就诊卡卡号
        int hospitalId = BizUtil.getCurrentHospitalId();


        return null;
    }

    @Override
    public QueryOrderDetailResponseData queryOrderDetail(QueryOrderDetailRequest request) {
        return null;
    }

    @Override
    public PageVO<QueryOrderListResponseData> queryOrderList(QueryOrderListRequest request) {
        return null;
    }

    @Override
    public CancelOrderResponseData cancelOrder(CancelOrderRequest request) throws Exception {
        CancelOrderResponseData responseData = new CancelOrderResponseData();
        String orderIdStr = request.getOrderId();
        if (Checker.isNone(orderIdStr) || Integer.parseInt(orderIdStr) <= 0) {
            throw new AppMessageException("订单不存在");
        }
        int orderId = Integer.parseInt(orderIdStr);
        int userId = Integer.parseInt(Checker.getStringValue(request.getUserId(), "0"));
        CancelRegisteredRequest req = CancelRegisteredRequest.newBuilder()
                .setOrderId(orderId)
                .setUserId(userId)
                .build();
        CancelRegisteredResponse res = taiheRegisterServiceBlockingStub.cancelRegistered(req);
        responseData.setIsSuccess(false);
        if (res.getCode() == ResultCode.SUCCEED_VALUE) {
            responseData.setIsSuccess(true);
        }
        return responseData;
    }

    @Override
    public List<QueryHospitalDistrictListResponseData> queryHospitalDistrictList(QueryHospitalDistrictListRequest request) {
        return null;
    }

    @Override
    public List<QueryQueueListResponse> queryQueueList(QueryQueueListRequest request) throws Exception {
        log.info("IsvRegisterServiceImpl#queryQueueList--QueryQueueListRequest：{}", JsonSerializer.toJson(request));
        int hospitalId = BizUtil.getCurrentHospitalId();
        //用户唯一识别号
        int userId = Integer.parseInt(Checker.getStringValue(request.getUserId(), "0"));

        List<QueryQueueListResponse> list = new LinkedList<>();

        com.ywt.gapi.taihe.register.GetQueueListRequest req = com.ywt.gapi.taihe.register.GetQueueListRequest.newBuilder()
                .setUserId(userId)
                .setHospitalId(hospitalId)
                .build();
        com.ywt.gapi.taihe.register.GetQueueListResponse res = taiheRegisterServiceBlockingStub.getQueueList(req);

        if (res.getCode() != ResultCode.SUCCEED_VALUE) {
            throw new AppMessageException(res.getMsg());
        }

        List<com.ywt.gapi.taihe.register.RegisteredOrder> queueList = res.getOrderList();

        LocalDate now = LocalDate.now();
        for (com.ywt.gapi.taihe.register.RegisteredOrder order : queueList) {
            QueryQueueListResponse reportItem = new QueryQueueListResponse();
            int cancel = 0; //是否显示退号按钮，1-是，0-否
            LocalDate regDate = DateUtil.convertToLocalDate(new Date(order.getRegisteredDate()));//预约日期
            if (now.isBefore(regDate)) {
                cancel = 1;
            }
            String statusName = order.getStatusName();
            int status = order.getStatus();

            if (order.getStatus() == 1) {
                //已预约
                statusName = "未取号";

                if (DateUtil.convertTimestampToDateString(order.getRegisteredDate(), "yyyy-MM-dd").equals(
                        DateUtil.formatDate(new Date(), "yyyy-MM-dd"))) {

                } else {
                    status = 0;
                }
            }
            reportItem.setCardNum(order.getMedicalCardId()+"");//就诊卡卡号
            reportItem.setName(order.getPatientName());//就诊人姓名
            reportItem.setSex(SexEnum.getSexDisplayName(order.getSex()));//性别
            reportItem.setAge("");//年龄
            reportItem.setTitle(statusName);//排队标题
            reportItem.setDepName(order.getDeptName());//科室
            reportItem.setDoctorName(order.getDoctorName());//医生姓名
            reportItem.setDoctorDesc("");//医生描述
            reportItem.setAddress(order.getAddress());//就诊地点

            int queueNum = 0, leftOver = 0;
            GetQueueInfoRequest getQueueInfoRequest = GetQueueInfoRequest.newBuilder()
                    .setRegistrationId(order.getHisSeqCode())
                    .setHospitalId(hospitalId)
                    .build();
            GetQueueInfoResponse getQueueInfoResponse = taiheServiceBlockingStub.getQueueInfo(getQueueInfoRequest);
            if (getQueueInfoResponse.getCode() == ResultCode.SUCCEED_VALUE) {
                QueueInfo data = getQueueInfoResponse.getQueueInfo();
                queueNum = data.getWaitingNumber();
            }
            reportItem.setQueueNum(queueNum+"");//排队编号
            reportItem.setLeftover("0");//前面排队剩余人数
            reportItem.setStatus(statusName);//状态,expired：已过号，queuing：排队中，ringing：叫号中，completed：已完成
            reportItem.setContext(order.getRemark());//排队结束显示内容
            list.add(reportItem);
        }
        return list;

    }

    @Override
    public QueryDoctorInfoResponseData queryDoctorInfo(QueryDoctorInfoRequest request) {
        return null;
    }

    @Override
    public PageVO<QueryDoctorListResponseData> queryDoctorList(QueryDoctorListRequest request) {
        log.info("IsvRegisterServiceImpl#queryDoctorList--QueryDoctorListRequest：{}", JsonSerializer.toJson(request));
        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();
        String deptCode = request.getDeptCode();
        String doctorName = request.getDoctorName();
        int hospitalId = BizUtil.getCurrentHospitalId();
        GetDoctorListRequest getDoctorListRequest = GetDoctorListRequest.newBuilder()
                .setDeptCode(deptCode)
                .setDoctorName(doctorName)
                .setHospitalId(hospitalId)
                .build();
        GetDoctorListResponse getDoctorListResponse = taiheServiceBlockingStub.getDoctorList(getDoctorListRequest);
        int total = 0;
        List<QueryDoctorListResponseData> doctorList = new LinkedList<>();
        if (getDoctorListResponse.getCode() == ResultCode.SUCCEED_VALUE) {
            List<com.ywt.gapi.third.taihe.Doctor> doctorsList = getDoctorListResponse.getDoctorsList();

            total = doctorsList.size();
            for (com.ywt.gapi.third.taihe.Doctor doctor : doctorsList) {

                QueryDoctorListResponseData doctorItem = new QueryDoctorListResponseData();
                //医生id
                doctorItem.setDoctorId(doctor.getDoctorCode());
                //医生姓名
                doctorItem.setName(doctor.getDoctorName());
                //医生简介
                doctorItem.setDesc(doctor.getDoctorIntro());
                //医生头像地址
                doctorItem.setPicUrl("");
                //职级，医生职级
                doctorItem.setLevel(doctor.getDoctorTitle());
                //医生所在科室
                Department department = new Department();
                department.setDepartmentId(doctor.getDoctorDeptCode());
                department.setName(doctor.getDoctorDept());
                List<Department> deptList = new ArrayList();
                deptList.add(department);
                doctorItem.setDepartments(deptList);

                doctorList.add(doctorItem);
            }
        }
        Pagination pagination = new Pagination(pageIndex, pageSize, total);
        PageVO<QueryDoctorListResponseData> res = new PageVO<>(pagination, doctorList);
        return res;
    }
}
