package com.gree.mall.miniapp.logic.material;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.gree.mall.miniapp.bean.material.MyDataCountBean;
import com.gree.mall.miniapp.bean.material.PartsApplyBean;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.bean.workorder.OrderFlagLogic;
import com.gree.mall.miniapp.commonmapper.CommonMapper;
import com.gree.mall.miniapp.enums.material.PartsApplyStatusEnum;
import com.gree.mall.miniapp.enums.workorder.OrderFlagEnum;
import com.gree.mall.miniapp.enums.workorder.OrderTypeEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.plus.entity.PgOrderBase;
import com.gree.mall.miniapp.plus.entity.WebsitPartsApply;
import com.gree.mall.miniapp.plus.entity.WebsitPartsApplyItem;
import com.gree.mall.miniapp.plus.service.PgOrderBaseService;
import com.gree.mall.miniapp.plus.service.WebsitPartsApplyItemService;
import com.gree.mall.miniapp.plus.service.WebsitPartsApplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class PartsApplyLogic {

    private final CommonLogic commonLogic;
    private final CommonMapper commonMapper;
    private final PgOrderBaseService pgOrderBaseService;
    private final WebsitPartsApplyService websitPartsApplyService;
    private final WebsitPartsApplyItemService websitPartsApplyItemService;
    private final OrderFlagLogic orderFlagLogic;


    public IPage<WebsitPartsApply> list(String status, Integer pageNum, Integer pageSize, HttpServletRequest request) {
        final CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat();
        return websitPartsApplyService.lambdaQuery()
                .eq(WebsitPartsApply::getCompanyWechatId, wechat.getCurrentCompanyWechatId())
                .eq(WebsitPartsApply::getCreateById, wechat.getUser().getUserId())
                .eq(StringUtils.isNotBlank(status), WebsitPartsApply::getStatus, status)
                .orderByDesc(WebsitPartsApply::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
    }

    public PartsApplyBean detail(String id) {
        PartsApplyBean bean = new PartsApplyBean();
        final WebsitPartsApply apply = websitPartsApplyService.getById(id);
        BeanUtils.copyProperties(apply, bean);
        final List<WebsitPartsApplyItem> items = websitPartsApplyItemService.lambdaQuery()
                .eq(WebsitPartsApplyItem::getWebsitPartsApplyId, id)
                .list();
        bean.setItems(items);
        return bean;
    }

    @Transactional
    public String add(PartsApplyBean bean) {
        final CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat();
        if (StringUtils.isBlank(bean.getOrderBaseId())) {
            throw new RemoteServiceException("工单单号不能为空");
        }
        final PgOrderBase orderBase = pgOrderBaseService.getById(bean.getOrderBaseId());
        if (!orderBase.getOrderType().equals(OrderTypeEnum.REPAIR.getKey())) {
            throw new RemoteServiceException("非维修工单，申请失败");
        }
        if (orderBase.getOrderStatus().equals(OrderFlagEnum.YWG.getKey())) {
            throw new RemoteServiceException("工单已完工，申请失败");
        }
        if (CollectionUtil.isEmpty(bean.getItems())) {
            throw new RemoteServiceException("申请明细不能为空");
        }
        String applyId = IdWorker.getIdStr();
        int totalQty = 0;
        for (int i = 0; i < bean.getItems().size(); i++) {
            WebsitPartsApplyItem item = bean.getItems().get(i);
            if (StringUtils.isBlank(item.getName())) {
                throw new RemoteServiceException("第" + (i+1) + "行，配件名称不能为空");
            }
            if (Objects.isNull(item.getQty()) || item.getQty() <= 0) {
                throw new RemoteServiceException("第" + (i+1) + "行，配件数量格式异常");
            }
            totalQty = totalQty + item.getQty();
            item.setWebsitPartsApplyId(applyId);
        }

        bean.setId(applyId)
                .setCompanyWechatId(wechat.getCompanyWechatId())
                .setCompanyWechatName(wechat.getCompanyName())
                .setUserMobile(orderBase.getUserMobile())
                .setStatus(PartsApplyStatusEnum.ING.getKey())
                .setTotalQty(totalQty)
                .setCreateById(wechat.getUserId())
                .setWebsitId(orderBase.getWebsitId())
                .setWebsitName(orderBase.getWebsitName())
                .insert();

        websitPartsApplyItemService.saveBatch(bean.getItems());

        orderFlagLogic.saveOrderFlag(Lists.newArrayList(orderBase.getId()), OrderFlagEnum.PARTS_ING);
        return applyId;
    }

    @Transactional
    public void cancel(String id) {
        final CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat();
        final WebsitPartsApply apply = websitPartsApplyService.getById(id);
        websitPartsApplyService.lambdaUpdate()
                .set(WebsitPartsApply::getStatus, PartsApplyStatusEnum.CANCEL.getKey())
                .set(WebsitPartsApply::getCancelBy, wechat.getUser().getNickName())
                .set(WebsitPartsApply::getCancelTime, DateUtil.date())
                .eq(WebsitPartsApply::getStatus, PartsApplyStatusEnum.ING.getKey())
                .eq(WebsitPartsApply::getId, id)
                .eq(WebsitPartsApply::getCreateById, wechat.getUserId())
                .update();

        final Integer count = websitPartsApplyService.lambdaQuery()
                .eq(WebsitPartsApply::getOrderBaseId, apply.getOrderBaseId())
                .eq(WebsitPartsApply::getStatus, PartsApplyStatusEnum.ING.getKey())
                .count();
        if (count == 0) {
            orderFlagLogic.deleteOrderFlag(apply.getOrderBaseId(), OrderFlagEnum.PARTS_ING);
        }

        orderFlagLogic.saveOrderFlag(Lists.newArrayList(apply.getOrderBaseId()), OrderFlagEnum.PARTS_CANCEL);
    }

    public MyDataCountBean count(HttpServletRequest request) {
        final CurrentCompanyWechat wechat = commonLogic.getCurrentCompanyWechat();
        MyDataCountBean countBean = commonMapper.partsApplyCount(wechat.getUser().getUserId());
        return countBean;
    }
}
