package shop.alien.second.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.BusinessException;
import shop.alien.entity.result.R;
import shop.alien.entity.second.SecondTradeRecord;
import shop.alien.entity.second.vo.SecondEntrustUserDTO;
import shop.alien.entity.second.vo.SecondTradeRecordVo;
import shop.alien.entity.second.vo.SellerEvaluationVo;
import shop.alien.second.service.SecondTradeRecordService;

import java.util.List;

/**
 * <p>
 * 二手交易记录表 前端控制器
 * </p>
 *
 * @author qrs
 * @since 2025-07-07
 */
@Slf4j
@Api(tags = {"二手平台-商品交易记录"})
@ApiSort(1)
@CrossOrigin
@RequiredArgsConstructor
@RestController
@RequestMapping("/secondTradeRecord")
public class SecondTradeRecordController {

    private final SecondTradeRecordService secondTradeRecordService;

    @ApiOperation("创建交易")
    @ApiOperationSupport(order = 1)
    @PostMapping("/createTrade")
    public R<Boolean> createTrade(@RequestBody SecondEntrustUserDTO entity) throws Exception {
        log.info("SecondTradeRecordController.createTrade?entity={}", entity.toString());
        if (secondTradeRecordService.createTrade(entity)) return R.success("创建成功");
        return R.fail("创建失败");
    }

    @ApiOperation("确认商品是否可以交易")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({@ApiImplicitParam(name = "goodsId", value = "商品id", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/goodsTradeConfirm")
    public R<Boolean> goodsTradeConfirm(@RequestParam int goodsId) throws Exception {
        log.info("SecondTradeRecordController.goodsTradeConfirm?goodsId={}", goodsId);
        return R.data(secondTradeRecordService.goodsTradeConfirm(goodsId));
    }

    @ApiOperation("确认/拒绝交易")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tradeId", value = "交易id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "messageId", value = "消息id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "0-拒绝  1-确认", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/tradeConfirm")
    public R<Boolean> tradeConfirm(@RequestParam int tradeId, @RequestParam int messageId, @RequestParam int type) {
        log.info("SecondTradeRecordController.tradeConfirm?tradeId={}, messageId={}, type={}", tradeId, messageId, type);
        try {
            secondTradeRecordService.tradeConfirm(tradeId, messageId, type);
            return R.success("操作成功");
        } catch (BusinessException e) {
            return R.fail(e.getCause().getMessage());
        }  catch (Exception e) {
            return R.fail("系统繁忙,请稍后再试");
        }
    }

    @ApiOperation("取消交易")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tradeId", value = "交易id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "cancelReason", value = "取消原因", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "cancelReasonSupplement", value = "取消原因补充", dataType = "String", paramType = "query")})
    @GetMapping("/cancelTrade")
    public R<Boolean> cancelTrade(@RequestParam int tradeId, @RequestParam String cancelReason, String cancelReasonSupplement) throws Exception {
        log.info("SecondTradeRecordController.cancelTrade?tradeId={}, cancelReason={}, cancelReasonSupplement={}", tradeId, cancelReason, cancelReasonSupplement);
        if (secondTradeRecordService.cancelTrade(tradeId, cancelReason, cancelReasonSupplement)) return R.success("取消交易成功");
        return R.fail("取消交易失败");
    }

    @ApiOperation("交易是否可以签到")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({@ApiImplicitParam(name = "tradeId", value = "交易id", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/whetherCanSignIn")
    public R<Boolean> whetherCanSignIn(@RequestParam int tradeId) throws Exception {
        log.info("SecondTradeRecordController.whetherCanSignIn?tradeId={}", tradeId);
        return R.data(secondTradeRecordService.whetherCanSignIn(tradeId));
    }

    @ApiOperation("交易签到")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tradeId", value = "交易id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "messageId", value = "消息id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "signInLatitudeLongitude", value = "签到地点(经纬度)", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "signInLatitudeLongitudeAddress", value = "签到地点(经纬度地址)", dataType = "String", paramType = "query", required = true)})
    @GetMapping("/tradeSignIn")
    public R<Boolean> tradeSignIn(@RequestParam int tradeId, int messageId, String signInLatitudeLongitude, String signInLatitudeLongitudeAddress) {
        log.info("SecondTradeRecordController.tradeSignIn?tradeId={}, messageId={}", tradeId, messageId);
        try {
            secondTradeRecordService.tradeSignIn(tradeId, messageId, signInLatitudeLongitude, signInLatitudeLongitudeAddress);
            return R.success("签到成功");
        } catch (BusinessException e) {
            return R.fail(e.getCause().getMessage());
        }  catch (Exception e) {
            return R.fail("系统繁忙,请稍后再试");
        }
    }

    @ApiOperation("交易完成确认")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tradeId", value = "交易id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "1-交易成功  2-交易失败", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "evaluate", value = "评价", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "rating", value = "评分", dataType = "Integer", paramType = "query")})
    @GetMapping("/tradeCompleteConfirm")
    public R<Boolean> tradeCompleteConfirm(@RequestParam int tradeId, @RequestParam int type, String evaluate, Integer rating) throws Exception {
        log.info("SecondTradeRecordController.tradeCompleteConfirm?tradeId={}, type={}, evaluate={}, rating={}", tradeId, type, evaluate, rating);
        return R.data(secondTradeRecordService.tradeCompleteConfirm(tradeId, type, evaluate, rating));
    }

    @ApiOperation("获取用户交易确认信息")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({@ApiImplicitParam(name = "tradeId", value = "交易id", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/getUserTradeStatus")
    public R<SecondTradeRecordVo> getUserTradeStatus(@RequestParam int tradeId) throws Exception {
        log.info("SecondTradeRecordController.getUserTradeStatus?tradeId={}", tradeId);
        return R.data(secondTradeRecordService.getUserTradeStatus(tradeId));
    }

    @ApiOperation("交易窗")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({@ApiImplicitParam(name = "sideId", value = "对方的id", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/getTradeRecord")
    public R<List<SecondTradeRecordVo>> getTradeRecord(@RequestParam int sideId) throws Exception {
        log.info("SecondTradeRecordController.getTradeRecord?sideId={}", sideId);
        return R.data(secondTradeRecordService.getTradeRecord(sideId));
    }

    @ApiOperation("双方是否有交易中的状态")
    @ApiOperationSupport(order = 10)
    @ApiImplicitParams({@ApiImplicitParam(name = "sideId", value = "对方的id", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/hasInTradeRecord")
    public R<SecondTradeRecord> hasInTradeRecord(@RequestParam int sideId) throws Exception {
        log.info("SecondTradeRecordController.hasInTradeRecord?sideId={}", sideId);
        return R.data(secondTradeRecordService.hasInTradeRecord(sideId));
    }

    @ApiOperation("修改交易信息")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "1-确认  2-拒绝", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/modifyTradeRecord")
    public R<Boolean> modifyTradeRecord(int type, Integer tradeId, String transactionTime,
                                        String transactionLatitudeLongitude,
                                        String transactionLatitudeLongitudeAddress,
                                        String transactionLocation,
                                        String messageId, String entrustUserPhone, String entrustUserName, String entrustIdCard, Integer entrustId, String entrustIdCardImg) throws Exception {
        log.info("SecondTradeRecordController.modifyTradeRecord?record={}", transactionTime);
        return R.data(secondTradeRecordService.modifyTradeRecord(type, tradeId, transactionTime, transactionLatitudeLongitude, transactionLatitudeLongitudeAddress, transactionLocation, messageId, entrustUserPhone, entrustUserName, entrustIdCard, entrustId, entrustIdCardImg));
    }

    @ApiOperation("获取用户作为卖家的交易评价列表（分页）")
    @ApiOperationSupport(order = 12)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sellerId", value = "卖家id（用户主页展示用，必传）", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer", paramType = "query", required = false, defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "Integer", paramType = "query", required = false, defaultValue = "10")
    })
    @GetMapping("/getSellerEvaluationList")
    public R<IPage<SellerEvaluationVo>> getSellerEvaluationList(
            @RequestParam(required = true) Integer sellerId,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        log.info("SecondTradeRecordController.getSellerEvaluationList?sellerId={}, pageNum={}, pageSize={}", 
                sellerId, pageNum, pageSize);
        try {
            IPage<SellerEvaluationVo> evaluationPage = secondTradeRecordService.getSellerEvaluationList(sellerId, pageNum, pageSize);
            return R.data(evaluationPage);
        } catch (Exception e) {
            log.error("SecondTradeRecordController.getSellerEvaluationList?error: {}", e.getMessage(), e);
            return R.fail("获取评价列表失败: " + e.getMessage());
        }
    }

    @ApiOperation("加入定位")
    @ApiOperationSupport(order = 13)
    @ApiImplicitParams({@ApiImplicitParam(name = "otherUserId", value = "对方userId", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/locationShareAdd")
    public R<String> locationShareAdd(Integer otherUserId) throws Exception {
        log.info("SecondTradeRecordController.locationShareAdd?otherUserId={}", otherUserId);
        secondTradeRecordService.locationShareAdd(otherUserId);
        return R.data("操作成功");
    }

    @ApiOperation("退出定位")
    @ApiOperationSupport(order = 14)
    @ApiImplicitParams({@ApiImplicitParam(name = "otherUserId", value = "对方userId", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/locationShareDel")
    public R<String> locationShareDel(Integer otherUserId) throws Exception {
        log.info("SecondTradeRecordController.locationShareDel?otherUserId={}", otherUserId);
        secondTradeRecordService.locationShareDel(otherUserId);
        return R.success("操作成功");
    }

    @ApiOperation("是否在定位里面")
    @ApiOperationSupport(order = 15)
    @ApiImplicitParams({@ApiImplicitParam(name = "otherUserId", value = "对方userId", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/locationShareHas")
    public R<Boolean> locationShareHas(Integer otherUserId) throws Exception {
        log.info("SecondTradeRecordController.locationShareHas?otherUserId={}", otherUserId);
        return R.data(secondTradeRecordService.locationShareHas(otherUserId));
    }
}
