package com.ywt.alipaympapi.web.controller;

import com.ywt.alipaympapi.core.utils.*;
import com.ywt.alipaympapi.models.BaseResponse;
import com.ywt.alipaympapi.models.BaseResponse2;
import com.ywt.alipaympapi.models.auth.*;
import com.ywt.alipaympapi.models.enums.DatePeriodEnum;
import com.ywt.alipaympapi.web.interceptors.WebAppContext;
import com.ywt.core.exception.AppMessageException;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.taihe.register.TaiheRegisterServiceGrpc;
import com.ywt.gapi.third.taihe.*;
import com.ywt.gapi.user.*;
import com.ywt.model.Code;
import com.ywt.model.PageVO;
import com.ywt.model.Pagination;
import com.ywt.model.ResponseVO;
import com.ywt.request.register.QueryDoctorScheduleListRequest;
import com.ywt.response.register.QueryDoctorScheduleListResponseData;
import com.ywt.response.register.ScheduleInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author dyh2020
 * Created on 2022/9/21
 */
@Slf4j
@RestController("/register")
@RequestMapping({"/register"})
public class RegisterController {

    @Autowired
    private TaiheServiceGrpc.TaiheServiceBlockingStub taiheServiceBlockingStub;

    /**
     * 得到医生分时排班信息
     */
    @RequestMapping({"/doctorSchedule"})
    public @ResponseBody
    ResponseVO<List<QueryDoctorScheduleListResponseData>> getDoctorScheduleList(@RequestBody QueryDoctorScheduleListRequest request) {
        try {
            int hospitalId = Checker.getIntegerValue(request.getHospitalId());
            String deptCode = Checker.getStringValue(request.getDeptCode());
            String doctorCode = Checker.getStringValue(request.getDoctorCode());
            String serviceDate = Checker.getStringValue(request.getServiceDate());
            Integer period = Checker.getIntegerValue(request.getPeriod());
            if (StringHelper.isNullOrWhiteSpace(deptCode)) {
                throw new AppMessageException("科室不存在");
            }
            if (StringHelper.isNullOrWhiteSpace(doctorCode)) {
                throw new AppMessageException("医生不存在");
            }

            List<QueryDoctorScheduleListResponseData> dataList = new LinkedList<>();

            if (!StringHelper.isNullOrWhiteSpace(serviceDate)) {
                Date date = DateUtil.parseDate(serviceDate, "yyyy-MM-dd");
                if (date == null) {
                    throw new AppMessageException("invalid serviceDate");
                }
                //查询医生某一天的排班分时信息
                if (period == null) {
                    throw new AppMessageException("请选择时段");
                }
                if (DatePeriodEnum.valueOf(period) == null) {
                    throw new AppMessageException("时段不存在");
                }

                String strDate = DateUtil.formatDate(date, "yyyy-MM-dd");
                QueryDoctorScheduleListResponseData map = getScheduleTimeInfoResponse(deptCode, doctorCode, strDate, period, hospitalId);

                if (map != null) {
                    dataList.add(map);
                }
            } else {
                //取医生8天排班的分时信息
                int[] periods = {DatePeriodEnum.MORNING.getValue(), DatePeriodEnum.AFTERNOON.getValue()};
                Calendar calendar = Calendar.getInstance();

                for (int offset = 0; offset < 8; offset++) {
                    calendar.add(Calendar.DATE, 1);
                    String strDate = DateUtil.formatDate(calendar.getTime(), "yyyy-MM-dd");

                    for (int p : periods) {
                        QueryDoctorScheduleListResponseData map = getScheduleTimeInfoResponse(deptCode, doctorCode, strDate, p, hospitalId);

                        if (map != null) {
                            dataList.add(map);
                        }
                    }
                }
            }
            return ResponseVO.success(dataList);
        } catch (AppMessageException e) {
            return ResponseVO.fail(Code.RESP_CODE_PARAM_ERROR, e.getMessage());
        } catch (Exception e) {
            log.error("PlanController#queryDepDoctorList(request = {}):\n {}", request, e.getMessage(), e);
            return ResponseVO.fail(Code.RESP_CODE_APP_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 得到分时排班信息
     *
     * @param deptCode
     * @param doctorCode
     * @param serviceDate
     * @param period
     * @return
     */
    private QueryDoctorScheduleListResponseData getScheduleTimeInfoResponse(String deptCode, String doctorCode, String serviceDate,
                                                                            int period, int hospitalId) {
        List<ScheduleInfo> lst = new LinkedList<>();

        GetScheduleTimeInfoRequest getScheduleTimeInfoRequest = GetScheduleTimeInfoRequest.newBuilder()
                .setDeptCode(deptCode)
                .setDoctorCode(doctorCode)
                .setServiceDate(serviceDate)
                .setDatePeriod(period)
                .setHospitalId(hospitalId)
                .build();
        GetScheduleTimeInfoResponse getScheduleTimeInfoResponse = taiheServiceBlockingStub.getScheduleTimeInfo(getScheduleTimeInfoRequest);

        if (getScheduleTimeInfoResponse.getCode() == ResultCode.SUCCEED_VALUE) {
            List<ScheduleTimeInfo> scheduleTimeInfoList = getScheduleTimeInfoResponse.getScheduleTimeInfosList();
            Calendar calendar = Calendar.getInstance();
            String strDate = DateUtil.formatDate(calendar.getTime(), "yyyy-MM-dd");
            String strTime = DateUtil.formatDate(calendar.getTime(), "HHmm");
            int time = Integer.parseInt(strTime);

            String strEndTime;
            String flag;
            int tmp;
            int left;

            for (ScheduleTimeInfo scheduleTimeInfo : scheduleTimeInfoList) {
                flag = scheduleTimeInfo.getAvailableFlag();
                left = scheduleTimeInfo.getAvailableLeftNum();

                if (strDate.equals(serviceDate) && !StringHelper.isNullOrWhiteSpace(scheduleTimeInfo.getEndTime())) {
                    strEndTime = scheduleTimeInfo.getEndTime();
                    tmp = Integer.parseInt(strEndTime.replace(":", ""));

                    if (tmp < time) {
                        left = 0;
                        flag = "N";
                    }
                }

                ScheduleInfo map = new ScheduleInfo();
                map.setScheduleItemCode(scheduleTimeInfo.getScheduleItemCode());
                map.setStartTime(scheduleTimeInfo.getStartTime());
                map.setEndTime(scheduleTimeInfo.getEndTime());
                map.setAvailableTotalNum(scheduleTimeInfo.getAvailableTotalNum());
                map.setAvailableLeftNum(left);
                map.setAvailableFlag(flag);
                map.setAvailableNumStr(scheduleTimeInfo.getAvailableNumStr());

                lst.add(map);
            }
        }

        if (lst.size() > 0) {
            QueryDoctorScheduleListResponseData dateMap = new QueryDoctorScheduleListResponseData();
            dateMap.setServiceDate(serviceDate);
            dateMap.setPeriod(period);
            dateMap.setDatePeriod(DatePeriodEnum.valueOf(period).getDisplayName());
            dateMap.setSchedule(lst);

            return dateMap;
        }

        return null;
    }

}
