package cn.pluss.platform.merchant.impl;

import cn.pluss.platform.entity.MerchantCashPlace;
import cn.pluss.platform.entity.MerchantCashPlaceStaff;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantCashPlaceStaffMapper;
import cn.pluss.platform.merchant.MerchantCashPlaceService;
import cn.pluss.platform.merchant.MerchantCashPlaceStaffService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.vo.MerchantCashPlaceStaffVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 收银点和员工关联记录表 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2021-03-23
 */
@Service
public class MerchantCashPlaceStaffServiceImpl extends ServiceImpl<MerchantCashPlaceStaffMapper, MerchantCashPlaceStaff> implements MerchantCashPlaceStaffService {

    @Setter(onMethod_ = {@Autowired})
    private UserAppService userAppService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantCashPlaceService cashPlaceService;

    @Override
    public void bindCashPlace(Long userId, MerchantCashPlace cashPlace) {

        UserApp tokenUserApp = userAppService.queryUserAppByToken();
        if (cashPlace == null || cashPlace.getId() == null) {
            throw new MsgException("缺少收银台信息");
        }

        UserApp userApp = new UserApp().setUserId(userId);
        userApp = userAppService.getOne(new QueryWrapper<>(userApp));

        if (userApp == null) {
            throw new MsgException("未找到用户信息");
        }

        if (!"staff".equals(userApp.getUserType())) {
            throw new MsgException("当前用户不是员工");
        }

        UserApp userAppBoss = new UserApp()
                .setMerchantCode(tokenUserApp.getMerchantCode())
                .setUserType("promoter");
        userAppBoss = userAppService.getOne(new QueryWrapper<>(userAppBoss));

        if (userAppBoss == null) {
            throw new MsgException("当前店主信息不存在");
        }

        if (cashPlace.getUserId() == null) {
            cashPlace = cashPlaceService.getOne(new QueryWrapper<>(cashPlace));

            if (cashPlace == null) {
                throw new MsgException("收银点不存在");
            }
        }

        MerchantCashPlaceStaff cashPlaceStaff = new MerchantCashPlaceStaff();
        cashPlaceStaff.setCashPlaceId(cashPlace.getId());
        cashPlaceStaff.setUserId(userApp.getUserId());
        cashPlaceStaff.setStatus(MerchantCashPlaceStaff.STATUS_ONLINE);

        save(cashPlaceStaff);
    }

    @Override
    public void bindCashPlace(Long userId, String cashPlaceCode) {
        MerchantCashPlace merchantCashPlace = new MerchantCashPlace().setCode(cashPlaceCode);
        merchantCashPlace = cashPlaceService.getOne(new QueryWrapper<>(merchantCashPlace));

        if (merchantCashPlace == null) {
            throw new MsgException("收银点不存在");
        }

        MerchantCashPlaceStaff cashPlaceStaff = new MerchantCashPlaceStaff();
        cashPlaceStaff.setCashPlaceId(merchantCashPlace.getId());
        cashPlaceStaff.setStatus(MerchantCashPlaceStaff.STATUS_ONLINE);
        QueryWrapper<MerchantCashPlaceStaff> qW = new QueryWrapper<>(cashPlaceStaff);
        cashPlaceStaff = getOne(qW);

        if (cashPlaceStaff != null) {
            UserApp userApp = new UserApp().setUserId(cashPlaceStaff.getUserId());
            userApp = userAppService.getOne(new QueryWrapper<>(userApp));

            if (userApp != null) {
                throw new MsgException("请联系 “" + userApp.getUserName() + "” 签退");
            } else {
                // 员工被删除后就直接将记录在线记录清除
                offLineCashPlace(merchantCashPlace);
            }
        }

        bindCashPlace(userId, merchantCashPlace);
    }

    @Override
    public void offLine(Long userId) {
        MerchantCashPlaceStaff cashPlaceStaff = new MerchantCashPlaceStaff();
        cashPlaceStaff.setUserId(userId);
        cashPlaceStaff.setStatus(MerchantCashPlaceStaff.STATUS_LEAVE);
        UpdateWrapper<MerchantCashPlaceStaff> uW = new UpdateWrapper<>();
        uW.eq("userId", userId);
        uW.eq("status", MerchantCashPlaceStaff.STATUS_ONLINE);
        update(cashPlaceStaff, uW);
    }

    @Override
    public void offLineCashPlace(MerchantCashPlace cashPlace) {
        if (cashPlace.getId() == null) {
            throw new MsgException("收银点id为空");
        }

        MerchantCashPlaceStaff cashPlaceStaff = new MerchantCashPlaceStaff();
        cashPlaceStaff.setCashPlaceId(cashPlace.getId());
        cashPlaceStaff.setStatus(MerchantCashPlaceStaff.STATUS_LEAVE);
        UpdateWrapper<MerchantCashPlaceStaff> uW = new UpdateWrapper<>();
        uW.eq("cashPlaceId", cashPlace.getId());
        uW.eq("status", MerchantCashPlaceStaff.STATUS_ONLINE);
        update(cashPlaceStaff, uW);
    }

    @Override
    public void offLineCashPlace(String cashPlaceCode) {
        MerchantCashPlace merchantCashPlace = new MerchantCashPlace().setCode(cashPlaceCode);
        merchantCashPlace = cashPlaceService.getOne(new QueryWrapper<>(merchantCashPlace));
        offLineCashPlace(merchantCashPlace);
    }

    @Override
    public UserApp getCurStaffFromCashPlace(MerchantCashPlace cashPlace) {
        if (cashPlace.getId() == null) {
            throw new MsgException("缺少收银台id");
        }

        MerchantCashPlaceStaff cashPlaceStaff = new MerchantCashPlaceStaff();
        cashPlaceStaff.setCashPlaceId(cashPlace.getId());
        QueryWrapper<MerchantCashPlaceStaff> qW = new QueryWrapper<>(cashPlaceStaff);
        qW.last("limit 1");
        qW.orderByDesc("updateTime");

        cashPlaceStaff = getOne(qW);
        if (cashPlaceStaff == null || !MerchantCashPlaceStaff.STATUS_ONLINE.equals(cashPlaceStaff.getStatus())) {
            return null;
        }

        UserApp userApp = new UserApp().setUserId(cashPlaceStaff.getUserId());
        userApp = userAppService.getOne(new QueryWrapper<>(userApp));

        return userApp;
    }

    @Override
    public Page<MerchantCashPlaceStaffVO> getRecord(Page<MerchantCashPlaceStaff> page, MerchantCashPlaceStaff condition, OrderItem orderItem) {
        if (condition.getCashPlaceId() == null && condition.getUserId() == null) {
            throw new MsgException("需要传员工id或收银点id");
        }
        page.getOrders().clear();
        page.getOrders().add(orderItem);

        val qWrapper = new QueryWrapper<>();
        qWrapper.eq(condition.getUserId() != null, "mcps.userId", condition.getUserId());
        qWrapper.eq(condition.getCashPlaceId() != null, "mcps.cashPlaceId", condition.getCashPlaceId());
        qWrapper.eq(StringUtils.isNotBlank(condition.getStatus()), "mcps.status", condition.getStatus());
        Page<MerchantCashPlaceStaffVO> pageData = baseMapper.selectCustom(page, qWrapper);

        if (pageData.getRecords().isEmpty()) {
            return pageData;
        }

        Set<Integer> cashPlaceIdSet = new HashSet<>();
        for (MerchantCashPlaceStaff record : pageData.getRecords()) {
            cashPlaceIdSet.add(record.getCashPlaceId());
        }

        QueryWrapper<MerchantCashPlace> qWrapper2 = new QueryWrapper<>();
        qWrapper2.in("id", cashPlaceIdSet);
        List<MerchantCashPlace> cashPlaceList = cashPlaceService.list(qWrapper2);

        for (MerchantCashPlaceStaffVO record : pageData.getRecords()) {
            for (MerchantCashPlace cashPlace : cashPlaceList) {
                if (record.getCashPlaceId().equals(cashPlace.getId())) {
                    record.setMerchantCashPlace(cashPlace);
                    break;
                }
            }
        }

        return pageData;
    }
}
