package com.fs.live.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.CloudHostUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.his.domain.FsStoreOrderDf;
import com.fs.his.vo.FsStoreOrderListAndStatisticsVo;
import com.fs.hisStore.dto.StoreOrderProductDTO;
import com.fs.hisStore.param.FsStoreOrderParam;
import com.fs.hisStore.vo.FsStoreOrderErpExportVO;
import com.fs.hisStore.vo.FsStoreOrderExportVO;
import com.fs.hisStore.vo.FsStoreOrderItemExportVO;
import com.fs.live.domain.LiveOrderDf;
import com.fs.live.dto.LiveOrderDeliveryNoteDTO;
import com.fs.live.param.LiveOrderParam;
import com.fs.live.service.ILiveOrderDfService;
import com.fs.live.service.ILiveOrderItemService;
import com.fs.live.service.ILiveOrderService;
import com.fs.live.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

/**`
 * 订单Controller
 *
 * @author fs
 * @date 2025-07-08
 */
@RestController
@RequestMapping("/live/liveOrder")
public class LiveHealthOrderController extends BaseController {

    @Autowired
    private ILiveOrderService liveOrderService;
    @Autowired
    private ILiveOrderItemService orderItemService;

    @Autowired
    private ILiveOrderDfService liveOrderDfService;

    @PreAuthorize("@ss.hasPermi('store:healthStoreOrder:exportItems:details')")
    @Log(title = "商城订单明细导出", businessType = BusinessType.EXPORT)
    @GetMapping("/healthExportItemsDetails")
    public AjaxResult healthExportItemsDetails(LiveOrderParam param) {
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (liveOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        param.setIsHealth("1");
        List<LiveOrderItemExportVO> list = orderItemService.selectLiveOrderItemListExportVO(param);
        //对手机号脱敏
        if (list != null) {
            for (LiveOrderItemExportVO vo : list) {
                if (!StringUtils.isEmpty(vo.getJsonInfo())) {
                    try {
                        StoreOrderProductDTO orderProductDTO = JSONObject.parseObject(vo.getJsonInfo(), StoreOrderProductDTO.class);
                        BeanUtil.copyProperties(orderProductDTO, vo);
                    } catch (Exception e) {
                    }
                }
            }
        }
        ExcelUtil<LiveOrderItemExportVO> util = new ExcelUtil<LiveOrderItemExportVO>(LiveOrderItemExportVO.class);
        return util.exportExcel(list, "订单明细数据");
    }


    /**
     * 导出健康商城列表（明文）
     */
    @PreAuthorize("@ss.hasPermi('store:healthStoreOrder:export:details')")
    @Log(title = "健康商城订单", businessType = BusinessType.EXPORT)
    @PostMapping("/healthExportDetails")
    public AjaxResult healthExportDetails(@RequestBody LiveOrderParam param) {
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (liveOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        param.setIsHealth("1");
        List<LiveOrderErpExportVO> list = liveOrderService.selectLiveOrderListVOByExport(param);
        String filter = param.getFilter();
        // 1. 处理filter参数：将逗号分隔的字符串拆分为ArrayList<String>
        ArrayList<String> filterList = new ArrayList<>();
        if (StringUtils.isNotBlank(filter)) {
            // 按逗号拆分，同时去除可能的空格（如filter传"orderId, orderCode"时兼容）
            String[] filterArr = filter.split("\\s*,\\s*");
            filterList.addAll(Arrays.asList(filterArr));
        }
        // 动态导出：根据选中的字段生成Excel
        ExcelUtil<LiveOrderErpExportVO> util = new ExcelUtil<LiveOrderErpExportVO>(LiveOrderErpExportVO.class);
        AjaxResult result;
        // 如果有选中的字段，只导出这些字段
        if (filter != null && !filter.isEmpty()) {
            return util.exportExcelSelectedColumns(list, "订单数据", filterList);
        } else {
            // 导出所有字段
            return util.exportExcel(list, "订单数据");
        }
    }

    /**
     * 导出健康商城列表
     */
    @PreAuthorize("@ss.hasPermi('live:healthLiveOrder:export')")
    @Log(title = "健康商城订单", businessType = BusinessType.EXPORT)
    @PostMapping("/healthExport")
    public AjaxResult export1(@RequestBody LiveOrderParam param) {
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (liveOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        param.setIsHealth("1");
        List<LiveOrderErpExportVO> list = liveOrderService.selectLiveOrderListVOByExport(param);
        //对手机号脱敏
        if (list != null) {
            for (LiveOrderErpExportVO vo : list) {
                if (vo.getPhone() != null) {
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (vo.getUserPhone() != null) {
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }

            }
        }
        String filter = param.getFilter();
        // 1. 处理filter参数：将逗号分隔的字符串拆分为ArrayList<String>
        ArrayList<String> filterList = new ArrayList<>();
        if (StringUtils.isNotBlank(filter)) {
            // 按逗号拆分，同时去除可能的空格（如filter传"orderId, orderCode"时兼容）
            String[] filterArr = filter.split("\\s*,\\s*");
            filterList.addAll(Arrays.asList(filterArr));
        }
        // 动态导出：根据选中的字段生成Excel
        ExcelUtil<LiveOrderErpExportVO> util = new ExcelUtil<LiveOrderErpExportVO>(LiveOrderErpExportVO.class);
        AjaxResult result;
        // 如果有选中的字段，只导出这些字段
        if (filter != null && !filter.isEmpty()) {
            return util.exportExcelSelectedColumns(list, "订单数据", filterList);
        } else {
            // 导出所有字段
            return util.exportExcel(list, "订单数据");
        }
    }

    /**
     * 查询健康商城订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:healthLiveOrder:list')")
    @PostMapping("/healthList")
    public TableDataInfo healthStoreList(@RequestBody LiveOrderParam param) {
        startPage();
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        param.setIsHealth("1");
        List<LiveOrderVO> list = liveOrderService.selectLiveOrderListVO(param);
        //金牛需求 区别其他项目 status = 6 (金牛代服管家) ,其他项目请避免使用订单状态status = 6
        TableDataInfo dataTable = getDataTable(list);
        if (CloudHostUtils.hasCloudHostName("康年堂")){
            dataTable.setMsg("knt");
        }
        if (list != null) {
            for (LiveOrderVO vo : list) {
                if(vo.getPhone()!=null){
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
                if (CloudHostUtils.hasCloudHostName("康年堂")){
                    //查询顺丰代服账号
                    LiveOrderDf df = liveOrderDfService.selectLiveOrderDfByOrderId(vo.getId());
                    if (df != null){
                        vo.setErpAccount(df.getLoginAccount());
                    }
                }

            }
        }
        LiveOrderListAndStatisticsVo vo = new LiveOrderListAndStatisticsVo();
        BeanUtils.copyProperties(dataTable, vo);
        if (dataTable.getTotal()>0){
            Map<String, BigDecimal> statistics= liveOrderService.selectLiveOrderStatistics(param);
            if (statistics != null && statistics.size() >= 3){
                vo.setPayPriceTotal(statistics.get("pay_price").toString());
                vo.setPayMoneyTotal(statistics.get("pay_money").toString());
                vo.setPayRemainTotal(statistics.get("pay_remain").toString());
            }else {
                vo.setPayPriceTotal("0");
                vo.setPayMoneyTotal("0");
                vo.setPayRemainTotal("0");
            }
            //商品数量合计
            String productStatistics= liveOrderService.selectLiveOrderProductStatistics(param);
            if (StringUtils.isNotBlank(productStatistics)){
                vo.setProductInfo(productStatistics);
            } else {
                vo.setProductInfo("");
            }

        }
        return vo;
    }

    @PreAuthorize("@ss.hasPermi('live:healthLiveOrder:exportItems')")
    @Log(title = "直播订单明细导出", businessType = BusinessType.EXPORT)
    @GetMapping("/healthExportItems")
    public AjaxResult exportItems1(LiveOrderParam param) {
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())){
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (liveOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getPayTimeRange())){
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        param.setIsHealth("1");
        List<LiveOrderItemExportVO> list = orderItemService.selectLiveOrderItemListExportVO(param);
        //对手机号脱敏
        if (list != null) {
            for (LiveOrderItemExportVO vo : list) {
                if (vo.getUserPhone() != null) {
                    String phone = vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2");
                    vo.setUserPhone(phone);
                }
                if (!StringUtils.isEmpty(vo.getJsonInfo())) {
                    try {
                        StoreOrderProductDTO orderProductDTO = JSONObject.parseObject(vo.getJsonInfo(), StoreOrderProductDTO.class);
                        BeanUtil.copyProperties(orderProductDTO, vo);
                    } catch (Exception e) {
                    }
                }
            }
        }
        ExcelUtil<LiveOrderItemExportVO> util = new ExcelUtil<LiveOrderItemExportVO>(LiveOrderItemExportVO.class);
        return util.exportExcel(list, "订单明细数据");
    }



    // 允许的文件扩展名
    private static final String[] ALLOWED_EXCEL_EXTENSIONS = {".xlsx", ".xls"};

    // 最大文件大小（5MB）
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

    /**
     * 下载订单发货导入模板
     */
    @GetMapping("/importDeliveryNoteExpressTemplate")
    public AjaxResult importDeliveryNoteExpressTemplate() {
        ExcelUtil<LiveOrderDeliveryNoteDTO> util = new ExcelUtil<>(LiveOrderDeliveryNoteDTO.class);
        return util.importTemplateExcel("订单发货导入模板");
    }

    /**
     * 订单发货批量导入
     */
    @Log(title = "发货同步导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importDeliveryNoteExpress")
    public R importDeliveryNoteExpress(@RequestParam("file") MultipartFile file, @RequestParam("miniAppId") String miniAppId) {
        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            return R.error("上传的文件不能为空");
        }
        // 2. 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return R.error("文件大小不能超过5MB");
        }
        // 3. 检查文件扩展名
        String fileName = file.getOriginalFilename();
        if (fileName == null || !isValidExcelFile(fileName)) {
            return R.error("请上传Excel文件（.xlsx或.xls格式）");
        }

        ExcelUtil<LiveOrderDeliveryNoteDTO> util = new ExcelUtil<>(LiveOrderDeliveryNoteDTO.class);
        try {
            List<LiveOrderDeliveryNoteDTO> dtoList = util.importExcel(file.getInputStream());
            if (!dtoList.isEmpty()) {
                if (dtoList.size() > 200) {
                    return R.error("操作失败，导入数据不能大于200条！");
                }
                return liveOrderService.importDeliveryNoteExpress(dtoList,miniAppId);
            } else {
                return R.error("操作失败，导入数据不能小于1条！");
            }
        } catch (Exception e) {
            logger.error("导入发货单失败", e);
            return R.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 发货单导出接口
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:healthExportShippingOrder')")
    @Log(title = "发货单导出", businessType = BusinessType.EXPORT)
    @GetMapping("/healthExportShippingOrder")
    public AjaxResult healthExportShippingOrder(LiveOrderParam param) {
        if ("".equals(param.getBeginTime()) && "".equals(param.getEndTime())) {
            param.setBeginTime(null);
            param.setEndTime(null);
        }
        if (liveOrderService.isEntityNull(param)) {
            param = new LiveOrderParam();
        }
        if (!StringUtils.isEmpty(param.getCreateTimeRange())) {
            param.setCreateTimeList(param.getCreateTimeRange().split("--"));
        }
        if (!StringUtils.isEmpty(param.getPayTimeRange())) {
            param.setPayTimeList(param.getPayTimeRange().split("--"));
        }
        if (!StringUtils.isEmpty(param.getDeliverySendTimeRange())) {
            param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
        }
        if (!StringUtils.isEmpty(param.getDeliveryImportTimeRange())) {
            param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
        }
        List<LiveOrderDeliveryNoteExportVO> deliveryNoteExportVOList = liveOrderService.getDeliveryNote(param);
        ExcelUtil<LiveOrderDeliveryNoteExportVO> util = new ExcelUtil<>(LiveOrderDeliveryNoteExportVO.class);
        //通过商品ID获取关键字
        String firstKeyword = deliveryNoteExportVOList.stream()
                .map(LiveOrderDeliveryNoteExportVO::getKeyword)
                .findFirst()
                .orElse("无订单");
        String fileName = "077AC" + firstKeyword + new java.text.SimpleDateFormat("yyyyMMdd").format(new Date());
        return util.exportExcel(deliveryNoteExportVOList, fileName);
    }

    /**
     * 检查文件是否为有效的Excel文件
     */
    private boolean isValidExcelFile(String fileName) {
        for (String ext : ALLOWED_EXCEL_EXTENSIONS) {
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }
}
