package com.jeequan.jeepay.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.db.entity.StoreUserWorkRecord;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.db.entity.SysUserMchStoreRela;
import com.jeequan.jeepay.service.mapper.StatsTradeMapper;
import com.jeequan.jeepay.service.mapper.StoreUserWorkRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商户员工交接班记录表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2023-01-28
 */
@Service
public class StoreUserWorkRecordService extends ServiceImpl<StoreUserWorkRecordMapper, StoreUserWorkRecord> {

    @Autowired private SysUserMchStoreRelaService sysUserMchStoreRelaService;
    @Autowired private StatsTradeMapper statsTradeMapper;

    /**
     * 交接班 上班新增一条记录，下班更新记录
     */
    @Transactional
    public void addOrUpdateWorkAndUser(byte workState, SysUserEntity sysUserEntity, String loginType, String storeId){

        StoreUserWorkRecord storeUserWorkRecord = new StoreUserWorkRecord();

        // 上班打卡
        if (workState == StoreUserWorkRecord.WORK_STATE_START){
            storeUserWorkRecord.setSysUserId(sysUserEntity.getSysUserId());
            storeUserWorkRecord.setLoginUsername(sysUserEntity.getLoginUsername());
            storeUserWorkRecord.setRealname(sysUserEntity.getRealname());
            storeUserWorkRecord.setUserNo(sysUserEntity.getUserNo());
            storeUserWorkRecord.setMchNo(sysUserEntity.getBelongInfoId());
            storeUserWorkRecord.setStoreId(storeId);
            storeUserWorkRecord.setWorkStartTime(DateTime.now());
            storeUserWorkRecord.setLoginPageType(loginType);

            List<SysUserMchStoreRela> mchStoreRelaList= sysUserMchStoreRelaService.list(SysUserMchStoreRela.gw().eq(SysUserMchStoreRela::getSysUserId, sysUserEntity.getSysUserId()));
            // 店员 只能绑一个门店
            if (SysUser.UEST_TYPE_CASHIER == sysUserEntity.getUserType()){
                storeUserWorkRecord.setStoreId(mchStoreRelaList.get(0).getStoreId());
            }
            this.save(storeUserWorkRecord);
        }
        // 下班打卡
        if (workState == StoreUserWorkRecord.WORK_STATE_END){
            StoreUserWorkRecord queryStoreUserWorkRecord = this.getBaseMapper().selectOne(StoreUserWorkRecord.gw()
                    .eq(StoreUserWorkRecord::getSysUserId, sysUserEntity.getSysUserId())
                    .eq(StoreUserWorkRecord::getStoreId, storeId)
                    .isNotNull(StoreUserWorkRecord::getWorkStartTime)
                    .orderByDesc(StoreUserWorkRecord::getWorkStartTime)
                    .last("limit 1"));

            storeUserWorkRecord.setId(queryStoreUserWorkRecord.getId());
            storeUserWorkRecord.setWorkEndTime(DateTime.now());
            storeUserWorkRecord.setLogoutPageType(loginType);

            String workStartTime = DateUtil.formatDateTime(queryStoreUserWorkRecord.getWorkStartTime());
            String workEndTime = DateUtil.formatDateTime(storeUserWorkRecord.getWorkEndTime());
            JSONObject workCount = this.workCount(sysUserEntity.getSysUserId(), workStartTime, workEndTime, Arrays.asList(storeId));
            storeUserWorkRecord.setRefundCount(workCount.getLong("refundCount"));
            storeUserWorkRecord.setRefundAmount(workCount.getLong("refundAmount"));
            storeUserWorkRecord.setSuccessCount(workCount.getLong("payCount"));
            storeUserWorkRecord.setSuccessAmount(workCount.getLong("payAmount"));
            this.updateById(storeUserWorkRecord);
        }
    }

    /**
     * 交班统计
     * */
    public JSONObject workCount(Long storeUserId, String workStartTime, String workEndTime, List<String> storeIdList) {

        Map<String, Object> params = new HashMap<>();
        if (workStartTime != null) params.put("createdStart", workStartTime);
        if (workEndTime != null) params.put("createdEnd", workEndTime);
        if (storeUserId != null) params.put("storeUserId", storeUserId);
        if (CollUtil.isNotEmpty(storeIdList)) params.put("storeIdList", storeIdList);

        return statsTradeMapper.selectTodayPayCount(params);
    }

    /**
     * 查询某门店下  用户上班状态，存在记录为上班，无记录为下班
     * */
    public byte getWorkState(String storeId, Long sysUserId) {
        StoreUserWorkRecord userWorkRecord = this.getOne(StoreUserWorkRecord.gw()
                .eq(StoreUserWorkRecord::getSysUserId, sysUserId)
                .eq(StoreUserWorkRecord::getStoreId, storeId)
                .isNotNull(StoreUserWorkRecord::getWorkStartTime)
                .orderByDesc(StoreUserWorkRecord::getWorkStartTime)
                .last("limit 1")
        );
        if (userWorkRecord != null && userWorkRecord.getWorkEndTime() == null) {
            return StoreUserWorkRecord.WORK_STATE_START;
        }
        return StoreUserWorkRecord.WORK_STATE_END;
    }
}
