package com.fs.task;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fs.common.annotation.QuartzRunnable;
import com.fs.common.core.redis.RedisCache;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.core.security.SecurityUtils;
import com.fs.erp.constant.ErpTypeConstant;
import com.fs.erp.domain.ErpDeliverys;
import com.fs.erp.domain.ErpGoods;
import com.fs.erp.domain.ErpOrderQuery;
import com.fs.erp.dto.*;
import com.fs.erp.service.IErpGoodsService;
import com.fs.erp.service.IErpOrderService;
import com.fs.erp.utils.ErpContextHolder;
import com.fs.store.config.StoreConfig;
import com.fs.store.domain.*;
import com.fs.store.dto.StoreProductGroupDTO;
import com.fs.store.enums.OrderLogEnum;
import com.fs.store.mapper.*;
import com.fs.store.param.*;
import com.fs.store.service.*;
import com.fs.store.vo.FsUserShareVO;
import com.fs.system.service.ISysConfigService;
import com.fs.wx.domain.FsWxExpressTask;
import com.fs.wx.mapper.FsWxExpressTaskMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

/**
 * 定时任务调度
 * @author fs
 */
@Component("storeTask")
public class StoreTask {
    Logger logger = LoggerFactory.getLogger(StoreTask.class);
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IFsStoreOrderService orderService;
    @Autowired
    private IFsStoreCouponUserService couponUserService;
    @Autowired
    private IFsStoreAfterSalesService afterSalesService;
    @Autowired
    private IFsUserService userService;

    @Autowired
    private FsStoreProductMapper fsStoreProductMapper;

    @Autowired
    private IErpOrderService erpOrderService;

    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;

    @Autowired
    private IFsStoreOrderService fsStoreOrderService;

    @Autowired
    private IFsStoreOrderItemService storeOrderItemService;

    @Autowired
    private FsUserTuiMoneyRankMapper fsUserTuiMoneyRankMapper;

    @Autowired
    private IErpGoodsService erpGoodsService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private FsStoreProductAttrValueMapper fsStoreProductAttrValueMapper;

    @Autowired
    private IFsStoreProductGroupService storeProductGroupService;

    @Autowired
    private IFsStoreAfterSalesService fsStoreAfterSalesService;

    @Autowired
    private FsStoreOrderItemMapper itemMapper;

    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private IFsStoreOrderStatusService orderStatusService;

    @Autowired
    private IFsExpressService expressService;

    @Autowired
    private IFsStorePaymentService fsStorePaymentService;


    @Autowired
    private FsWxExpressTaskMapper fsWxExpressTaskMapper;

    @Autowired
    private FsWarehousesMapper fsWarehousesMapper;

    /**
     * 发货任务
     */
    @QuartzRunnable(name = "发货任务")
    @Transactional
    public void deliveryOp() {
        List<FsStoreOrder> list = orderService.selectDeliverPenddingData();

        for (FsStoreOrder order: list) {
            String orderCode = order.getOrderCode();
            ErpOrderQueryRequert request = new ErpOrderQueryRequert();
            request.setCode(order.getExtendOrderId());
            // 根据仓库code找erp
            if(com.fs.common.utils.StringUtils.isNotBlank(order.getStoreHouseCode())){
                String erp = fsWarehousesMapper.selectErpByCode(order.getStoreHouseCode());
                ErpContextHolder.setErpType(erp);
            }
            ErpOrderQueryResponse response = erpOrderService.getOrder(request);
            if (CollectionUtils.isNotEmpty(response.getOrders())) {
                for (ErpOrderQuery orderQuery : response.getOrders()) {
                    if (CollectionUtils.isNotEmpty(orderQuery.getDeliverys())) {
                        // 部分发货或者全部发货
                        if (ObjectUtils.equals(orderQuery.getDelivery_state(), 1) || ObjectUtils.equals(orderQuery.getDelivery_state(), 2)) {

                            orderStatusService.create(order.getId(), OrderLogEnum.DELIVERY_GOODS.getValue(),
                                    OrderLogEnum.DELIVERY_GOODS.getDesc());

                            for (ErpDeliverys delivery : orderQuery.getDeliverys()) {

                                FsExpress express=expressService.selectFsExpressByOmsCode(delivery.getExpress_code());
                                if(express == null){
                                    logger.warn("当前express_code: {} 不存在!",delivery.getExpress_code());
                                    continue;
                                }

                                if (delivery.getDelivery()) {
                                    orderService.deliveryOrder(orderCode, delivery.getMail_no(),
                                            delivery.getExpress_code(), delivery.getExpress_name());
                                }
                            }

                            logger.info("订单 {} 发货信息同步成功",order.getOrderCode());
                        }
                    }
                }
            }
        }

    }

    /**
     * 佣金排行榜
     */
    @QuartzRunnable(name = "佣金排行榜")
    public void addUserTuiMoneyRank() {
        List<FsUserShareVO> fsUserShareVOS1 = fsUserTuiMoneyRankMapper.selectFsUserTuiMoneyRankByType(1);
        fsUserTuiMoneyRankMapper.deleteFsUserTuiMoneyRankByType(1);
        Long id = 1L;
        int rank = 1;
        for (FsUserShareVO vo : fsUserShareVOS1) {
            FsUserTuiMoneyRank userRank = new FsUserTuiMoneyRank();
            userRank.setAvatar(vo.getAvatar());
            userRank.setUserId(vo.getUserId());
            userRank.setTuiMoney(vo.getTuiMoney());
            userRank.setType(1);
            userRank.setId(id);
            userRank.setSort(rank);
            userRank.setNickname(vo.getNickname());
            userRank.setPhone(vo.getPhone());
            fsUserTuiMoneyRankMapper.insertFsUserTuiMoneyRank(userRank);
            rank++;
            id++;
        }


        List<FsUserShareVO> fsUserShareVOS2 = fsUserTuiMoneyRankMapper.selectFsUserTuiMoneyRankByType(2);
        fsUserTuiMoneyRankMapper.deleteFsUserTuiMoneyRankByType(2);
        rank = 1;
        for (FsUserShareVO vo : fsUserShareVOS2) {
            FsUserTuiMoneyRank userRank = new FsUserTuiMoneyRank();
            userRank.setAvatar(vo.getAvatar());
            userRank.setUserId(vo.getUserId());
            userRank.setSort(rank);
            userRank.setTuiMoney(vo.getTuiMoney());
            userRank.setType(2);
            userRank.setId(id);
            userRank.setNickname(vo.getNickname());
            userRank.setPhone(vo.getPhone());
            fsUserTuiMoneyRankMapper.insertFsUserTuiMoneyRank(userRank);
            rank++;
            id++;
        }
        List<FsUserShareVO> fsUserShareVOS3 = fsUserTuiMoneyRankMapper.selectFsUserTuiMoneyRankByType(3);
        fsUserTuiMoneyRankMapper.deleteFsUserTuiMoneyRankByType(3);
        rank = 1;
        for (FsUserShareVO vo : fsUserShareVOS3) {
            FsUserTuiMoneyRank userRank = new FsUserTuiMoneyRank();
            userRank.setAvatar(vo.getAvatar());
            userRank.setUserId(vo.getUserId());
            userRank.setSort(rank);
            userRank.setTuiMoney(vo.getTuiMoney());
            userRank.setType(3);
            userRank.setId(id);
            userRank.setNickname(vo.getNickname());
            userRank.setPhone(vo.getPhone());
            fsUserTuiMoneyRankMapper.insertFsUserTuiMoneyRank(userRank);
            rank++;
            id++;
        }
    }

    /**
     * 更新商品成本价
     */
    @QuartzRunnable(name = "更新商品成本价")
    public void storeProdUpdateCostPrice() {
        String json = configService.selectConfigByKey("store.config");
        StoreConfig config = JSONUtil.toBean(json, StoreConfig.class);
        List<FsStoreProductAttrValue> values = fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueList(new FsStoreProductAttrValue());

        Map<Long, FsStoreProduct> fsStoreProductMap = fsStoreProductMapper.selectAllProductMappingInfo();

        int i = 0;
        for (FsStoreProductAttrValue value : values) {
            try {
                if (StringUtils.isNotEmpty(value.getBarCode())) {
                    ErpGoodsQueryRequert query = new ErpGoodsQueryRequert();
                    query.setCode(value.getBarCode());

                    FsStoreProduct fsStoreProduct = fsStoreProductMap.get(value.getProductId());
                    String erp = fsStoreProduct.getErp();
                    ErpContextHolder.setErpType(erp);

                    ErpGoodsQueryResponse goods = erpGoodsService.getGoods(query);
                    List<ErpGoods> items = goods.getItems();
                    if (items != null && items.size() > 0) {
                        ErpGoods erpGoods = items.get(0);
                        BigDecimal salesPrice = erpGoods.getSales_price();
                        if (salesPrice != null && salesPrice.compareTo(BigDecimal.ZERO) != 0) {
                            BigDecimal divide = salesPrice.multiply(new BigDecimal(config.getSalesPriceRate())).divide(new BigDecimal("100"));
                            logger.info("商品id" + value.getId() + "商品成本：" + salesPrice + "代理价" + divide);
                            FsStoreProductAttrValue va = new FsStoreProductAttrValue();
                            va.setCost(salesPrice);
                            va.setPrice(divide);
                            va.setId(value.getId());
                            fsStoreProductAttrValueMapper.updateFsStoreProductAttrValue(va);
                            i++;
                        }
                    }
                } else if (StringUtils.isNotEmpty(value.getGroupBarCode())) {
                    FsStoreProductGroup group = storeProductGroupService.selectFsStoreProductGroupByBarCode(value.getGroupBarCode());
                    if (group != null) {
                        JSONArray jsonArray = JSONUtil.parseArray(group.getProducts());
                        List<StoreProductGroupDTO> productGroupDTOS = JSONUtil.toList(jsonArray, StoreProductGroupDTO.class);
                        if (productGroupDTOS != null) {
                            for (StoreProductGroupDTO dto : productGroupDTOS) {
                                FsStoreProductAttrValue attrValue = fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueById(dto.getId());
                                Integer count = dto.getCount();
                                String barCode = attrValue.getBarCode();
                                ErpGoodsQueryRequert query = new ErpGoodsQueryRequert();
                                query.setCode(barCode);

                                FsStoreProduct fsStoreProduct = fsStoreProductMap.get(value.getProductId());
                                String erp = fsStoreProduct.getErp();
                                ErpContextHolder.setErpType(erp);

                                ErpGoodsQueryResponse goods = erpGoodsService.getGoods(query);
                                List<ErpGoods> items = goods.getItems();
                                if (items != null && items.size() > 0) {
                                    ErpGoods erpGoods = items.get(0);
                                    BigDecimal salesPrice = erpGoods.getSales_price();
                                    if (salesPrice != null && salesPrice.compareTo(BigDecimal.ZERO) != 0) {
                                        salesPrice = salesPrice.multiply(new BigDecimal(count));
                                        BigDecimal divide = salesPrice.multiply(new BigDecimal(config.getSalesPriceRate())).divide(new BigDecimal("100"));
                                        logger.info("商品id" + value.getId() + "商品成本：" + salesPrice + "代理价" + salesPrice);
                                        FsStoreProductAttrValue va = new FsStoreProductAttrValue();
                                        va.setCost(salesPrice);
                                        va.setAgentPrice(divide);
                                        va.setId(value.getId());
                                        fsStoreProductAttrValueMapper.updateFsStoreProductAttrValue(va);
                                        i++;
                                    }
                                }

                            }
                        }
                    }

                }
            } catch (Exception e) {
                logger.info("商品更新成本价错误：" + value.getId());
            }finally {
                ErpContextHolder.clear();
            }


        }
        logger.info("更新商品成本价:" + i);


    }

    /**
     * 优惠券过期处理
     */
    @QuartzRunnable(name = "优惠券过期处理")
    public void couponOp() {
        couponUserService.updateFsCouponByExpire();

    }


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


    /**
     * 订单完成7天后会员分佣
     */
    @QuartzRunnable(name = "订单完成7天后会员分佣")
    public void userMoneyOp() {
        List<FsStoreOrder> list = orderService.selectFsStoreOrderListByFinish7Day();
        if (list != null) {
            for (FsStoreOrder order : list) {
                userService.addMoney(order);
            }
        }
    }


    /**
     * 订单Items同步
     */
    @QuartzRunnable(name = "订单Items同步")
    public void orderItemSyncOp() {
        List<FsStoreOrder> list = fsStoreOrderService.selectFsStoreOrderItemJson();
        for (FsStoreOrder storeOrder : list) {
            FsStoreOrderItem parmOrderItem = new FsStoreOrderItem();
            parmOrderItem.setOrderId(storeOrder.getId());
            List<FsStoreOrderItem> listOrderItem = storeOrderItemService.selectFsStoreOrderItemList(parmOrderItem);
            if (listOrderItem.size() > 0) {
                String itemJson = JSONUtil.toJsonStr(listOrderItem);
                storeOrder.setItemJson(itemJson);
                fsStoreOrderMapper.uploadItemJson(storeOrder);
            }
        }
    }


    /**
     * 批量推管易
     * @throws ParseException 解析异常
     */
    @QuartzRunnable(name = "批量推管易")
    public void updateOrderItem() throws ParseException {
        List<Long> ids = itemMapper.selectOrderIdByNoErp();
        for (Long id : ids) {
            fsStoreOrderService.createOmsOrder(id);
        }
    }


    /**
     * 同步物流状态
     */
    @QuartzRunnable(name = "同步物流状态")
    public void syncExpress() {
        List<Long> ids = fsStoreOrderMapper.selectSyncExpressIds();

        for (Long id : ids) {
            FsStoreOrderExpressEditParam param = new FsStoreOrderExpressEditParam();
            param.setOrderId(id);
            fsStoreOrderService.syncExpress(param);
        }

    }


    /**
     * 批量分佣
     */
    @QuartzRunnable(name = "批量分佣")
    public void AddTuiMoney() {
        List<Long> ids = fsStoreOrderMapper.selectAddTuiMoney();
        for (Long id : ids) {
            FsStoreOrderAddTuiMoneyParam param = new FsStoreOrderAddTuiMoneyParam();
            param.setOrderId(id);
            fsStoreOrderService.addTuiMoney(param);
        }

    }


    public void selectPayMoneyLessOne() {
        List<FsStoreOrder> list = fsStoreOrderMapper.selectPayMoneyLessOne();
        for (FsStoreOrder order : list) {
            FsStoreAfterSalesParam param = new FsStoreAfterSalesParam();
            param.setOrderCode(order.getOrderCode());
            param.setServiceType(0);
            param.setRefundAmount(order.getPayMoney());
            param.setReasons("超时未处理，自动申请退款");
            List<FsStoreAfterSalesProductParam> productParams = new ArrayList<>();
            List<FsStoreOrderItem> items = fsStoreOrderMapper.selectOrderItem(order.getId());
            for (FsStoreOrderItem item : items) {
                FsStoreAfterSalesProductParam param1 = new FsStoreAfterSalesProductParam();
                param1.setProductId(item.getProductId());
                param1.setNum(item.getNum());
                productParams.add(param1);
            }
            param.setProductList(productParams);
            fsStoreAfterSalesService.autoApplyForAfterSales(order.getUserId(), param);
        }
    }

    /**
     * 检测弱密码
     */
    @QuartzRunnable(name = "检测弱密码")
    public void updateCompanyUserStatus() {
        CompanyUser user = new CompanyUser();
        user.setStatus("0");
        user.setDelFlag("0");
        List<CompanyUser> companyUsers = companyUserMapper.selectCompanyUserList(user);
        for (CompanyUser companyUser : companyUsers) {
            if (SecurityUtils.matchesPassword("123456", companyUser.getPassword())) {
                companyUser.setStatus("1");
                companyUserMapper.updateCompanyUser(companyUser);
                logger.info("密码为123456 停用账号：" + companyUser.getUserId() + ":" + companyUser.getNickName());
            }
        }
    }



    /**
     * 更新发货状态
     */
    @QuartzRunnable(name = "发货任务")
    public void updateExpress() {
        List<FsStoreOrder> list = fsStoreOrderMapper.selectUpdateExpress();

        for (FsStoreOrder order : list) {
            ErpOrderQueryRequert request = new ErpOrderQueryRequert();
            request.setCode(order.getExtendOrderId());
            // 根据仓库code找erp
            if(com.fs.common.utils.StringUtils.isNotBlank(order.getStoreHouseCode())){
                String erp = fsWarehousesMapper.selectErpByCode(order.getStoreHouseCode());
                ErpContextHolder.setErpType(erp);
            }

            ErpOrderQueryResponse response = erpOrderService.getOrder(request);
            if (CollectionUtils.isNotEmpty(response.getOrders())) {
                for (ErpOrderQuery orderQuery : response.getOrders()) {
                    // 部分发货或者全部发货
                    if (ObjectUtils.equals(orderQuery.getDelivery_state(), 1) || ObjectUtils.equals(orderQuery.getDelivery_state(), 2)) {
                        // 订单状态变更
                        orderStatusService.create(order.getId(), OrderLogEnum.DELIVERY_GOODS.getValue(),
                                OrderLogEnum.DELIVERY_GOODS.getDesc());

                        redisCache.deleteObject(DELIVERY + ":" + order.getExtendOrderId());

                        for (ErpDeliverys delivery : orderQuery.getDeliverys()) {
                            if (delivery.getDelivery()) {
                                orderService.deliveryOrder(order.getOrderCode(), delivery.getMail_no(),
                                        delivery.getExpress_code(), delivery.getExpress_name());
                            }
                        }

                    }
                }
            }
        }

    }


}
