package com.gic.haoban.manage.web.controller.order;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.business.order.api.service.order.AfterSalesManageApiService;
import com.gic.business.order.dto.member.MemberStoreInfoDTO;
import com.gic.business.order.dto.ordermanage.OrderExchangeConsultDTO;
import com.gic.business.order.dto.ordermanage.OrderExchangeDetailDTO;
import com.gic.business.order.dto.ordermanage.OrderRefundConsultDTO;
import com.gic.business.order.dto.ordermanage.OrderRefundDetailDTO;
import com.gic.business.order.dto.ordermanage.OrderRefundExchangeListDTO;
import com.gic.business.order.dto.ordermanage.RefundAddressDTO;
import com.gic.business.order.qdto.OperationUserQDTO;
import com.gic.business.order.qdto.aftersales.ExchangeAddressQDTO;
import com.gic.business.order.qdto.aftersales.ExchangeBaseQDTO;
import com.gic.business.order.qdto.aftersales.ExchangeDeliveryBackQDTO;
import com.gic.business.order.qdto.aftersales.ExchangeRefusedQDTO;
import com.gic.business.order.qdto.aftersales.ExchangeSellerAgreeApplyQDTO;
import com.gic.business.order.qdto.aftersales.RefundBaseQDTO;
import com.gic.business.order.qdto.aftersales.RefundRefusedQDTO;
import com.gic.business.order.qdto.aftersales.RefundSellerAgreeQDTO;
import com.gic.business.order.qdto.aftersales.RefundSellerConfirmGoodsQDTO;
import com.gic.business.order.qdto.ordermanage.RefundExchangeQDTO;
import com.gic.business.order.service.activity.MemberReferClerkApiService;
import com.gic.business.order.service.ordermanage.MallSellerAddressApiService;
import com.gic.business.order.service.ordermanage.OrderRefundApiService;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.order.refund.ConsultOperVO;
import com.gic.haoban.manage.web.vo.order.refund.OrderExchangeConsultVO;
import com.gic.haoban.manage.web.vo.order.refund.OrderExchangeDetailVO;
import com.gic.haoban.manage.web.vo.order.refund.OrderRefundConsultVO;
import com.gic.haoban.manage.web.vo.order.refund.OrderRefundDetailVO;
import com.gic.haoban.manage.web.vo.order.refund.RefundAddressVO;
import com.gic.haoban.manage.web.vo.order.refund.SellerAddressVO;
import com.gic.store.goods.dto.stock.GoodsStockBaseQDTO;
import com.gic.store.goods.enums.ProductStockChannelType;
import com.gic.store.goods.service.ProductStockApiService;

@RestController
@RequestMapping("/refund")
public class GicOrderRefundController {

    private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(GicOrderRefundController.class);

    @Autowired
    private OrderRefundApiService orderRefundApiService;
    @Autowired
    private MallSellerAddressApiService mallSellerAddressApiService;
    @Autowired
    private AfterSalesManageApiService afterSalesManageApiService;
    @Autowired
    private ProductStockApiService productStockApiService;
    @Autowired
    private MemberReferClerkApiService memberReferClerkApiService;
    @Autowired
    private ClerkService clerkService;

    /**
     * 
    * @Title: exchangeConsult
    * @Description: 售后列表
    * @author xugh
    * @param orderExchangeId
    * @return
    * @throws
     */
    @RequestMapping(value = "order-exchange-refund-list")
    @ResponseBody
    public RestResponse<Object> exchangeRefundList(RefundExchangeQDTO qdto) {
        String clerkId = qdto.getClerkId();
        if (StringUtils.isEmpty(clerkId)) {
            return RestResponse.failure("9999", "导购ID为空");
        }
        ClerkDTO clerk = this.clerkService.getClerkByClerkId(clerkId);
        if (clerk.getClerkType() == 1) {
            qdto.setClerkId(null);
        }
        qdto.setHbSearch(qdto.getSearch());
        qdto.setSearch(null);
        qdto.setHbFlag(1);
        ServiceResponse<Page<OrderRefundExchangeListDTO>> resp = orderRefundApiService.refundExchangePage(qdto);
        return RestResponse.successResult(resp.getResult());
    }

    // 退款-详情
    @RequestMapping(value = "order-refund-detail")
    @ResponseBody
    public RestResponse<Object> refundDetail(String enterpriseId, String storeId, String orderRefundId) {
        ServiceResponse<OrderRefundDetailDTO> resp = this.orderRefundApiService.refundDetail(orderRefundId);
        OrderRefundDetailDTO dto = resp.getResult();
        OrderRefundDetailVO vo = EntityUtil.changeEntityByJSON(OrderRefundDetailVO.class, dto);
        this.fillMemberInfo(enterpriseId, vo.getMemberId(), vo, null);
        // 判断好办端能否审批(确认收货) 只有收货门店能确认
        boolean canAduitFlag = false;
        if (vo.getRefundStatus() == 1) {
            canAduitFlag = true;
        } else {
            // 退货地址类型 0归属门店 1发货门店 2平台地址
            Integer sellerAddressType = dto.getSellerAddressType();
            String refundStoreId = dto.getRefundStoreId();
            logger.info("退货收货门店={},{},{}", storeId, refundStoreId, sellerAddressType);
            if (null != sellerAddressType && sellerAddressType != 2 && StringUtils.isNotEmpty(refundStoreId) && storeId.equals(refundStoreId)) {
                canAduitFlag = true;
            }
        }
        vo.setCanAduitFlag(canAduitFlag);
        vo.setUsePoint(dto.getUsePoints());
        return RestResponse.successResult(vo);
    }

    // 换货-详情
    @RequestMapping(value = "order-exchange-detail")
    @ResponseBody
    public RestResponse<Object> exchangeDetail(String enterpriseId, String storeId, String orderExchangeId) {
        ServiceResponse<OrderExchangeDetailDTO> resp = this.orderRefundApiService.exchangeDetail(orderExchangeId);
        OrderExchangeDetailDTO dto = resp.getResult();
        OrderExchangeDetailVO vo = EntityUtil.changeEntityByJSON(OrderExchangeDetailVO.class, dto);
        String targetProSkuId = resp.getResult().getTargetProSkuId();
        // 查询库存
        vo.setTargetProStock(1);
        GoodsStockBaseQDTO qdto = new GoodsStockBaseQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setGoodsId(vo.getMallProId());
        qdto.setSkuId(targetProSkuId);
        qdto.setStoreId(storeId);
        qdto.setChannelType(ProductStockChannelType.MALL.getCode());
        ServiceResponse<Integer> stockResp = this.productStockApiService.queryGoodsStock(qdto);
        if (stockResp.isSuccess() && null != stockResp.getResult()) {
            vo.setTargetProStock(stockResp.getResult());
        }
        this.fillMemberInfo(enterpriseId, vo.getMemberId(), null, vo);
        // 判断好办端能否审批售后canAduitFlag
        int sellerAddressType = dto.getSellerAddressType();
        boolean canAduitFlag = false;
        if (vo.getExchangeStatus() == 1) {
            canAduitFlag = true;
        } else {
            String exchangeStoreId = dto.getExchangeStoreId();
            logger.info("换货收货门店={},{}", storeId, exchangeStoreId, sellerAddressType);
            if (sellerAddressType != 2 && StringUtils.isNotEmpty(exchangeStoreId) && storeId.equals(exchangeStoreId)) {
                canAduitFlag = true;
            }
        }
        vo.setCanAduitFlag(canAduitFlag);
        return RestResponse.successResult(vo);
    }

    // 审批退款单
    // auditStatus 拒绝 1 , 同意2
    // 拒绝收货 1 同意收货2
    // step 1 申请 2收货
    @RequestMapping(value = "audit-refund-order")
    @ResponseBody
    public RestResponse<Object> auditRefund(String enterpriseId, String memberId,
            @RequestParam(defaultValue = "1") int auditStatus, String clerkId, String remark,
            @RequestParam(defaultValue = "1") int step, RefundBaseQDTO baseQDTO, ExchangeAddressQDTO address,
            @RequestParam(defaultValue = "0") Double applyRefundPrice) {
        ServiceResponse<Void> resp = null;
        // 拒绝
        if (auditStatus == 1) {
            RefundRefusedQDTO qdto = EntityUtil.changeEntityByJSON(RefundRefusedQDTO.class, baseQDTO);
            qdto.setReason(remark);
            if (step == 1) {
                resp = this.afterSalesManageApiService.refundSellerRefusedApply(enterpriseId, memberId, qdto,this.getOper(clerkId));
            }
            if (step == 2) {
                resp = this.afterSalesManageApiService.refundSellerRefusedGoods(enterpriseId, memberId, qdto,this.getOper(clerkId));
            }
        }
        // 同意
        if (auditStatus == 2) {
            if (step == 1) {
                RefundSellerAgreeQDTO qdto = EntityUtil.changeEntityByJSON(RefundSellerAgreeQDTO.class, baseQDTO);
                qdto.setApplyRefundPrice(applyRefundPrice);
                qdto.setExchangeAddress(address);
                resp = this.afterSalesManageApiService.refundSellerConfirmApply(enterpriseId, memberId, qdto,this.getOper(clerkId));
            }
            if (step == 2) {
                RefundSellerConfirmGoodsQDTO qdto = EntityUtil.changeEntityByJSON(RefundSellerConfirmGoodsQDTO.class,
                        baseQDTO);
                qdto.setApplyRefundPrice(applyRefundPrice);
                resp = this.afterSalesManageApiService.refundSellerConfirmGoods(enterpriseId, memberId, qdto,this.getOper(clerkId));
            }
        }
        if (!resp.isSuccess()) {
            String code = resp.getCode();
            if (Arrays.asList("900001", "300105", "200001").contains(code)) {
                return RestResponse.failure(HaoBanErrCode.ERR_9600.getCode() + "", "请刷新页面");
            }
            return RestResponse.failure(resp.getCode(), resp.getMessage());
        }
        return RestResponse.successResult();
    }

    // 审批换货单
    // 拒绝 1 , 同意2
    // 拒绝收货 1 同意收货2
    // step 1 申请 2收货
    @RequestMapping(value = "audit-exchange-order")
    @ResponseBody
    public RestResponse<Object> auditExchange(String enterpriseId, String memberId,
            @RequestParam(defaultValue = "1") int auditStatus, String clerkId, String remark, RefundBaseQDTO baseQDTO,
            ExchangeAddressQDTO address, @RequestParam(defaultValue = "1") int step) {
        ServiceResponse<Void> resp = null;
        // 拒绝
        if (auditStatus == 1) {
            ExchangeRefusedQDTO qdto = EntityUtil.changeEntityByJSON(ExchangeRefusedQDTO.class, baseQDTO);
            qdto.setRemark(remark);
            if (step == 1) {
                resp = this.afterSalesManageApiService.exchangeSellerRefused(enterpriseId, memberId, qdto,this.getOper(clerkId));
            }
            if (step == 2) {
                resp = this.afterSalesManageApiService.exchangeSellerRefusedGoods(enterpriseId, memberId, qdto,this.getOper(clerkId));
            }
        }
        // 同意
        if (auditStatus == 2) {
            ExchangeSellerAgreeApplyQDTO qdto = EntityUtil.changeEntityByJSON(ExchangeSellerAgreeApplyQDTO.class,
                    baseQDTO);
            if (step == 1) {
                qdto.setExchangeAddress(address);
                resp = this.afterSalesManageApiService.exchangeSellerConfirm(enterpriseId, memberId, qdto,this.getOper(clerkId));
            }
            if (step == 2) {
                resp = this.afterSalesManageApiService.exchangeSellerConfirmGoods(enterpriseId, memberId, qdto,this.getOper(clerkId));
            }
        }
        if (!resp.isSuccess()) {
            String code = resp.getCode();
            if (Arrays.asList("900001", "300105", "200001").contains(code)) {
                return RestResponse.failure(HaoBanErrCode.ERR_9600.getCode() + "", "请刷新页面");
            }
            return RestResponse.failure(resp.getCode(), resp.getMessage());
        }
        return RestResponse.successResult();
    }

    // 协商记录-退款
    @RequestMapping(value = "order-refund-consult")
    @ResponseBody
    public RestResponse<Object> refundConsult(String orderRefundId) {
        ServiceResponse<List<OrderRefundConsultDTO>> resp = orderRefundApiService.listRefundConsult(orderRefundId);
        List<OrderRefundConsultVO> list = new ArrayList<>() ;
        for(OrderRefundConsultDTO dto : resp.getResult()) {
            String operInfo = dto.getOperInfo() ;
            dto.setOperInfo(null);
            OrderRefundConsultVO vo = EntityUtil.changeEntityByJSON(OrderRefundConsultVO.class, dto) ;
            if(StringUtils.isNotEmpty(operInfo)) {
                ConsultOperVO oper = JSONObject.parseObject(operInfo, ConsultOperVO.class) ;
                vo.setOperInfo(oper);
            }
            list.add(vo) ;
        }
        return RestResponse.successResult(list);
    }

    // 协商记录-换货
    @RequestMapping(value = "order-exchange-consult")
    @ResponseBody
    public RestResponse<Object> exchangeConsult(String orderExchangeId) {
        ServiceResponse<List<OrderExchangeConsultDTO>> resp = orderRefundApiService
                .listExchangeConsult(orderExchangeId);
        List<OrderExchangeConsultVO> list = new ArrayList<>() ;
        for(OrderExchangeConsultDTO dto : resp.getResult()) {
            String operInfo = dto.getOperInfo() ;
            dto.setOperInfo(null);
            OrderExchangeConsultVO vo = EntityUtil.changeEntityByJSON(OrderExchangeConsultVO.class, dto) ;
            if(StringUtils.isNotEmpty(operInfo)) {
                ConsultOperVO oper = JSONObject.parseObject(operInfo, ConsultOperVO.class) ;
                vo.setOperInfo(oper);
            }
            list.add(vo) ;
        }
        return RestResponse.successResult(list);
    }

    // 收货地址
    @RequestMapping("get-seller-address")
    @ResponseBody
    public RestResponse<Object> refundAddressList(String enterpriseId, String orderId, String orderItemId) {
        SellerAddressVO vo = new SellerAddressVO();
        ServiceResponse<List<RefundAddressDTO>> resp = this.mallSellerAddressApiService.listRefundAddress(enterpriseId,
                orderId, orderItemId);
        List<RefundAddressDTO> list = resp.getResult();
        List<RefundAddressVO> sellerAddressList = new ArrayList<>();
        list.forEach(dto -> {
            RefundAddressVO item = EntityUtil.changeEntityByJSON(RefundAddressVO.class, dto);
            if (dto.getAddressType() == 0) {
                vo.setOwnerStoreAddress(item);
            }
            if (dto.getAddressType() == 1) {
                vo.setDeliverStoreAddress(item);
            }
            if (dto.getAddressType() == 2) {
                sellerAddressList.add(item);
            }
        });
        vo.setSellerAddressList(sellerAddressList);
        return RestResponse.successResult(vo);
    }

    // 换货单发货
    @RequestMapping(value = "exchange-order-deliver")
    @ResponseBody
    public RestResponse<Object> exchangeDeliver(String enterpriseId, String memberId, String companyCode,
            String logisticsNo, String companyId, String companyName, String storeId, ExchangeBaseQDTO baseQDTO,String clerkId) {
        ExchangeDeliveryBackQDTO qdto = new ExchangeDeliveryBackQDTO();
        qdto.setCourierNumber(logisticsNo);
        qdto.setOrderId(baseQDTO.getOrderId());
        qdto.setOrderItemId(baseQDTO.getOrderItemId());
        qdto.setOrderExchangeId(baseQDTO.getOrderExchangeId());
        qdto.setLogisticsCompanyCode(companyCode);
        qdto.setLogisticsCompanyId(companyId);
        qdto.setLogisticsCompanyName(companyName);
        qdto.setDeliveryStoreId(storeId);
        ServiceResponse<Void> resp = this.afterSalesManageApiService.exchangeSellerDeliveryGoods(enterpriseId, memberId,
                qdto,this.getOper(clerkId));
        logger.info("换货单发货={}", JSON.toJSONString(resp));
        if (resp.isSuccess()) {
            return RestResponse.successResult();
        }
        return RestResponse.failure("9999", resp.getMessage());
    }

    private void fillMemberInfo(String enterpriseId, String memberId, OrderRefundDetailVO refund,
            OrderExchangeDetailVO exchange) {
        ServiceResponse<MemberStoreInfoDTO> memberResp = this.memberReferClerkApiService.getMemberInfo(enterpriseId,
                memberId);
        MemberStoreInfoDTO memberInfo = memberResp.getResult();
        if (null != memberInfo) {
            if (null != refund) {
                refund.setMemberId(memberId);
                refund.setMemberName(memberInfo.getMemberName());
                refund.setMemberImage(memberInfo.getMemberImage());
                refund.setMemberCardNo(memberInfo.getMemberCardNo());
                refund.setMainClerkName(memberInfo.getMainClerkName());
                refund.setMainStoreName(memberInfo.getMainStoreName());
                refund.setOpenClerkName(memberInfo.getOpenClerkName());
                refund.setOpenStoreName(memberInfo.getOpenStoreName());
            }
            if (null != exchange) {
                exchange.setMemberId(memberId);
                exchange.setMemberName(memberInfo.getMemberName());
                exchange.setMemberImage(memberInfo.getMemberImage());
                exchange.setMemberCardNo(memberInfo.getMemberCardNo());
                exchange.setMainClerkName(memberInfo.getMainClerkName());
                exchange.setMainStoreName(memberInfo.getMainStoreName());
                exchange.setOpenClerkName(memberInfo.getOpenClerkName());
                exchange.setOpenStoreName(memberInfo.getOpenStoreName());
            }
        }
    }
    
    private OperationUserQDTO getOper(String clerkId) {
        ClerkDTO clerk = this.clerkService.getclerkById(clerkId) ;
        OperationUserQDTO dto = new OperationUserQDTO() ;
        if(null == clerk) {
            return dto ;
        }
        dto.setOperatorId(clerk.getClerkId()) ;
        dto.setOperatorType(clerk.getClerkType());
        dto.setOperatorName(clerk.getClerkName());
        dto.setOperatorCode(clerk.getClerkCode());
        return dto ;
    }

}
