package com.jwipc.shopping.controller.pc;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.shopping.constant.ModuleConst;
import com.jwipc.shopping.dto.ShoppingAfterSalesDTO;
import com.jwipc.shopping.entity.ShoppingAfterSalesInfo;
import com.jwipc.shopping.logic.OnlineMallLogic;
import com.jwipc.shopping.model.po.ShoppingAfterSalesPO;
import com.jwipc.shopping.model.po.ShoppingCartInfoPO;
import com.jwipc.shopping.model.query.MyAfterSalesQuery;
import com.jwipc.shopping.model.query.OnlineMallCartQuery;
import com.jwipc.shopping.model.vo.*;
import com.jwipc.util.DateUtils;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 功能描述:
 *
 * @Author: zx
 * @Date: 2024/3/15 0015 9:46
 */
@RestController
@RequestMapping(ModuleConst.MODULE_ROOT + "/myAfterSale/rest")
@RequiredArgsConstructor
@Slf4j
public class MyAfterSalesRestController {

    @Autowired
    OnlineMallLogic onlineMallLogic;

    /**
     * 订单列表查询
     *
     * @return 结果
     */
    @AuditLogInter(value = "列表查询", module = "我的售后")
    @RequestMapping("/findMyAfterSalesPage")
    public PageView findMyAfterSalesPage(MyAfterSalesQuery query) {
//        if (!LoginUtil.getAccount().equals("admin")) {
//            query.setUserId(LoginUtil.getUserId());
//        }
        return onlineMallLogic.findMyAfterSalesPage(query);
    }
    /**
     * 备注保存更新
     * @param param 参数
     */
    @PostMapping("/noteSave")
    public ResponseEntity noteSave(ShoppingAfterSalesInfo param){
        onlineMallLogic.noteSave(param);
        return ResponseEntity.ok(true);
    }
    /**
     * 售后申请保存
     * @param param 参数
     */
    @PostMapping("/afterSale/saveOrUpdate")
    public ResponseEntity saveOrUpdate(@RequestBody ShoppingAfterSalesDTO param){
        onlineMallLogic.afSaveOrUpdate(param);
        return ResponseEntity.ok(true);
    }

    /**
     * 售后申请提交
     * @param param 参数
     */
    @PostMapping("/afterSale/submit")
    public ResponseEntity submit(@RequestBody ShoppingAfterSalesDTO param){
        onlineMallLogic.submit(param);
        return ResponseEntity.ok(true);
    }

    /**
     * 配额维护导出
     * @param exportFiled 导出的列信息
     * @param queryStr 查询条件
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final List<OnlineMallCart> exportData = onlineMallLogic.listAllExport(JSON.parseObject(queryStr, OnlineMallCartQuery.class));
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"购物订单导出-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, exportFiled);
    }
    /**
     * 发货单物流查询
     *
     * @return 结果
     */
    @RequestMapping("/orderTrackDetailList")
    public PageView orderTrackDetailList(String packageId) {
        OrderTrackResponse response = onlineMallLogic.requestMiddleOrderTrack(packageId);
        Page<OrderTrackDetail> page = new Page<>();
        List<OrderTrackDetail> list = null;
        if (response != null) {
            OrderTrackDto orderTrackDto = response.getResult();
            if (orderTrackDto != null) {
                list = orderTrackDto.getOrderTrack();
            }
        }
        return PageUtil.getPV(list, page.getTotal());

    }


    /***
     * 确认商城订单
     *
     * @param id 购物订单ID
     * @return 结果
     */
    @PostMapping("/confirm/mall/order")
    public ResponseEntity<?> confirmMallOrder(Long id) {
        if (ObjectUtil.isNull(id)) {
            return ResponseEntity.badRequest().body(" 参数错误, 请联系管理员 ");
        }
        return ResponseEntity.ok(onlineMallLogic.confirmMallOrder(id));
    }

    /***
     * 商城取消订单
     *
     * @param id 购物订单ID
     * @return 结果
     */
    @PostMapping("/delOrder")
    public ResponseEntity<?> delOrder(Long id, String orderId) {
        if (ObjectUtil.isEmpty(orderId)) {
            return ResponseEntity.badRequest().body("商城回传的订单号为空，参数错误, 请联系管理员 ");
        }
        DelOrderResponse delOrder = onlineMallLogic.delOrder(id, orderId);
        if (delOrder == null) {
            return ResponseEntity.badRequest().body("取消订单接口调用异常");
        }
        return ResponseEntity.ok(onlineMallLogic.delOrder(id, orderId));
    }


    /**
     * 获取订单明细
     */
    @ResponseBody
    @RequestMapping("/detail/list")
    public List<ShoppingCartInfoPO> detailList(Long cartId) {
        return onlineMallLogic.detailListPagePO(cartId);
    }


    /**
     * 根据商城订单ID获取商城订单主表数据
     */
    @ResponseBody
    @RequestMapping("/find/by/id")
    public ResponseEntity findHeadById(Long cartId) {
        OnlineMallCart cart = onlineMallLogic.findHeadById(cartId);
        return ResponseEntity.ok(cart);
    }


    @RequestMapping("/form/submitReceiptNum")
    @Transactional
    public ResponseEntity formPayData(String rows, Long cartId) {
        onlineMallLogic.updateReceiptStatus(cartId, rows);
        return ResponseEntity.ok(true);
    }


    @RequestMapping("/form/excelShopCart")
    public ResponseEntity excelShopCart(@RequestPart("files") MultipartFile files) {
        List<ExcelShopCartVO> shopCartVOS = null;
        try {
            shopCartVOS = onlineMallLogic.excelShopCart(files.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.ok(shopCartVOS);
    }


    /**
     * 售后列表导出
     * @param exportFiled 导出的列信息
     * @param queryStr 查询条件
     */
    @PostMapping("/AsExport")
    public void AsExport(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final List<ShoppingAfterSalesPO> exportData = onlineMallLogic.exportMyAfterSalesPage(JSON.parseObject(queryStr, MyAfterSalesQuery.class));
        exportFiled = exportFiled.replace("createTime","createTimeStr");
        exportData.stream().forEach(item -> {
            item.setCreateTimeStr(DateUtils.formatYYYYMMDDDash(item.getCreateTime()));
        });
        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"售后明细导出-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, exportFiled);
    }
}
