package com.gxwebsoft.clinic.controller;

import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.clinic.service.ClinicPatientUserService;
import com.gxwebsoft.clinic.entity.ClinicPatientUser;
import com.gxwebsoft.clinic.param.ClinicPatientUserParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 患者控制器
 *
 * @author 科技小王子
 * @since 2025-10-19 09:27:04
 */
@Tag(name = "患者管理")
@RestController
@RequestMapping("/api/clinic/clinic-patient-user")
public class ClinicPatientUserController extends BaseController {
    @Resource
    private ClinicPatientUserService clinicPatientUserService;
    @Resource
    private UserService userService;

    @Operation(summary = "分页查询患者")
    @GetMapping("/page")
    public ApiResult<PageResult<ClinicPatientUser>> page(ClinicPatientUserParam param) {
        // 使用关联查询
        return success(clinicPatientUserService.pageRel(param));
    }

    @Operation(summary = "分页查询患者")
    @GetMapping("/userPage")
    public ApiResult<PageResult<ClinicPatientUser>> userPage(ClinicPatientUserParam param) {
        // 使用关联查询
        param.setUserId(getLoginUserId());
        return success(clinicPatientUserService.pageRel(param));
    }

    @Operation(summary = "查询全部患者")
    @GetMapping()
    public ApiResult<List<ClinicPatientUser>> list(ClinicPatientUserParam param, HttpServletRequest request) {
        List<ClinicPatientUser> list = clinicPatientUserService.listRel(param);
//        RequestUtil requestUtil = new RequestUtil();
//        requestUtil.setTenantId(getTenantId().toString());
//        String access_token = JwtUtil.getAccessToken(request);
//        requestUtil.setAccessToken(access_token);
        List<Integer> uidList = new ArrayList<>();
        if (!list.isEmpty()) {
            uidList = list.stream().map(ClinicPatientUser::getPatientUserId).toList();
//            List<User> userList = requestUtil.getUserList(String.join(",", uidList));
            List<User> userList = userService.getByUserIdListInner(uidList);
            for (ClinicPatientUser clinicPatientUser : list) {
                User user = userList.stream().filter(u -> u.getUserId().equals(clinicPatientUser.getPatientUserId())).findFirst().orElse(null);
                clinicPatientUser.setPatientUser(user);
            }
        }
        return success(list);
    }

    @GetMapping("/getByPatientUserId/{patientUserId}")
    public ApiResult<ClinicPatientUser> getByPatientUserId(@PathVariable("patientUserId") Integer patientUserId) {
        // 使用关联查询
        return success(clinicPatientUserService.getByPatientUserId(patientUserId));
    }

    @Operation(summary = "根据id查询患者")
    @GetMapping("/{id}")
    public ApiResult<ClinicPatientUser> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(clinicPatientUserService.getByIdRel(id));
    }


    @Operation(summary = "添加患者")
    @PostMapping()
    public ApiResult<?> save(@RequestBody ClinicPatientUser clinicPatientUser) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            clinicPatientUser.setUserId(loginUser.getUserId());
        }
        User patientUser = userService.getByPhoneInner(clinicPatientUser.getPhone());
        if (patientUser != null) clinicPatientUser.setPatientUserId(patientUser.getUserId());
        else return fail("患者用户不存在");
        if (clinicPatientUserService.save(clinicPatientUser)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }


    @Operation(summary = "修改患者")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ClinicPatientUser clinicPatientUser) {
        if (clinicPatientUserService.updateById(clinicPatientUser)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }


    @Operation(summary = "删除患者")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (clinicPatientUserService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }


    @Operation(summary = "批量添加患者")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<ClinicPatientUser> list) {
        if (clinicPatientUserService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }


    @Operation(summary = "批量修改患者")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicPatientUser> batchParam) {
        if (batchParam.update(clinicPatientUserService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }


    @Operation(summary = "批量删除患者")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (clinicPatientUserService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
