package com.yami.shop.api.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.ReturnMoneyStsType;
import com.yami.shop.bean.model.OrderRefund;
import com.yami.shop.bean.model.OrderRefundRecord;
import com.yami.shop.bean.model.RefundAddr;
import com.yami.shop.bean.model.RefundDelivery;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.dao.OrderRefundRecordMapper;
import com.yami.shop.dao.ShopDetailMapper;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.service.RefundAddrService;
import com.yami.shop.service.RefundDeliveryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

/**
 * 退货物流信息接口
 */
@RestController
@RequestMapping("/refund/delivery")
@Api(tags = "退货物流信息接口")
@Slf4j
@AllArgsConstructor
public class RefundDeliveryController {

    private final RefundDeliveryService refundDeliveryService;
    private final RefundAddrService refundAddrService;
    private final OrderRefundService orderRefundService;
    private final OrderRefundRecordMapper orderRefundRecordMapper;
    private final ShopDetailMapper shopDetailMapper;

    /**
     * 分页获取退货物流信息列表
     */
    @GetMapping("/page")
    @ApiOperation("分页获取退货物流信息列表")
    public R<IPage<RefundDelivery>> page(PageParam<RefundDelivery> pageParam, RefundDelivery refundDelivery) {
        IPage<RefundDelivery> refundDeliveryPage = refundDeliveryService.page(pageParam, new LambdaQueryWrapper<RefundDelivery>());
        return R.SUCCESS(refundDeliveryPage);
    }

    /**
     * 根据退款编号获取退货物流信息
     */
    @GetMapping("/getByRefundSn/{refundSn}")
    @ApiOperation("根据退款编号获取退货物流信息")
    public R<RefundDelivery> getByRefundSn(@PathVariable("refundSn") String refundSn) {
        RefundDelivery refundDelivery = refundDeliveryService.getOne(new LambdaQueryWrapper<RefundDelivery>().eq(RefundDelivery::getRefundSn, refundSn));
        if (ObjectUtil.isEmpty(refundDelivery)){
            return R.SUCCESS(new RefundDelivery());
        }
        return R.SUCCESS(refundDelivery);
    }

    /**
     * 根据ID获取退货物流信息
     */
    @GetMapping("/getById/{id}")
    @ApiOperation("根据ID获取退货物流信息")
    public R<RefundDelivery> getById(@PathVariable Long id) {
        RefundDelivery refundDelivery = refundDeliveryService.getById(id);
        return R.SUCCESS(refundDelivery);
    }

    /**
     * 保存退货物流信息
     */
    @PostMapping("/save")
    @ApiOperation("保存退货物流信息")
    @Transactional(rollbackFor = Exception.class)
    public synchronized R<?> save(@Valid @RequestBody RefundDelivery refundDelivery) {


        //获取门店信息
        RefundAddr refundAddr = refundAddrService.getOne(new LambdaQueryWrapper<RefundAddr>()
        .eq(RefundAddr::getShopId, refundDelivery.getShopId())
        .eq(RefundAddr::getDefaultAddr, 1)
        .eq(RefundAddr::getStatus, 1));
        if (ObjectUtil.isNotEmpty(refundAddr)) {
            //门店信息获取地址
            String shopAddress = refundAddr.getProvince() + refundAddr.getCity() + refundAddr.getArea() + refundAddr.getAddr();
            refundDelivery.setReceiverAddr(shopAddress);
            refundDelivery.setReceiverName(refundAddr.getReceiverName());
            refundDelivery.setReceiverMobile(refundAddr.getReceiverMobile());
            refundDelivery.setCreateTime(new Date());
            refundDeliveryService.save(refundDelivery);
        }
        //添加填写物流信息轨迹
        OrderRefund orderRefund = orderRefundService.getOne(new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getRefundSn, refundDelivery.getRefundSn()));

        if (ObjectUtil.isEmpty( orderRefund)){
            throw new GlobalException("该退款单不存在");
        }

        if (orderRefund.getReturnMoneySts() != 60) {
            throw new GlobalException("该退款单状态不对不能提交");
        }

        orderRefund.setReturnMoneySts(ReturnMoneyStsType.RECEIVE.value());
        orderRefund.setShipTime(new Date());
        orderRefund.setUpdateTime(new Date());
        orderRefund.setIsReturnLogistics(true);
        orderRefundService.updateById(orderRefund);

        OrderRefundRecord orderRefundRecord = new OrderRefundRecord();
        orderRefundRecord.setOrderRefundId(orderRefund.getRefundId());
        orderRefundRecord.setInstructions("商家收到商品井确认不影响二次销售后，将会为您处理退款");
        Date date = new Date();
        orderRefundRecord.setCreateTime(date);
        orderRefundRecord.setUpdateTime(date);
        orderRefundRecord.setAuditStatus(7);
        orderRefundRecord.setSort(5);
        orderRefundRecordMapper.insert(orderRefundRecord);

        log.info("客户填写完成快递信息后海博退款单状态同步65");
        orderRefundService.changeStatus(orderRefund.getRefundSn(), ReturnMoneyStsType.RECEIVE.value());

        return R.SUCCESS("添加成功");
    }

    /**
     * 更新退货物流信息
     */
    @PutMapping("/update")
    @ApiOperation("更新退货物流信息")
    public R<String> update(@Valid @RequestBody RefundDelivery refundDelivery) {
        RefundDelivery dbRefundDelivery = refundDeliveryService.getById(refundDelivery.getRefundDeliveryId());
        if (dbRefundDelivery == null) {
            return R.FAIL("退货物流信息不存在");
        }

        refundDeliveryService.updateById(refundDelivery);
        return R.SUCCESS("更新成功");
    }


    /**
     * 删除退货物流信息
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除退货物流信息")
    public R<String> delete(@PathVariable Long id) {
        RefundDelivery refundDelivery = refundDeliveryService.getById(id);
        if (refundDelivery == null) {
            return R.FAIL("退货物流信息不存在");
        }

        refundDeliveryService.removeById(id);
        return R.SUCCESS("删除成功");
    }
}
