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.dto.ExportDataDTO;
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.logic.OnlineMallLogic;
import com.jwipc.shopping.model.po.ShoppingCartInfoPO;
import com.jwipc.shopping.model.query.OnlineMallCartQuery;
import com.jwipc.shopping.model.vo.*;
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.ArrayList;
import java.util.Date;
import java.util.List;

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

    @Autowired
    OnlineMallLogic onlineMallLogic;

    /**
     * 订单列表查询
     *
     * @return 结果
     */
    @AuditLogInter(value = "列表查询数据", module = "商城购物订单")
    @RequestMapping("/findByCartPage")
    public PageView findByCartPage(OnlineMallCartQuery query) {
//        if (!LoginUtil.getAccount().equals("admin")) {
//            query.setUserId(LoginUtil.getUserId());
//        }
        return onlineMallLogic.findByCartPage(query);

    }

    /**
     * 订单明细列表查询
     *
     * @return 结果
     */
    @RequestMapping("/findInfoByCartPage")
    public PageView findInfoByCartPage(OnlineMallCartQuery query) {
//        if (!LoginUtil.getAccount().equals("admin")) {
//            query.setUserId(LoginUtil.getUserId());
//        }
        return onlineMallLogic.findInfoByCartPage(query);

    }

    /**
     * 售后申请保存
     * @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("/cancel/mall/order")
    public ResponseEntity<?> confirmMallOrder2(Long id) {
        if (ObjectUtil.isNull(id)) {
            return ResponseEntity.badRequest().body(" 参数错误, 请联系管理员 ");
        }
        return ResponseEntity.ok(onlineMallLogic.confirmMallOrder2(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));
    }

    /**
     * 删除
     *
     * @param id 参数
     */
    @PostMapping("/remove")
    public ResponseEntity remove(Long id) {
        onlineMallLogic.remove(id);
        return ResponseEntity.ok(true);
    }
    /**
     * 获取订单明细
     */
    @ResponseBody
    @RequestMapping("/detail/list")
    public List<ShoppingCartInfoPO> detailList(Long cartId) {
        return onlineMallLogic.detailListPage(cartId);
    }
    /**
     * 获取订单明细
     */
    @ResponseBody
    @RequestMapping("/detailPO/list")
    public List<ShoppingCartInfoPO> detailListPO(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);
    }

    /**
     * 是否线下取消
     *
     * @return 页面
     */
    @PostMapping("/callOff")
    public ResponseEntity whether(Long id, Integer whetherCallOff){
        onlineMallLogic.whetherCallOff(id,whetherCallOff);
        //return ResponseEntity.ok("操作成功");
        return ResponseEntity.ok(true);
    }

    /**
     * 明细导出
     * @param queryStr 查询条件
     */
    @PostMapping("/detail/export")
    public void priceExport(HttpServletResponse response, String queryStr) throws IOException {
        List<ExportDataDTO> exportDataDTOS = new ArrayList<>();
        //先加载固定字段
//        exportDataDTOS.add(ExportDataDTO.builder().title("").field("factoryCode").build());
//        exportDataDTOS.add(ExportDataDTO.builder().title("物料凭证号").field("mvCode").build());
//        exportDataDTOS.add(ExportDataDTO.builder().title("行号").field("mvItemNo").build());
//        exportDataDTOS.add(ExportDataDTO.builder().title("其他折扣").field("deductionRatio").color(IndexedColors.YELLOW.getIndex()).build());
        exportDataDTOS.add(ExportDataDTO.builder().title("订单号").field("thirdOrder").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("商城来源").field("storeName").build());//主表
        exportDataDTOS.add(ExportDataDTO.builder().title("商城返回订单号").field("orderId").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("收货状态").field("receiptStatusText").build());//收货表
        exportDataDTOS.add(ExportDataDTO.builder().title("创建时间").field("createTime").exportDateFormatter("dateTime").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("收货人").field("receivingUser").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("收货人电话").field("receivingTel").build());

//        exportDataDTOS.add(ExportDataDTO.builder().title("省/市/地区").field("provinceName + / + cityName + / + countyName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("省/市/地区").field("provinceCityCounty").build());

        exportDataDTOS.add(ExportDataDTO.builder().title("详细地址").field("address").build());//收货表
        exportDataDTOS.add(ExportDataDTO.builder().title("采购组织").field("pgoName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("采购组").field("pgName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("工厂").field("factoryName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("发货状态").field("deliveryStatusText").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("商城名称").field("storeName").build());//info表
        exportDataDTOS.add(ExportDataDTO.builder().title("商品名称").field("skuName").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("单价").field("unitCost").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("单位").field("unit").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("商品数量").field("qty").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("请购数量").field("requireNum").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("收货数量").field("receiptNum").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("收货时间").field("receivedTime").exportDateFormatter("dateTime").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("退货数量").field("returnQuatity").build());//售后明细表


        exportDataDTOS.add(ExportDataDTO.builder().title("采购申请单号").field("prCode").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("OA流程单号").field("purchaseOrderNumber").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("发货单号").field("packageId").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("发票号").field("invoiceNumber").build());
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        OnlineMallCartQuery query = JSON.parseObject(queryStr, OnlineMallCartQuery.class);
        final List<OnlineMallCart> exportData = onlineMallLogic.selectDataExport1(query);

        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,"购物订单明细-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN),"sheet", exportData, JSON.toJSONString(exportDataDTOS));
    }


    }
