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.common.utils.StringUtils;
import com.fs.erp.constant.AfterSalesOrderStatusEnum;
import com.fs.erp.constant.TaskStatusEnum;
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.mapper.FsJstAftersalePushScrmMapper;
import com.fs.erp.service.FsJstAftersalePushScrmService;
import com.fs.erp.service.FsJstAftersalePushService;
import com.fs.his.domain.FsStoreAfterSales;
import com.fs.his.dto.FsStoreCartDTO;
import com.fs.his.mapper.FsStoreAfterSalesMapper;
import com.fs.hisStore.domain.FsStoreAfterSalesScrm;
import com.fs.hisStore.domain.FsStoreOrderItemScrm;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.mapper.FsStoreAfterSalesScrmMapper;
import com.fs.hisStore.mapper.FsStoreOrderScrmMapper;
import com.fs.hisStore.service.IFsStoreOrderItemScrmService;
import com.fs.ybPay.dto.RefundOrderDTO;
import lombok.extern.slf4j.Slf4j;
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.Collections;
import java.util.List;

@Slf4j
@Service
public class FsJstAftersalePushScrmServiceImpl implements FsJstAftersalePushScrmService {

    @Autowired
    private FsJstAftersalePushScrmMapper fsJstAftersalePushMapper;

    @Autowired
    private JstErpHttpService jstErpHttpService;

    @Autowired
    private FsStoreOrderScrmMapper fsStoreOrderMapper;

    @Autowired
    private IFsStoreOrderItemScrmService storeOrderItemService;

    @Autowired
    private FsStoreAfterSalesScrmMapper 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;
            }

            FsStoreOrderScrm 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,"该订单未找到!");
            RefundOrderDTO dto;
            dto = getAfterSaleDTO(item, fsStoreOrder);
            // 买家已经申请，等待卖家同意
            if(StringUtils.equals(AfterSalesOrderStatusEnum.WAIT_SELLER_AGREE.getIndex().toString()
                    ,item.getType())){

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

            // 售后关闭
            } 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, FsStoreOrderScrm 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());


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

        for(FsStoreOrderItemScrm 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;
    }
}
