package com.yami.shop.platform.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.dto.OrderRefundDto;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.BackendOrderParam;
import com.yami.shop.bean.param.OrderRefundCountParam;
import com.yami.shop.bean.param.OrderRefundStaisticsParam;
import com.yami.shop.bean.vo.OrderRefundSkuVo;
import com.yami.shop.bean.vo.OrderRefundVo;
import com.yami.shop.common.config.Constant;
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.*;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.ExportTaskService;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单退款管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2018-09-15
 */
@Api(tags = "订单退款管理")
@RestController
@AllArgsConstructor
@RequestMapping("/platform/orderRefund")
public class OrderRefundController {

    private final OrderRefundService orderRefundService;
    private final OrderRefundSkuMapper orderRefundskuMapper;
    private final OrderItemMapper orderItemMapper;
    private final OrderRefundRecordMapper orderRefundRecordMapper;

    private final RefundAppointmentMapper refundAppointmentMapper;
    private final RefundDeliveryMapper refundDeliveryMapper;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ExportTaskService exportTaskService;
    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param orderRefundDto 实体对象
     * @return 分页数据
     */
    @GetMapping("/page")
//    @PreAuthorize("@pms.hasPermission('platform:orderRefund:page')")
    public R<IPage<OrderRefundDto>> getOrderRefundPage(PageParam<OrderRefundDto> page, OrderRefundDto orderRefundDto,
                                                       @RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime) {
        return R.SUCCESS(orderRefundService.getPage(page, orderRefundDto, startTime, endTime));
    }

    /**
     * 通过id查询
     *
     * @param refundId id
     * @return 查询详细信息
     */
//    @GetMapping("/info")
////    @PreAuthorize("@pms.hasPermission('platform:orderRefund:info')")
//    public R<OrderRefund> info(@RequestParam("refundId") Long refundId, @RequestParam("shopId") Long shopId) {
//        OrderRefund orderRefund = orderRefundService.getOrderRefundById(refundId, shopId);
//        return R.SUCCESS(orderRefund);
//    }

    /**
     * 通过ID查询详情
     */
    @GetMapping("/orderRefundInfo/{refundId}")
    @ApiOperation(value = "查看退款订单详情", notes = "查看退款订单详情")
    public R<OrderRefundVo> orderRefundInfo(@PathVariable("refundId") Long refundId) {
        OrderRefundVo orderRefundVo = orderRefundService.selectInfoById(refundId);

        //获取申请退款轨迹
        List<OrderRefundRecord> orderRefundRecords = orderRefundRecordMapper.selectList(new LambdaQueryWrapper<OrderRefundRecord>()
                .eq(OrderRefundRecord::getOrderRefundId, refundId)
                .orderByDesc(OrderRefundRecord::getSort));
        orderRefundVo.setOrderRefundRecordList(orderRefundRecords);

        Integer dvyType = orderRefundVo.getDvyType();
        if (dvyType == 1){
            // 1:快递 2:自提 3：及时配送
            RefundDelivery refundDelivery = refundDeliveryMapper.selectOne(new LambdaQueryWrapper<RefundDelivery>()
                    .eq(RefundDelivery::getRefundSn, orderRefundVo.getRefundSn()));
            orderRefundVo.setRefundDelivery(refundDelivery);
        }else {
            RefundAppointment refundAppointment = refundAppointmentMapper.selectOne(new LambdaQueryWrapper<RefundAppointment>()
                    .eq(RefundAppointment::getRefundNumber, orderRefundVo.getRefundSn()));
            orderRefundVo.setRefundAppointment(refundAppointment);
        }

        List<OrderRefundSkuVo> orderRefundSkuVos = orderRefundskuMapper.selectByRefundId(refundId);
        orderRefundSkuVos.forEach(c -> c.setOrderItem(orderItemMapper.selectById(c.getOrderItemId())));
        orderRefundVo.setOrderRefundSkuList(orderRefundSkuVos);
        return R.SUCCESS(orderRefundVo);
    }

    /**
     * 后管端分页获取退款订单列表
     */
    @ApiOperation("后台分页获取退款订单列表")
    @GetMapping("/orderRefundPage")
    public R<IPage<OrderRefundVo>> orderRefundPage(PageParam<OrderRefund> page, OrderRefundStaisticsParam orderRefund) {
        getOrderRefundStaisticsParam(orderRefund);
        IPage<OrderRefundVo> page1 = orderRefundService.orderRefundPage(page, orderRefund);
        for (OrderRefundVo record : page1.getRecords()) {
            record.setOrderRefundSkuList(orderRefundskuMapper.selectByRefundId(record.getRefundId()));
        }
        return R.SUCCESS(page1);
    }

    /**
     * 统计退款订单数量
     */
    @ApiOperation("统计退款订单数量")
    @GetMapping("/orderRefundCount")
    public R<OrderRefundCountParam> orderRefundCount(OrderRefundStaisticsParam orderRefund) {
        getOrderRefundStaisticsParam(orderRefund);
        return R.SUCCESS(orderRefundService.orderRefundCount(orderRefund));
    }

    /**
     * 导出
     * @param orderRefund
     * @param response
     */
    @GetMapping("/export")
    @ApiOperation("后管端-退款订单列表导出")
    public R<String> export(OrderRefundStaisticsParam orderRefund, HttpServletResponse response) {
        getOrderRefundStaisticsParam(orderRefund);
        Long userId = null;
        try {
            userId = SecurityUtils.getSysUser().getUserId();
        } catch (Exception e) {
            throw new GlobalException("导出获取当前登录用户失败");
        }
        if (ObjectUtil.isEmpty(userId)){
            throw new GlobalException("导出获取当前登录用户信息失败,请登录");
        }
        ExportTask exportTaskOne =  exportTaskService.findByUserIdAndStatusAndType(userId,0,2);//查询导出任务为退款订单并且在进行中的数据
        // 异步执行
        if (exportTaskOne!=null){
            return R.FAIL("售后订单有导出任务正在执行中,请中断或者等待完成");
        }
        return orderRefundService.export(orderRefund,userId);
    }

    private void getOrderRefundStaisticsParam(OrderRefundStaisticsParam orderRefund){
        if (orderRefund.getChannelIdList()==null||orderRefund.getChannelIdList().isEmpty()){
            throw new GlobalException("请求参数-所属企业不允许为空");
        }
        if (ObjectUtil.isEmpty(orderRefund.getUserAttrType())){
            orderRefund.setUserAttrType("1");//默认查询正常人员属性
        }
        if (orderRefund.getChannelIdList().contains(0L)){
            Long userId = null;
            try {
                userId = SecurityUtils.getSysUser().getUserId();
            } catch (Exception e) {
                throw new GlobalException("获取当前登录用户失败");
            }
            List<Long> channelIdList =  sysUserService.findByUserIdListId(userId);
            orderRefund.setChannelIdList(channelIdList);
            if (userId != Constant.SUPER_ADMIN_ID&&(orderRefund.getChannelIdList()==null||orderRefund.getChannelIdList().isEmpty())){
                List<Long> longs = new ArrayList<>();
                longs.add(0L);
                orderRefund.setChannelIdList(longs);
            }
        }
    }
}
