package com.fs.hisStore.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fs.common.core.redis.RedisCache;
import com.fs.company.service.ICompanyService;
import com.fs.company.vo.RedPacketMoneyVO;
import com.fs.course.mapper.FsCourseRedPacketLogMapper;
import com.fs.erp.domain.ErpDeliverys;
import com.fs.erp.domain.ErpOrderQuery;
import com.fs.erp.dto.ErpOrderQueryRequert;
import com.fs.erp.dto.ErpOrderQueryResponse;
import com.fs.erp.service.IErpOrderService;
import com.fs.his.config.FsSysConfig;
import com.fs.his.dto.ExpressInfoDTO;
import com.fs.his.service.IFsExpressService;
import com.fs.his.service.IFsUserService;
import com.fs.his.utils.ConfigUtil;
import com.fs.hisStore.domain.FsStoreProductAttrValueScrm;
import com.fs.hisStore.dto.DateComparisonConfigDTO;
import com.fs.hisStore.enums.ShipperCodeEnum;
import com.fs.hisStore.mapper.FsStoreProductAttrValueScrmMapper;
import com.fs.hisStore.param.FsStoreOrderAddTuiMoneyParam;
import com.fs.hisStore.service.IFsStoreProductScrmService;
import com.fs.live.domain.LiveAfterSales;
import com.fs.live.domain.LiveOrder;
import com.fs.live.domain.LiveOrderItem;
import com.fs.live.domain.LiveOrderPayment;
import com.fs.live.mapper.LiveOrderItemMapper;
import com.fs.live.mapper.LiveOrderMapper;
import com.fs.live.mapper.LiveOrderPaymentMapper;
import com.fs.live.param.LiveAfterSalesAudit1Param;
import com.fs.live.param.LiveAfterSalesParam;
import com.fs.live.param.LiveAfterSalesProductParam;
import com.fs.live.service.*;
import com.fs.pay.pay.dto.OrderQueryDTO;
import com.fs.pay.service.IPayService;
import com.fs.store.config.StoreConfig;
import com.fs.system.service.ISysConfigService;
import com.fs.ybPay.domain.OrderResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.ParseException;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import static com.fs.hisStore.constants.StoreConstants.DELIVERY;

/**
 * 定时任务调度测试
 *
 * @author fs
 */
@Slf4j
@Component("liveTask")
public class LiveTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ILiveOrderService liveOrderService;

    @Autowired
    private ILiveCouponService liveCouponService;

    @Autowired
    private ILiveCouponIssueService liveCouponIssueService;
    @Autowired
    private IFsStoreProductScrmService fsStoreProductScrmService;

    @Autowired
    private ILiveAfterSalesService liveAfterSalesService;

    @Autowired
    private ILiveOrderItemService liveOrderItemService;

    @Autowired
    private ILiveOrderPaymentService liveOrderPaymentService;

    @Autowired
    private IFsUserService userService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    @Qualifier("erpOrderServiceImpl")
    private IErpOrderService gyOrderService;

    @Autowired
    @Qualifier("wdtErpOrderServiceImpl")
    private IErpOrderService wdtOrderService;

    @Autowired
    @Qualifier("hzOMSErpOrderServiceImpl")
    private IErpOrderService hzOMSOrderService;

    @Autowired
    @Qualifier("dfOrderServiceImpl")
    private IErpOrderService dfOrderService;

    @Autowired
    @Qualifier("JSTErpOrderServiceImpl")
    private IErpOrderService jSTOrderService;

    @Autowired
    @Qualifier("k9OrderScrmServiceImpl")
    private IErpOrderService k9OrderService;

    @Autowired
    private ConfigUtil configUtil;

    @Autowired
    IErpOrderService erpOrderService;

    @Autowired
    private LiveOrderMapper liveOrderMapper;

    @Autowired
    private LiveOrderItemMapper liveOrderItemMapper;

    @Autowired
    private LiveOrderPaymentMapper liveOrderPaymentMapper;

    @Autowired
    private IPayService ybPayService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IFsExpressService expressService;

    @Autowired
    private FsCourseRedPacketLogMapper fsCourseRedPacketLogMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void PushErp() throws ParseException {
        List<Long> ids = liveOrderMapper.selectOrderIdByNoErp();
        for (Long id : ids) {
            liveOrderService.createOmsOrder(id);
        }
    }

    public void redPacketSubMoney() throws Exception {
        List<RedPacketMoneyVO> redPacketMoneyVOS = fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogByCompany();
        for (RedPacketMoneyVO redPacketMoneyVO : redPacketMoneyVOS) {
            companyService.subtractCompanyMoney(redPacketMoneyVO.getMoney(), redPacketMoneyVO.getCompanyId());
        }
    }

    public void redPacketAddMoney() throws Exception {
        List<RedPacketMoneyVO> redPacketMoneyVOS = fsCourseRedPacketLogMapper.selectFsCourseAddRedPacketLogByCompany();
        for (RedPacketMoneyVO redPacketMoneyVO : redPacketMoneyVOS) {
            companyService.addRedPacketCompanyMoney(redPacketMoneyVO.getMoney(), redPacketMoneyVO.getCompanyId());
        }
    }


    //定时任务刷新微信订单结算状态
    public void refreshOrderSettlementStatus(){
        liveOrderService.refreshOrderSettlementStatus();
    }



    //每5分钟执行一次
    public void deliveryOp() {
        List<LiveOrder> list = liveOrderService.selectUpdateExpress();
        for (LiveOrder order : list) {
            ErpOrderQueryRequert request = new ErpOrderQueryRequert();
            request.setCode(order.getExtendOrderId());
            IErpOrderService erpOrderService = getErpOrderService();
            ErpOrderQueryResponse response = erpOrderService.getLiveOrder(request);
            if (erpOrderService != dfOrderService) {
                if (response.getOrders() != null && !response.getOrders().isEmpty()) {
                    for (ErpOrderQuery orderQuery : response.getOrders()) {
                        if (orderQuery.getDeliverys() != null && orderQuery.getDeliverys().size() > 0) {
                            for (ErpDeliverys delivery : orderQuery.getDeliverys()) {
                                if (delivery.getDelivery() && StringUtils.isNotEmpty(delivery.getMail_no())) {
                                    //更新商订单状态 删除REDIS
                                    liveOrderService.deliveryOrder(order.getOrderCode(), delivery.getMail_no(), delivery.getExpress_code(), delivery.getExpress_name());
                                    redisCache.deleteObject(DELIVERY + ":" + order.getExtendOrderId());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public void couponOp() {
        // 直播优惠券过期处理，如果有对应方法则调用
        // liveCouponService.updateFsCouponByExpire();
    }

    //退款自动处理 24小时未审核自动审核通过 每小时执行一次
    public void refundOp() {
        //获取所有退款申请
        List<LiveAfterSales> list = liveAfterSalesService.selectLiveAfterSalesByDoAudit();
        if (list != null) {
            for (LiveAfterSales afterSales : list) {
                //仅退款
                if (afterSales.getRefundType().equals(0)) {
                    LiveAfterSalesAudit1Param audit1Param = new LiveAfterSalesAudit1Param();
                    audit1Param.setSalesId(afterSales.getId());
                    audit1Param.setOperator("平台");
                    liveAfterSalesService.audit1(audit1Param);
                }
            }
        }
    }

    //每天执行一次
    public void userMoneyOp() {
        // 直播订单完成7天后给用户返现，如果有对应方法则调用
        // List<LiveOrder> list = liveOrderService.selectLiveOrderListByFinish7Day();
        // if (list != null) {
        //     for (LiveOrder order : list) {
        //         userService.addMoney(order);
        //     }
        // }
    }

    //每30秒执行一次
    public void orderItemSyncOp() {
//         同步订单项JSON，如果有对应方法则调用
         List<LiveOrder> list = liveOrderService.selectLiveOrderItemJson();
         for (LiveOrder storeOrder : list) {
             LiveOrderItem parmOrderItem = new LiveOrderItem();
             parmOrderItem.setOrderId(storeOrder.getOrderId());
             List<LiveOrderItem> listOrderItem = liveOrderItemService.selectLiveOrderItemList(parmOrderItem);
             if (listOrderItem.size() > 0) {
                 String itemJson = JSONUtil.toJsonStr(listOrderItem);
                 storeOrder.setItemJson(itemJson);
                 liveOrderMapper.updateLiveOrderItemJson(storeOrder);
             }
         }
    }

    public void returnDeliveryId() {
        IErpOrderService erpOrderService = getErpOrderService();
        // 获取ERP订单号列表，如果有对应方法则调用
        // List<String> list = liveOrderMapper.selectErpCode();
        // for (String s : list) {
        //     ErpOrderQueryRequert request = new ErpOrderQueryRequert();
        //     request.setCode(s);
        //     ErpOrderQueryResponse response = erpOrderService.getOrder(request);
        //     if (response.getOrders() != null && response.getOrders().size() > 0) {
        //         for (ErpOrderQuery orderQuery : response.getOrders()) {
        //             if (orderQuery.getDeliverys() != null && orderQuery.getDeliverys().size() > 0) {
        //                 for (ErpDeliverys delivery : orderQuery.getDeliverys()) {
        //                     if (delivery.getDelivery() && StringUtils.isNotEmpty(delivery.getMail_no())) {
        //                         LiveOrder order = new LiveOrder();
        //                         order.setExtendOrderId(s);
        //                         order.setDeliverySn(delivery.getMail_no());
        //                         order.setStatus(2);
        //                         liveOrderMapper.updateDelivery(order);
        //                     }
        //                 }
        //             }
        //         }
        //     }
        // }
    }

    public void changeStatus() {
//         获取需要更新物流状态的订单ID列表，如果有对应方法则调用
//         List<Long> list = liveOrderMapper.selectOrderId();
//         for (Long orderId : list) {
//             LiveOrder order = liveOrderMapper.selectLiveOrderByOrderId(String.valueOf(orderId));
//             String lastFourNumber = "";
//             if (order.getDeliverySn() != null && order.getDeliverySn().equals(ShipperCodeEnum.SF.getValue())) {
//                 lastFourNumber = order.getUserPhone();
//                 if (lastFourNumber != null && lastFourNumber.length() == 11) {
//                     lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
//                 }
//             }
//             ExpressInfoDTO dto = expressService.getExpressInfo(order.getOrderCode(), order.getDeliverySn(), order.getDeliverySn(), lastFourNumber);
//             LiveOrder map = new LiveOrder();
//             map.setDeliveryStatus(Integer.parseInt(dto.getState()));
//             map.setOrderId(orderId);
//             map.setDeliveryType(dto.getStateEx());
//             liveOrderMapper.updateLiveOrder(map);
//         }
    }

    public void subCompanyMoney() {
        // 获取需要扣减公司金额的支付ID列表，如果有对应方法则调用
        // List<Long> list = liveOrderPaymentMapper.selectPaymentIds();
        // for (Long paymentId : list) {
        //     LiveOrderPayment payment = liveOrderPaymentService.selectLiveOrderPaymentByPaymentId(paymentId);
        //     if (payment.getCompanyId() != null && payment.getCompanyId() > 0) {
        //         companyService.subCompanyPaymentMoney(payment);
        //     }
        // }
    }

    public void updateOrderItem() throws ParseException {
        List<Long> ids = liveOrderService.selectOrderIdByNoErp();
        for (Long id : ids) {
            liveOrderService.createOmsOrder(id);
        }
    }

    //每天执行一次
    public void syncExpress() {
        List<Long> ids = liveOrderService.selectSyncExpressIds();
        for (Long id : ids) {
            liveOrderService.syncExpress(id);
        }
    }

    public void returnPayStatus() {
        // 获取需要查询支付状态的支付ID列表，如果有对应方法则调用
        // List<String> ids = liveOrderPaymentMapper.selectPayStatusIds();
        // for (String id : ids) {
        //     OrderQueryDTO o = new OrderQueryDTO();
        //     o.setUpOrderId(id);
        //     OrderResult orderResult = ybPayService.getOrder(o);
        //     if ("0".equals(orderResult.getState())) {
        //         String[] order = orderResult.getLowOrderId().split("-");
        //         if (orderResult.getStatus().equals("100")) {
        //             switch (order[0]) {
        //                 case "live":
        //                     liveOrderService.payConfirm(1, null, order[1], o.getUpOrderId(), orderResult.getBankTrxId(), orderResult.getBankOrderId());
        //                 case "live_remain":
        //                     liveOrderService.payConfirm(1, null, order[1], o.getUpOrderId(), orderResult.getBankTrxId(), orderResult.getBankOrderId());
        //                 case "payment":
        //                     liveOrderPaymentService.payConfirm(order[1], o.getUpOrderId(), orderResult.getBankTrxId(), orderResult.getBankOrderId());
        //             }
        //         }
        //     }
        // }
    }

    public void AddTuiMoney() {
        // 获取需要添加推荐金额的订单ID列表，如果有对应方法则调用
        // List<Long> ids = liveOrderMapper.selectAddTuiMoney();
        // for (Long id : ids) {
        //     FsStoreOrderAddTuiMoneyParam param = new FsStoreOrderAddTuiMoneyParam();
        //     param.setOrderId(id);
        //     liveOrderService.addTuiMoney(param);
        // }
    }

    public void selectPayMoneyLessOne() {
        // 获取支付金额小于1的订单列表，如果有对应方法则调用
        // List<LiveOrder> list = liveOrderMapper.selectPayMoneyLessOne();
        // for (LiveOrder order : list) {
        //     LiveAfterSalesParam param = new LiveAfterSalesParam();
        //     param.setOrderCode(order.getOrderCode());
        //     param.setServiceType(0);
        //     param.setRefundAmount(order.getPayMoney());
        //     param.setReasons("超时未处理，自动申请退款");
        //     List<LiveAfterSalesProductParam> productParams = new ArrayList<>();
        //     List<LiveOrderItem> items = liveOrderItemMapper.selectLiveOrderItemByOrderId(order.getOrderId());
        //     for (LiveOrderItem item : items) {
        //         LiveAfterSalesProductParam param1 = new LiveAfterSalesProductParam();
        //         param1.setProductId(item.getProductId());
        //         param1.setNum(item.getNum());
        //         productParams.add(param1);
        //     }
        //     param.setProductList(productParams);
        //     liveAfterSalesService.applyForAfterSales(order.getUserId(), param);
        // }
    }

    public void deleteCustomer() {
        // 删除客户逻辑
    }

    private IErpOrderService getErpOrderService() {
        //判断是否开启erp
        IErpOrderService erpOrderService = null;
        FsSysConfig erpConfig = configUtil.getSysConfig();
        Integer erpOpen = erpConfig.getErpOpen();
        if (erpOpen != null && erpOpen == 1) {
            //判断erp类型
            Integer erpType = erpConfig.getErpType();
            if (erpType != null) {
                if (erpType == 1) {
                    //管易
                    erpOrderService = gyOrderService;
                } else if (erpType == 2) {
                    //旺店通
                    erpOrderService = wdtOrderService;
                } else if (erpType == 3) {
                    //代服
                    erpOrderService = hzOMSOrderService;
                } else if (erpType == 4) {
                    //瀚智
                    erpOrderService = dfOrderService;
                } else if (erpType == 5) {
                    erpOrderService = jSTOrderService;
                } else if (erpType == 6) {
                    erpOrderService = k9OrderService;
                }
            }
        }
        return erpOrderService;
    }

    /**
     * 提醒证件到期任务
     */
    public void remindCertValidation() {
        log.info("提醒店铺证件到期任务执行... 当前时间: {}", LocalTime.now());

        // 从配置表获取需要比较的表和字段
        List<DateComparisonConfigDTO> tablesToCheck = jdbcTemplate.query(
                "SELECT table_name, date_column,in_advance,user_column,phone_column,remind_words,platform,cert_type" +
                        " FROM date_comparison_config", (rs, rowNum) -> {
                    return DateComparisonConfigDTO.builder()
                            .tableName(rs.getString("table_name"))//表名
                            .certType(rs.getString("cert_type"))//证件类型
                            .dateColumn(rs.getString("date_column"))//日期字段
                            .userColumn(rs.getString("user_column"))//用户字段
                            .remindWords(rs.getString("remindWords"))//提醒内容
                            .phoneColumn(rs.getString("phone_column"))//提醒手机
                            .inAdvance(rs.getInt("inAdvance"))//提前天数
                            .platform(rs.getString("platform")).build();//平台
                });

        tablesToCheck.forEach(dto -> {
            //获取证件失效日期字段小于当前时间加提前天数的用户和电话号码
            String sql = String.format("SELECT %s , %s " +
                            "FROM %s " +
                            "WHERE %s >= DATE_SUB(CURDATE(), INTERVAL %d DAY)",
                    dto.getUserColumn(),
                    dto.getPhoneColumn(),
                    dto.getTableName(),
                    dto.getDateColumn(),
                    dto.getInAdvance()
            );
            List<Map<String, Object>> users = jdbcTemplate.queryForList(sql);
            users.forEach(user -> {
                String userName = (String) user.get(dto.getUserColumn());
                String phone = (String) user.get(dto.getPhoneColumn());
                String remindWords = String.format("【%s平台提示】尊敬的%s用户，店铺%s证件即将到期，请及时处理！",
                        dto.getPlatform(),
                        userName,
                        dto.getCertType());
                // 使用phone发送remindWords短信
                // TODO 发送通知
            });
        });
    }

    /**
     * 禁用店铺
     */
    public void disable() {
        log.info("禁用店铺任务执行... 当前时间: {}", LocalTime.now());
        // 从配置表获取需要禁用的表和字段
        List<DateComparisonConfigDTO> toDisable = jdbcTemplate.query(
                "SELECT table_name, date_column,invalid_expression,status_column" +
                        " FROM date_comparison_config " +
                        " WHERE is_do_invalid = '1'", (rs, rowNum) -> DateComparisonConfigDTO.builder()
                        .tableName(rs.getString("table_name"))//表名
                        .dateColumn(rs.getString("date_column"))//日期字段
                        .invalidExpression(rs.getString("invalid_expression"))//失效表达式
                        .statusColumn(rs.getString("status_column"))//状态字段
                        .build());

        toDisable.forEach(dto -> {
            //更新证件失效日期字段小于当前时间的数据
            String sql = String.format("UPDATE %s " +
                            "SET %s = %s " +
                            "WHERE %s < CURDATE()",
                    dto.getTableName(),
                    dto.getStatusColumn(),
                    dto.getInvalidExpression(),
                    dto.getDateColumn());
            jdbcTemplate.update(sql);
        });
    }

    public void getOrderDeliveryStatus() {
        IErpOrderService erpOrderService = getErpOrderService();
        List<LiveOrder> orders = null;
        if (erpOrderService != null && erpOrderService == dfOrderService) {
            // 获取已发货订单列表，如果有对应方法则调用
             orders = liveOrderMapper.selectShippedOrder();
             if (orders != null && !orders.isEmpty()) {
                 List<CompletableFuture<Void>> futures = new ArrayList<>();
                 for (LiveOrder order : orders) {
                     CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                         erpOrderService.getOrderLiveDeliveryStatus(order);
                     });
                     futures.add(future);
                 }
                 CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
             }
        }
    }
}
