package com.gxwebsoft.clinic.controller;

import cn.hutool.core.util.IdUtil;
import com.gxwebsoft.clinic.dto.PrescriptionOrderRequest;
import com.gxwebsoft.clinic.entity.ClinicPrescription;
import com.gxwebsoft.clinic.entity.ClinicPrescriptionItem;
import com.gxwebsoft.clinic.param.ClinicPrescriptionParam;
import com.gxwebsoft.clinic.service.ClinicPrescriptionItemService;
import com.gxwebsoft.clinic.service.ClinicPrescriptionService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 处方主表
 * 控制器
 *
 * @author 科技小王子
 * @since 2025-10-22 02:01:13
 */
@Tag(name = "处方主表管理")
@RestController
@RequestMapping("/api/clinic/clinic-prescription")
public class ClinicPrescriptionController extends BaseController {
    @Resource
    private ClinicPrescriptionService clinicPrescriptionService;
    @Resource
    private ClinicPrescriptionItemService clinicPrescriptionItemService;

    @Operation(summary = "分页查询处方主表")
    @GetMapping("/page")
    public ApiResult<PageResult<ClinicPrescription>> page(ClinicPrescriptionParam param) {
        param.setLoginUserId(getLoginUserId());
        return success(clinicPrescriptionService.pageRel(param));
    }

    @Operation(summary = "查询全部处方主表")
    @GetMapping()
    public ApiResult<List<ClinicPrescription>> list(ClinicPrescriptionParam param) {
        // 使用关联查询
        return success(clinicPrescriptionService.listRel(param));
    }

    @Operation(summary = "根据id查询处方主表")
    @GetMapping("/{id}")
    public ApiResult<ClinicPrescription> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(clinicPrescriptionService.getByIdRel(id));
    }


    @Operation(summary = "添加处方主表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody ClinicPrescription clinicPrescription) {
        // 记录当前登录用户id
//        clinicPrescription.setDoctorId(getLoginUserId());
        // 生成订单号
        String orderNo = Long.toString(IdUtil.getSnowflakeNextId());
        clinicPrescription.setOrderNo(orderNo);
        if (clinicPrescriptionService.save(clinicPrescription)) {
            if (clinicPrescription.getItems() != null && !clinicPrescription.getItems().isEmpty()) {
                for (ClinicPrescriptionItem item : clinicPrescription.getItems()) {
                    item.setPrescriptionId(clinicPrescription.getId());
                    item.setPrescriptionNo(orderNo);
                }
                clinicPrescriptionItemService.saveBatch(clinicPrescription.getItems());
            }
            // 返回处方数据，包含处方ID
            return success("添加成功", clinicPrescriptionService.getByLastId(clinicPrescription));
        }
        return fail("添加失败");
    }


    @Operation(summary = "修改处方主表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ClinicPrescription clinicPrescription) {
        if (clinicPrescriptionService.updateById(clinicPrescription)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }


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


    @Operation(summary = "批量添加处方主表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<ClinicPrescription> list) {
        if (clinicPrescriptionService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }


    @Operation(summary = "批量修改处方主表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicPrescription> batchParam) {
        if (batchParam.update(clinicPrescriptionService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }


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

    @Operation(summary = "创建处方订单")
    @PostMapping("/order")
    public ApiResult<?> createOrder(@RequestBody PrescriptionOrderRequest request) {
        try {
            // 1. 参数校验
            if (request.getPrescriptionId() == null) {
                return fail("处方ID不能为空");
            }
            if (request.getPayType() == null) {
                return fail("支付方式不能为空");
            }

            // 2. 查询处方信息
            ClinicPrescription prescription = clinicPrescriptionService.getById(request.getPrescriptionId());
            if (prescription == null) {
                return fail("处方不存在");
            }

            // 3. 检查处方状态
            if (prescription.getStatus() != null && prescription.getStatus() == 2) {
                return fail("该处方已支付，无需重复支付");
            }
            if (prescription.getStatus() != null && prescription.getStatus() == 3) {
                return fail("该处方已取消，无法支付");
            }

            // 4. 更新处方订单信息
            ClinicPrescription updatePrescription = new ClinicPrescription();
            updatePrescription.setId(request.getPrescriptionId());

            // 根据支付类型更新状态
            if (request.getPayType() == 1) {
                // 微信支付，状态保持为正常，等待支付回调
                updatePrescription.setStatus(0);
            } else if (request.getPayType() == 4 || request.getPayType() == 5) {
                // 现金支付或POS机支付，直接标记为已支付
                updatePrescription.setStatus(2);
                updatePrescription.setIsSettled(1);
                updatePrescription.setSettleTime(LocalDateTime.now());
            } else if (request.getPayType() == 6) {
                // 免费，直接标记为已完成
                updatePrescription.setStatus(1);
                updatePrescription.setIsSettled(1);
                updatePrescription.setSettleTime(LocalDateTime.now());
            }

            if (clinicPrescriptionService.updateById(updatePrescription)) {
                return success("订单创建成功", prescription);
            }
            return fail("订单创建失败");

        } catch (Exception e) {
            return fail("订单创建失败：" + e.getMessage());
        }
    }

}
