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

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.business.order.dto.ordermanage.OrderDetailDTO;
import com.gic.business.order.qdto.ordermanage.QueryOrderDetailQDTO;
import com.gic.business.order.service.ordermanage.WebOrderManageApiService;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.GlobalInfo;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.manage.web.controller.order.GicOrderController;
import com.gic.haoban.manage.web.vo.coupon.CoupCardVO;
import com.gic.haoban.manage.web.vo.order.OrderDetailVO;
import com.gic.haoban.manage.web.vo.scan.ScanDetailVO;
import com.gic.marketing.api.dto.CoupCardDTO;
import com.gic.marketing.api.out.service.CouponHBOuterService;
import com.gic.marketing.api.qdto.card.HaobanWriteOffCardQDTO;
import org.apache.commons.collections.CollectionUtils;
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.RestController;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 工作台
 */
@RestController
@RequestMapping("/scan")
public class ScanController {

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

    @Autowired
    GicOrderController getOrderDetail;
    @Autowired
    private WebOrderManageApiService webOrderManageApiService;
    @Autowired
    private CouponHBOuterService couponHBOuterService;
    @Autowired
    private ClerkService clerkService;

    /**
     * 原有扫码接口聚合
     * @see GicOrderController#scan(String, String, String)
     * @param enterpriseId  企业id
     * @param writeOffCode  核销码
     * @param storeId   门店id
     * @param clerkId   导购id
     * @param analysisFlag 是否扫码 1是 0否
     * @return
     */
    @RequestMapping("/all")
    public RestResponse<ScanDetailVO> scan(String enterpriseId, String writeOffCode, String storeId,String clerkId,Integer analysisFlag) {
        if (StringUtils.isEmpty(writeOffCode)) {
            return RestResponse.failure("9999", "核销码为空");
        }
        ScanDetailVO scanDetailVO = new ScanDetailVO();
        // 通过核销码查询
        QueryOrderDetailQDTO qdto = new QueryOrderDetailQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setWriteOffCode(writeOffCode);
        ServiceResponse<OrderDetailDTO> ret = webOrderManageApiService.getOrderDetail(qdto);
        OrderDetailDTO detail = ret.getResult();
        logger.info("订单信息={}", JSON.toJSONString(ret));
        //订单
        if (ret.isSuccess() && detail != null) {
            // 已核销,且不是好办核销的
            if (null != detail.getOrderInfo().getDeliveryOptType()
                    && detail.getOrderInfo().getDeliveryOptType() != 1) {
                logger.info("已核销,且不是好办核销的={}", writeOffCode);
                scanDetailVO.setOrderError("此自提点无法核销");
            }
            if (!storeId.equals(detail.getOrderInfo().getPickUpStoreId())) {
                scanDetailVO.setOrderError("此自提点无法核销");
            }
            OrderDetailVO orderDetailVO = getOrderDetail.getOrderDetail(enterpriseId, ret.getResult().getOrderInfo(),
                    ret.getResult().getOrderItemList(), storeId);
            if (!(orderDetailVO.getOrderStep().equals("2") || orderDetailVO.getOrderStep().equals("4"))) {
                scanDetailVO.setOrderError("核销订单不存在");
            }
            Date pickOverTime = detail.getOrderInfo().getPickUpOverTime();
            if (null != pickOverTime && pickOverTime.before(new Date())) {
                scanDetailVO.setOrderError("此订单自提时间已截止");
            }
            scanDetailVO.setOrderDetailVO(orderDetailVO);
        }

        //卡券
        HaobanWriteOffCardQDTO writeOffCardQDTO = new HaobanWriteOffCardQDTO();
        writeOffCardQDTO.setEnterpriseId(enterpriseId);
        writeOffCardQDTO.setCardCode(writeOffCode);
        writeOffCardQDTO.setClerkId(clerkId);
        writeOffCardQDTO.setCardType(2);
        writeOffCardQDTO.setAnalysisFlag(analysisFlag);
        ServiceResponse<List<CoupCardDTO>> couponRet = couponHBOuterService.getCardLogByCode(writeOffCardQDTO);
        if (couponRet.isSuccess() && CollectionUtils.isNotEmpty(couponRet.getResult())) {
            List<CoupCardDTO> couponList = couponRet.getResult();
            CoupCardDTO coupCardDTO = couponList.get(0);
            if (couponList.size() > 1) {
                scanDetailVO.setCouponError("识别到多张兑换券，为防止核销错误，请协助会员，在会员小程序中进行兑换券核销");
                scanDetailVO.setCouponErrorType(1);
            }else {
                boolean checkStore = coupCardDTO.isCheckStore();
                if (!checkStore) {
                    scanDetailVO.setCouponError("兑换券在本店不可用");
                }
                Integer verificationType = coupCardDTO.getVerificationType();
                if (!Objects.equals(verificationType, 0)) {
                    scanDetailVO.setCouponError("请通过收银台核销此兑换券");
                }
            }
            CoupCardVO cardVO = EntityUtil.changeEntityNew(CoupCardVO.class, coupCardDTO);
            if (Objects.equals(GlobalInfo.COUPON_STATUS_USED, coupCardDTO.getStatus())) {
                cardVO.setStoreName(coupCardDTO.getOrderStoreName());
                cardVO.setClerkName(coupCardDTO.getOrderClerkName());
            }else {
                ClerkDTO clerkDTO = clerkService.getclerkById(clerkId);
                if (clerkDTO != null) {
                    cardVO.setStoreName(clerkDTO.getStoreName());
                    cardVO.setClerkName(clerkDTO.getClerkName());
                }
            }
            cardVO.setUseTime(coupCardDTO.getUseTime());
            scanDetailVO.setCardVO(cardVO);
        }
        return RestResponse.successResult(scanDetailVO);
    }
}
