package com.ylx.web.controller.massage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylx.common.core.controller.BaseController;
import com.ylx.common.core.domain.R;
import com.ylx.common.utils.SecurityUtils;
import com.ylx.common.utils.StringUtils;
import com.ylx.massage.domain.CancelOrderApplication;
import com.ylx.massage.domain.TJs;
import com.ylx.massage.domain.TOrder;
import com.ylx.massage.domain.vo.CancelOrderApplicationDetailVo;
import com.ylx.massage.enums.OrderStatusEnum;
import com.ylx.massage.service.CancelOrderApplicationService;
import com.ylx.massage.service.TJsService;
import com.ylx.massage.service.TOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 退单申请控制器
 *
 * @author jinshihui
 */
@Slf4j
@RestController
@RequestMapping("api/order/cancelOrderApplication")
@Api(tags = "退单申请")
public class CancelOrderApplicationController extends BaseController {

    @Resource
    private CancelOrderApplicationService cancelOrderApplicationService;

    @Resource
    private TOrderService orderService;

    @Resource
    private TJsService jsService;


    /**
     * 分页查询退单申请列表
     *
     * @param page                   分页对象
     * @param cancelOrderApplication 查询条件
     * @return R<Page < CancelOrderApplication>>分页结果
     */
    @GetMapping("list")
    @ApiOperation("分页查询退单申请列表")
    public R<Page<CancelOrderApplication>> queryByPage(Page<CancelOrderApplication> page, CancelOrderApplication cancelOrderApplication) {
        try {
            log.info("开始查询退单申请列表，查询条件：{}", JSON.toJSONString(cancelOrderApplication));

            // 构建查询条件
            LambdaQueryWrapper<CancelOrderApplication> queryWrapper = new LambdaQueryWrapper<>();
            // 订单号模糊查询
            queryWrapper.like(StringUtils.isNotBlank(cancelOrderApplication.getOrderNo()),
                    CancelOrderApplication::getOrderNo, cancelOrderApplication.getOrderNo());
            // 技师姓名模糊查询
            queryWrapper.like(StringUtils.isNotBlank(cancelOrderApplication.getTechName()),
                    CancelOrderApplication::getTechName, cancelOrderApplication.getCName());
            // 技师电话模糊查询
            queryWrapper.like(StringUtils.isNotBlank(cancelOrderApplication.getTechPhone()),
                    CancelOrderApplication::getTechPhone, cancelOrderApplication.getCPhone());
            // 技师昵称模糊查询
            queryWrapper.like(StringUtils.isNotBlank(cancelOrderApplication.getTechNickName()),
                    CancelOrderApplication::getTechNickName, cancelOrderApplication.getCNickName());
            // 用户电话模糊查询
            queryWrapper.like(StringUtils.isNotBlank(cancelOrderApplication.getUserPhone()),
                    CancelOrderApplication::getUserPhone, cancelOrderApplication.getUserPhone());
            // 审核状态精确查询（0：待审核，1：已审核，2：已取消）
            queryWrapper.eq(cancelOrderApplication.getAuditStatus() != null,
                    CancelOrderApplication::getAuditStatus, cancelOrderApplication.getAuditStatus());
            // 申请时间范围查询（开始时间到结束时间）
            queryWrapper.between(org.apache.commons.lang3.StringUtils.isNotBlank(cancelOrderApplication.getStartTime()) && org.apache.commons.lang3.StringUtils.isNotBlank(cancelOrderApplication.getEndTime()),
                    CancelOrderApplication::getApplicationTime, cancelOrderApplication.getStartTime(), cancelOrderApplication.getEndTime());
            // 按申请时间倒序排列（最新的申请在前）
            queryWrapper.orderByDesc(CancelOrderApplication::getApplicationTime);
            // 执行分页查询
            Page<CancelOrderApplication> pageResult = cancelOrderApplicationService.page(page, queryWrapper);
            log.info("查询退单申请列表成功，共查询到{}条记录", pageResult.getTotal());
            pageResult.getRecords().forEach(application -> {
                application.setCName(application.getTechName());
                application.setCNickName(application.getTechNickName());
                application.setCPhone(application.getTechPhone());
            });
            return R.ok(pageResult);
        } catch (Exception e) {
            log.error("查询退单申请列表失败", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }


    /**
     * 根据主键ID查询订单详情
     *
     * @param id
     * @return R<CancelOrderApplicationDetailVo> 订单详情
     */
    @ApiOperation("根据主键ID查询订单详情")
    @GetMapping(value = "/getByOrderId")
    public R<CancelOrderApplicationDetailVo> getByOrderId(@RequestParam("id") String id) {
        try {
            if (StringUtils.isBlank(id)) {
                return R.fail("ID不能为空");
            }
            //通过主键ID查询退单申请信息
            CancelOrderApplication application = cancelOrderApplicationService.getById(id);
            if (application == null) {
                return R.fail("退单申请不存在");
            }
            String orderId = application.getOrderId();
            TOrder order = orderService.getById(orderId);
            if (order == null) {
                return R.fail("订单不存在");
            }
            CancelOrderApplicationDetailVo vo = new CancelOrderApplicationDetailVo();
            BeanUtils.copyProperties(order, vo);
            vo.setId(id);
            Integer status = vo.getnStatus();
            vo.setStatusName(OrderStatusEnum.getDescByCode(status));

            //获取技师ID
            String techId = order.getcJsId();
            //根据技师ID查询技师信息
            TJs tech = jsService.getById(techId);
            vo.setJsName(tech.getcName());
            vo.setCNickName(tech.getcNickName());
            vo.setJsPhone(tech.getcPhone());

            // 设置服务时长（分钟）
            vo.setServiceDuration(application.getServiceDuration());
            JSONArray objects = order.getcGoods();
            // 遍历商品列表，累加项目金额
            BigDecimal projectPrice = BigDecimal.ZERO;
            StringBuffer projectNameBuffer = new StringBuffer();
            //项目时长
            BigDecimal projectDuration = new BigDecimal(0);
            for (int i = 0; i < objects.size(); i++) {
                JSONObject object = objects.getJSONObject(i);
                BigDecimal price = object.getBigDecimal("dPrice");
                projectPrice = projectPrice.add(price);
                projectNameBuffer.append(object.getString("cTitle")).append(" ");
                projectDuration = projectDuration.add(object.getBigDecimal("nMinute"));
            }
            // 设置退单原因
            vo.setCancelOrderReason(application.getCancelOrderReason());
            // 设置项目名称
            vo.setProjectName(projectNameBuffer.toString().trim());
            // 设置项目时长
            vo.setProjectDuration(projectDuration.intValue());
            // 设置项目金额
            vo.setProjectPrice(projectPrice);
            // 设置退款金额
            vo.setRefundAmount(application.getRefundAmount());
            return R.ok(vo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 审核退单申请
     *
     * @param cancelOrderApplicationDetailVo 退单申请详情
     * @return R<CancelOrderApplication> 审核结果
     */
    @ApiOperation("审核退单申请")
    @PostMapping("/audit")
    public R audit(@RequestBody CancelOrderApplication cancelOrderApplication) {
        try {
            if (StringUtils.isBlank(cancelOrderApplication.getId())) {
                return R.fail("退单申请ID不能为空");
            }
            // 检查申请是否存在
            CancelOrderApplication application = cancelOrderApplicationService.getById(cancelOrderApplication.getId());
            if (application == null) {
                return R.fail("退单申请不存在");
            }
            //检查当前审核状态是否为待审核
            if (application.getAuditStatus() != 0) {
                return R.fail("退单申请当前状态不是待审核");
            }

            // 审核退单申请
            application.setRefundAmount(cancelOrderApplication.getRefundAmount());
            application.setAuditRemark(cancelOrderApplication.getAuditRemark());
            application.setOrderStatus(8);
            application.setAuditStatus(cancelOrderApplication.getAuditStatus());
            // 审核通过，更新订单状态为退单审核通过
            if (application.getAuditStatus() == 1) {
                // 更新订单状态
                TOrder order = new TOrder();
                order.setcId(application.getOrderId());
                order.setnStatus(8);
                orderService.updateById(order);
            }
            // 审核时间
            application.setAuditTime(LocalDateTime.now());
            // 审核人ID
            application.setAuditUserId(SecurityUtils.getUserId().toString());
            // 审核人姓名
            application.setAuditUserName(SecurityUtils.getUsername());
            boolean b = cancelOrderApplicationService.updateById(application);
            if (!b) {
                return R.fail("审核退单申请失败");
            }
            return R.ok("审核退单申请成功");
        } catch (Exception e) {
            log.error("审核退单申请失败，申请ID：{}", cancelOrderApplication.getId(), e);
            return R.fail("审核退单申请失败：" + e.getMessage());
        }
    }


    /**
     * 根据主键ID查询退单申请详情
     *
     * @param id 退单申请ID
     * @return R<CancelOrderApplication> 退单申请详情
     */
    @GetMapping("{id}")
    @ApiOperation("查询退单申请详情")
    public R<CancelOrderApplication> queryById(@PathVariable("id") String id) {
        try {
            if (StringUtils.isBlank(id)) {
                return R.fail("退单申请ID不能为空");
            }
            CancelOrderApplication application = cancelOrderApplicationService.getById(id);
            if (application == null) {
                return R.fail("退单申请不存在");
            }
            return R.ok(application);
        } catch (Exception e) {
            log.error("查询退单申请详情失败，申请ID：{}", id, e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }
}
