package com.eitc.patient.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eitc.common.core.controller.BaseController;
import com.eitc.common.core.domain.AjaxResult;
import com.eitc.common.utils.JWTUtil;
import com.eitc.patient.domain.AppUser;
import com.eitc.patient.domain.AppUserPatients;
import com.eitc.patient.domain.MedicalHistory;
import com.eitc.patient.domain.Patient;
import com.eitc.patient.enums.MedicalHistoryDiseaseSourceEnum;
import com.eitc.patient.enums.MedicalHistoryDiseaseTypeEnum;
import com.eitc.patient.service.IAppUserPatientsService;
import com.eitc.patient.service.IAppUserService;
import com.eitc.patient.service.IMedicalHistoryService;
import com.eitc.patient.service.IPatientService;
import com.eitc.patient.vo.AppUserPatientVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * AppUserController
 *
 * @author mtx
 * @date: 2024/06/12 16:48
 */
@Api(tags = "APP用户接口")
@RestController
@RequestMapping("/app/user")
public class AppUserController extends BaseController {

    @Resource
    private IAppUserService appUserService;
    @Resource
    private IAppUserPatientsService appUserPatientsService;
    @Resource
    private IPatientService patientService;
    @Resource
    private IMedicalHistoryService medicalHistoryService;


    /**
     * 添加就诊人
     *
     * @param entry 参数
     * @return 返回结果
     * @author mtx
     * @date: 2024/6/14 8:34
     */
    @PostMapping
    @ApiOperation("添加就诊人")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userRelationship", value = "关系", required = true, dataType = "String"),
            @ApiImplicitParam(name = "patientName", value = "患者姓名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "identificationCard", value = "身份证号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "documentType", value = "证件类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "allergyHistory", value = "过敏史", required = true, dataType = "String"),
            @ApiImplicitParam(name = "pastHistory", value = "既往史", required = true, dataType = "String"),
            @ApiImplicitParam(name = "familyHistory", value = "家族史", required = true, dataType = "String"),
            @ApiImplicitParam(name = "patientPhone", value = "患者手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "homeAddress", value = "家庭住址", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认（1默认，0不是默认）", required = true, dataType = "String"),
    })
    public AjaxResult add(@Valid @RequestBody AppUserPatientVO entry) {
        appUserService.add(entry);
        return success();
    }

    /**
     * 添加就诊人
     *
     * @param entry 参数
     * @return 返回结果
     * @author mtx
     * @date: 2024/6/14 8:34
     */
    @PutMapping
    @ApiOperation("编辑就诊人")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "patientId", value = "患者id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userRelationship", value = "关系", required = true, dataType = "String"),
            @ApiImplicitParam(name = "patientName", value = "患者姓名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "identificationCard", value = "身份证号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "documentType", value = "证件类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "allergyHistory", value = "过敏史", required = true, dataType = "String"),
            @ApiImplicitParam(name = "pastHistory", value = "既往史", required = true, dataType = "String"),
            @ApiImplicitParam(name = "familyHistory", value = "家族史", required = true, dataType = "String"),
            @ApiImplicitParam(name = "patientPhone", value = "患者手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "homeAddress", value = "家庭住址", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认（1默认，0不是默认）", required = true, dataType = "String"),
    })
    public AjaxResult edit(@Valid @RequestBody AppUserPatientVO entry) {
        appUserService.edit(entry);
        return success();
    }

    @DeleteMapping("/remove")
    @ApiOperation("解绑就诊人")
    public AjaxResult remove(String patientId) {
        return toAjax(appUserPatientsService.remove(Wrappers.<AppUserPatients>lambdaQuery()
                .eq(AppUserPatients::getAppUserId, JWTUtil.getAppUserId())
                .eq(AppUserPatients::getPatientId, patientId)));
    }

    /**
     * 就诊人列表
     *
     * @return 返回结果
     * @author mtx
     * @date: 2024/6/14 8:34
     */
    @GetMapping("/list")
    @ApiOperation("就诊人列表")
    public AjaxResult list() {
        // 根据登录信息获取登录人下绑定的就诊人
        String userId = JWTUtil.getAppUserId();
        List<AppUserPatients> list = appUserPatientsService.list(Wrappers.<AppUserPatients>lambdaQuery()
                .eq(AppUserPatients::getAppUserId, userId)
                .orderByDesc(AppUserPatients::getUpdateDate));
        List<AppUserPatientVO> vos = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return success(vos);
        }
        // 封装就诊人
        for (AppUserPatients li : list) {
            Patient patient = patientService.getById(li.getPatientId());
            AppUserPatientVO vo = new AppUserPatientVO();
            vo.setPatientId(li.getPatientId());
            vo.setUserRelationship(li.getRelationship());
            vo.setPatientName(patient.getPatientName());
            vo.setIdentificationCard(patient.getIdentificationCard());
            vo.setDocumentType(patient.getDocumentType());
            vo.setPatientPhone(patient.getPatientPhone());
            vo.setHomeAddress(patient.getHomeAddress());
            vo.setIsDefault(li.getIsDefault());

            // 封装病史
            List<MedicalHistory> histories = medicalHistoryService.list(Wrappers.<MedicalHistory>lambdaQuery()
                    .eq(MedicalHistory::getDiseaseSource, MedicalHistoryDiseaseSourceEnum.PATIENT.getCode())
                    .eq(MedicalHistory::getPatientId, li.getPatientId()));
            if (CollectionUtils.isNotEmpty(histories)) {
                vo.setAllergyHistory(
                        histories.stream()
                                .filter(entry -> MedicalHistoryDiseaseTypeEnum.ALLERGY_HISTORY.getCode().equals(entry.getDiseaseType()))
                                .map(MedicalHistory::getDiseaseContent)
                                .collect(Collectors.joining(","))
                );
                vo.setPastHistory(
                        histories.stream()
                                .filter(entry -> MedicalHistoryDiseaseTypeEnum.PAST_HISTORY.getCode().equals(entry.getDiseaseType()))
                                .map(MedicalHistory::getDiseaseContent)
                                .collect(Collectors.joining(","))
                );
                vo.setFamilyHistory(
                        histories.stream()
                                .filter(entry -> MedicalHistoryDiseaseTypeEnum.FAMILY_HISTORY.getCode().equals(entry.getDiseaseType()))
                                .map(MedicalHistory::getDiseaseContent)
                                .collect(Collectors.joining(","))
                );
            }
            vos.add(vo);
        }
        return success(vos);

    }

    /**
     * 设置密码
     */
    @PostMapping("/setPassword")
    @ApiOperation("设置密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "登录手机号", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "captchaCode", value = "短信验证码", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "confirmPassword", value = "确认密码", dataType = "String", dataTypeClass = String.class)
    })
    public AjaxResult setPassword(@RequestBody Map<String, String> map) {
        return appUserService.setPassword(map);
    }

    /**
     * 修改手机号
     */
    @PostMapping("/updatePhoneNumber")
    @ApiOperation("修改手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "新手机号", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "captchaCode", value = "短信验证码", dataType = "String", dataTypeClass = String.class),
    })
    public AjaxResult updatePhoneNumber(@RequestBody Map<String, String> map) {
        return appUserService.updatePhoneNumber(map);
    }

    /**
     * 编辑用户信息
     */
    @PostMapping("/edit")
    @ApiOperation("编辑用户信息")
    public AjaxResult edit(@RequestBody AppUser appUser) {
        if (StringUtils.isBlank(appUser.getId())) {
            return AjaxResult.error("用户ID不能为空");
        }
        AppUser au = new AppUser();
        au.setId(appUser.getId());
        au.setAvatar(appUser.getAvatar());
        return toAjax(appUserService.updateById(au));
    }

    /**
     * 获取用户信息
     *
     * @return 返回
     */
    @ApiOperation("APP当前登录用户信息")
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        String id = JWTUtil.getAppUserId();
        AppUser appUser = appUserService.getById(id);
        appUser.setPassword(null);
        return success(appUser);
    }

    /**
     * 锁定用户&解锁用户
     */
    @PostMapping("/locking")
    @ApiOperation("锁定用户&解锁用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "type", value = "类型（1锁定用户，0解锁用户）", dataType = "String", dataTypeClass = String.class)
    })
    public AjaxResult locking(@RequestBody Map<String, String> map) {
        return appUserService.locking(map);
    }

}
