package com.fs.erp.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.utils.ExceptionUtil;
import com.fs.erp.constant.AfterSalesOrderStatusEnum;
import com.fs.erp.constant.TradeStatus;
import com.fs.erp.domain.ErpOrderItem;
import com.fs.erp.domain.FsJstAftersalePush;
import com.fs.erp.dto.*;
import com.fs.erp.http.JstErpHttpService;
import com.fs.erp.mapper.FsJstAftersalePushMapper;
import com.fs.erp.service.FsJstAftersalePushService;
import com.fs.express.enums.TaskStatusEnum;
import com.fs.live.domain.LiveOrder;
import com.fs.live.domain.LiveOrderItem;
import com.fs.live.mapper.LiveOrderItemMapper;
import com.fs.live.mapper.LiveOrderMapper;
import com.fs.store.domain.FsStoreAfterSales;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.domain.FsStoreOrderItem;
import com.fs.store.dto.FsStoreCartDTO;
import com.fs.store.mapper.FsStoreAfterSalesMapper;
import com.fs.store.mapper.FsStoreOrderMapper;
import com.fs.store.service.IFsStoreOrderItemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class FsJstAftersalePushServiceImpl implements FsJstAftersalePushService {

    @Autowired
    private FsJstAftersalePushMapper fsJstAftersalePushMapper;

    @Autowired
    private JstErpHttpService jstErpHttpService;

    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;

    @Autowired
    private IFsStoreOrderItemService storeOrderItemService;
    @Autowired
    private LiveOrderMapper liveOrderMapper;
    @Autowired
    private LiveOrderItemMapper liveOrderItemMapper;
    @Autowired
    private FsStoreAfterSalesMapper fsStoreAfterSalesMapper;

    @Value("${jst.shop_code}")
    private String shopId;
    @Override
    public void pushJst() {
        List<FsJstAftersalePush> fsJstAftersalePushes = fsJstAftersalePushMapper.queryPenddingData();

        for (FsJstAftersalePush item : fsJstAftersalePushes) {
            item.setTaskStatus(TaskStatusEnum.PROCESSING.getCode());
            int update = fsJstAftersalePushMapper.update(item);
            if(update <= 0){
                log.info("获取记录{} 锁失败!",item.getId());
                continue;
            }
            RefundOrderDTO dto;
            if(ObjectUtils.equals(item.getOrderType(),0)) {
                FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(item.getOrderId());

                item.setRetryCount(item.getRetryCount()+1);

                if(fsStoreOrder == null){
                    item.setErrorMessage("该订单未找到!");
                    item.setTaskStatus(TaskStatusEnum.FAILED.getCode());
                    log.info("该订单未找到!");
                    fsJstAftersalePushMapper.update(item);
                    continue;
                }
                Asserts.notNull(fsStoreOrder,"该订单未找到!");
                dto = getAfterSaleDTO(item, fsStoreOrder);
            } else {
                LiveOrder liveOrder = liveOrderMapper.selectFsUserVipOrderByOrderCode(item.getOrderId());

                item.setRetryCount(item.getRetryCount()+1);

                if(liveOrder == null){
                    item.setErrorMessage("该订单未找到!");
                    item.setTaskStatus(TaskStatusEnum.FAILED.getCode());
                    log.info("该订单未找到!");
                    fsJstAftersalePushMapper.update(item);
                    continue;
                }
                Asserts.notNull(liveOrder,"该订单未找到!");
                dto = getAfterSaleDTOLive(item, liveOrder);
            }

            // 买家已经申请，等待卖家同意
            if(StringUtils.equals(AfterSalesOrderStatusEnum.WAIT_SELLER_AGREE.getIndex().toString()
                    ,item.getType())){

            // 买家已经退货，等待卖家确认收货
            } else if(StringUtils.equals(AfterSalesOrderStatusEnum.WAIT_SELLER_CONFIRM_GOODS.getIndex().toString(),
                    item.getType())){
                // 查询售后单 同步快递单号过去
                FsStoreAfterSales fsStoreAfterSales = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(item.getId());
                dto.setLogisticsCompany(fsStoreAfterSales.getDeliverySn());
                dto.setLId(fsStoreAfterSales.getDeliveryId());

            // 售后关闭
            } else if(StringUtils.equals(AfterSalesOrderStatusEnum.CLOSED.getIndex().toString(),item.getType())) {

            // 退款成功
            } else if(StringUtils.equals(AfterSalesOrderStatusEnum.SUCCESS.getIndex().toString(),item.getType())) {

            // 确认
            }


            if(!StringUtils.equals(AfterSalesOrderStatusEnum.CONFIRM.getIndex().toString(),item.getType())) {
                try{
                    CommonResponse<AfterSaleResponseDTO> response = jstErpHttpService.aftersaleUpload(dto);
                    item.setParams(JSON.toJSONString(dto));
                    item.setResult(JSON.toJSONString(response));
                    item.setTaskStatus(TaskStatusEnum.SUCCESS.getCode());
                }catch (Exception e) {
                    item.setErrorMessage(ExceptionUtil.getExceptionMessage(e));
                    item.setTaskStatus(TaskStatusEnum.FAILED.getCode());
                }

            // 如果是确认类型
            } else{
                AfterSaleConfirmRequestDTO requestDTO = new AfterSaleConfirmRequestDTO();

                requestDTO.setAsIds(Collections.singletonList(Long.valueOf(item.getAfterSaleId())));
                requestDTO.setExchangeForce(true);
                requestDTO.setConfirmRefund(true);

                try{
                    CommonResponse<AssetProcessResultDTO> response = jstErpHttpService.aftersaleConfirm(requestDTO);
                    item.setParams(JSON.toJSONString(dto));
                    item.setResult(JSON.toJSONString(response));
                    item.setTaskStatus(TaskStatusEnum.SUCCESS.getCode());
                }catch (Exception e){
                    item.setErrorMessage(ExceptionUtil.getExceptionMessage(e));
                    item.setTaskStatus(TaskStatusEnum.FAILED.getCode());
                }
            }

            fsJstAftersalePushMapper.update(item);
        }
    }

    private RefundOrderDTO getAfterSaleDTO(FsJstAftersalePush item, FsStoreOrder fsStoreOrder) {
        RefundOrderDTO dto = new RefundOrderDTO();
        AfterSalesOrderStatusEnum statusEnum = AfterSalesOrderStatusEnum.getByIndex(Integer.valueOf(item.getType()));

        dto.setShopStatus(statusEnum.getCode());
        dto.setQuestionType("可更新");
        dto.setOuterAsId(item.getAfterSaleId());
        dto.setRemark("用户退款");
        dto.setType("仅退款");

        dto.setShopId(Long.parseLong(shopId));
        dto.setTotalAmount(fsStoreOrder.getTotalPrice());
        dto.setSoId(item.getOrderId());
        dto.setRefund(fsStoreOrder.getPayMoney());


        FsStoreOrderItem itemMap=new FsStoreOrderItem();
        itemMap.setOrderId(fsStoreOrder.getId());
        List<FsStoreOrderItem> orderItems=storeOrderItemService.selectFsStoreOrderItemList(itemMap);
        List<RefundItemDTO> refundItemDTOS=new ArrayList<>();

        for(FsStoreOrderItem orderItem: orderItems) {
            FsStoreCartDTO cartDTO = JSONUtil.toBean(orderItem.getJsonInfo(), FsStoreCartDTO.class);

            RefundItemDTO itemDTO = new RefundItemDTO();
            itemDTO.setSkuId(cartDTO.getBarCode());
            itemDTO.setQty(cartDTO.getNum());
            itemDTO.setAmount(cartDTO.getPrice());
            itemDTO.setType("退货");
            refundItemDTOS.add(itemDTO);
        }
        dto.setItems(refundItemDTOS);
        return dto;
    }

    private RefundOrderDTO getAfterSaleDTOLive(FsJstAftersalePush item, LiveOrder liveOrder) {
        RefundOrderDTO dto = new RefundOrderDTO();
        AfterSalesOrderStatusEnum statusEnum = AfterSalesOrderStatusEnum.getByIndex(Integer.valueOf(item.getType()));

        dto.setShopStatus(statusEnum.getCode());
        dto.setQuestionType("可更新");
        dto.setOuterAsId(item.getAfterSaleId());
        dto.setRemark("用户退款");
        dto.setType("仅退款");

        dto.setShopId(Long.parseLong(shopId));
        dto.setTotalAmount(liveOrder.getTotalPrice());
        dto.setSoId(item.getOrderId());
        dto.setRefund(liveOrder.getPayMoney());


        LiveOrderItem itemMap=new LiveOrderItem();
        itemMap.setOrderId(liveOrder.getOrderId());
        List<LiveOrderItem> orderItems = liveOrderItemMapper.selectLiveOrderItemList(itemMap);

        List<RefundItemDTO> refundItemDTOS=new ArrayList<>();

        for(LiveOrderItem orderItem: orderItems) {
            FsStoreCartDTO cartDTO = JSONUtil.toBean(orderItem.getJsonInfo(), FsStoreCartDTO.class);

            RefundItemDTO itemDTO = new RefundItemDTO();
            itemDTO.setSkuId(cartDTO.getBarCode());
            itemDTO.setQty(cartDTO.getNum());
            itemDTO.setAmount(cartDTO.getPrice());
            itemDTO.setType("退货");
            refundItemDTOS.add(itemDTO);
        }
        dto.setItems(refundItemDTOS);
        return dto;
    }
}
