package cn.xluobo.business.sc.order.service;

import cn.xluobo.business.sys.receipt.repo.model.SysReceiptAccount;
import cn.xluobo.business.sys.receipt.service.ISysReceiptAccountService;
import cn.xluobo.core.page.RespPage;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.core.api.APIResponse;
import com.ruoyi.core.api.ApiResEnums;
import com.ruoyi.school.member.domain.resp.MemberCardVO;
import com.ruoyi.school.member.service.IScMemberCardService;
import com.ruoyi.school.order.domain.ScOrder;
import com.ruoyi.school.order.domain.req.ReqSearchScOrder;
import com.ruoyi.school.order.domain.resp.RespOrder;
import com.ruoyi.school.order.enums.OrderStatusEnum;
import com.ruoyi.school.order.mapper.ScOrderMapper;
import com.ruoyi.school.order.service.IScOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author ：zhangbaoyu
 * @date ：Created in 2020-01-14 17:24
 */
@Service
@Transactional
@Slf4j
public class BusinessScOrderService {

    @Autowired
    private IScOrderService scOrderService;

    @Autowired
    private ScOrderMapper orderMapper;



    @Autowired
    private IScMemberCardService memberCardService;
    @Autowired
    private ISysReceiptAccountService accountService;

    /**
     * 查询
     *
     * @param reqSearchScOrder
     * @return
     */
    public APIResponse searchList(ReqSearchScOrder reqSearchScOrder) {
        RespPage<RespOrder> page = new RespPage<>(reqSearchScOrder.getPageNum(), reqSearchScOrder.getPageSize());
        List<RespOrder> orderList = orderMapper.selectFroSearchTable(reqSearchScOrder, page);
        page.setRows(orderList);
        return APIResponse.toAPIResponse(page);
    }

    /**
     * 详情
     *
     * @param orderId
     * @return
     */
    public APIResponse detailById(Long orderId) {
        if (null == orderId) {
            return APIResponse.toAPIResponse(null);
        }
        Map<String, Object> detailMap = Maps.newHashMap();

        // 订单信息
        ScOrder order = scOrderService.getById(orderId);
        detailMap.put("orderInfo", order);

        // 会员卡详情
        MemberCardVO memberCardVO=memberCardService.getByCardNo(order.getCardNo());
        detailMap.put("orderDetail", memberCardVO);

        // 收款账户
        SysReceiptAccount account = accountService.getById(order.getAccountId());
        detailMap.put("orderAccount", account);

        return APIResponse.toAPIResponse(detailMap);
    }


    /**
     * 作废订单
     *
     * @param orderIds
     * @return
     */
    @Transactional
    public APIResponse invalidById(Long[] orderIds) {
        if (null == orderIds || orderIds.length == 0) {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();

        Integer dealSuccessCnt = 0;
        Integer dealFailCnt = 0;
        StringBuffer errorSb = new StringBuffer();

        for (Long orderId : orderIds) {
            ScOrder order = scOrderService.getById(orderId);
            if (null == order) {
                errorSb.append("订单'").append(orderId).append("',");
                errorSb.append("无法获取订单信息,请稍后重试;");
                dealFailCnt++;
                continue;
            }
            if (OrderStatusEnum.INVALID.getOrderStatus().equals(order.getOrderStatus())) {
                errorSb.append("订单'").append(orderId).append("',");
                errorSb.append("该订单已作废,无法再次作废;");
                dealFailCnt++;
                continue;
            }
//            相关会员卡
            MemberCardVO memberCardVO=memberCardService.getByCardNo(order.getCardNo());
            if(memberCardVO.getChargeType().equals("count") ){
                if (memberCardVO.getTotalCount().compareTo(memberCardVO.getRemainingCount())!=0)
                { errorSb.append("订单'").append(orderId).append("',");
                    errorSb.append("订单中的会员卡已经开始使用，无法作废;");
                    dealFailCnt++;
                    continue;
                }
            }
            if (memberCardVO.getChargeType().equals("days") ){
                if (!memberCardVO.getTotalDays().equals(memberCardVO.getRemainingDays())){
                    errorSb.append("订单'").append(orderId).append("',");
                    errorSb.append("订单中的会员卡已经开始使用，无法作废;");
                    dealFailCnt++;
                    continue;
                }

            }
            if (memberCardVO.getChargeType().equals("total_fee")){
                if (memberCardVO.getTotalFee().compareTo(memberCardVO.getRemainingTotalFee())!=0){
                    errorSb.append("订单'").append(orderId).append("',");
                    errorSb.append("订单中的会员卡已经开始使用，无法作废;");
                    dealFailCnt++;
                    continue;
                }
            }
//            // 订单作废
            scOrderService.invalidOrder(orderId);
            memberCardService.suspendCard(memberCardVO.getId());
        }

        if (dealFailCnt == 0) {
            return APIResponse.toOkResponse();
        } else {
            return APIResponse.toExceptionResponse("操作失败,成功:" + dealSuccessCnt + ",失败:" + dealFailCnt + ",原因如下:" + errorSb.toString());
        }


    }
}
