package com.ywt.outpatient.controllers;

import com.ywt.biz.common.enums.SexEnum;
import com.ywt.biz.common.util.DateUtil;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.outpaitent.micro.*;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.domain.models.enums.MicroConsultTypeEnum;
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.*;

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

@RestController("/outpatient/micro")
@RequestMapping(value = {"/outpatient/micro"}, method = RequestMethod.POST)
public class MicroOutpatientController {
    private static Logger logger = LoggerFactory.getLogger(MicroOutpatientController.class);

    @DubboReference
    private MicroOutpatientService microOutpatientServiceBlockingStub;

    @Autowired
    private UserSrv userSrv;

    //微门诊记录
    @RequestMapping({"/list"})
    public @ResponseBody
    BaseResponse getMicroOutpatientList(@RequestBody Map<String, Object> reqBody) {
        BaseResponse response = new BaseResponse();
        Integer status = (Integer) reqBody.getOrDefault("status", 2);//0-待诊 1-非待诊 2-所有
        Integer pageIndex = (Integer) reqBody.getOrDefault("pageIndex", 1);//页码
        Integer pageSize = (Integer) reqBody.getOrDefault("pageSize", 20);//页大小
        int userId = userSrv.getCurrentUserIdWrapped();

        if (status < 0 || status > 2) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "invalid status");
        }

        try {
            GetMicroConsultListRequest req = GetMicroConsultListRequest.newBuilder()
                    .setStatus(status)
                    .setDoctorId(userId)
                    .setPageIndex(pageIndex)
                    .setPageSize(pageSize)
                    .build();
            GetMicroConsultListResponse res = microOutpatientServiceBlockingStub.getMicroConsultList(req);
            if (res.getCode() == ResultCode.SUCCEED_VALUE) {
                List<Map<String, Object>> lst = new LinkedList<>();
                Map<String, Object> item;

                for (MicroConsult consult : res.getMicroConsultList()) {
                    item = new HashMap<>();
                    item.put("id", consult.getId());
                    item.put("name", consult.getName());
                    item.put("idCardNo", consult.getIdCardNo());
                    item.put("createTime", DateUtil.convertTimestampToDateString(consult.getCreateTime(), "yyyy-MM-dd HH:mm"));
                    item.put("hisPatientId", consult.getHisPatientId());
                    item.put("type", consult.getType());
                    item.put("userId", consult.getUserId());
                    item.put("status", consult.getStatus());
                    item.put("consult", (consult.getType() & MicroConsultTypeEnum.CONSULT.getValue()) == MicroConsultTypeEnum.CONSULT.getValue() ? 1 : 0);
                    item.put("prescription", (consult.getType() & MicroConsultTypeEnum.PRESCRIPTION.getValue()) == MicroConsultTypeEnum.PRESCRIPTION.getValue() ? 1 : 0);
                    item.put("returnVisit", (consult.getType() & MicroConsultTypeEnum.RETURN_VISIT.getValue()) == MicroConsultTypeEnum.RETURN_VISIT.getValue() ? 1 : 0);
                    item.put("orderId", consult.getOrderId());
                    item.put("sessionId", consult.getSessionId());
                    item.put("patientId", consult.getPatientId());
                    item.put("sex", consult.getSex());
                    item.put("strSex", SexEnum.getSexDisplayName(consult.getSex()));
                    item.put("age", consult.getAge());
                    item.put("mobile", consult.getMobile());
                    item.put("createTimeChinese", DateUtil.convertTimestampToDateString(consult.getCreateTime(), "yyyy年MM月dd日 HH:mm"));
                    item.put("amount", consult.getAmount() / 100d);
                    item.put("statusName", consult.getStatusName());
                    item.put("orderType", consult.getOrderType());
                    item.put("address", consult.getAddress());
                    item.put("mrVisible", consult.getMrVisible());
                    lst.add(item);
                }

                Map<String, Object> data = new HashMap<>();
                data.put("list", lst);
                data.put("count", res.getCount());
                data.put("totalPage", res.getTotalPages());
                data.put("waitCount", res.getWaitCount());
                data.put("recordCount", res.getRecordCount());
                return response.succeed(data);
            }
            return response.failed(BaseResponse.APP_ERROR, res.getMsg());
        } catch (Exception e) {
            logger.error("getMicroOutpatientList({}, {}): {}", status, userId, e.getMessage(), e);
            return response.error();
        }
    }

    //结束门诊
    @RequestMapping({"/end"})
    public @ResponseBody
    BaseResponse endOutpatient(@RequestBody Map<String, Object> reqBody) {
        BaseResponse response = new BaseResponse();
        Integer id = (Integer) reqBody.getOrDefault("id", 0);//微门诊记录ID
        int userId = userSrv.getCurrentUserIdWrapped();

        if (id <= 0) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "invalid id");
        }
        try {
            EndOutpatientRequest req = EndOutpatientRequest.newBuilder()
                    .setId(id)
                    .setDoctorId(userId)
                    .build();
            EndOutpatientResponse res = microOutpatientServiceBlockingStub.endOutpatient(req);

            if (res.getCode() == ResultCode.SUCCEED_VALUE) {
                return response.succeed();
            }
            return response.failed(BaseResponse.APP_ERROR, res.getMsg());
        } catch (Exception e) {
            logger.error("endOutpatient({}, {}): {}", id, userId, e.getMessage(), e);
            return response.error();
        }
    }
}
