package com.jeequan.jeepay.mch.ctrl.store;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.jwt.JWTPayload;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.StoreUserWorkRecord;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.StoreUserWorkRecordService;
import com.jeequan.jeepay.service.impl.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 商户员工交接班记录管理
 *
 * @author yr
 * 
 * @date 2023/01/31 10:21
 */
@Slf4j
@RestController
@RequestMapping("/api/user/workRecords")
public class StoreUserWorkRecordController extends CommonCtrl {

    @Autowired private SysUserService sysUserService;
    @Autowired private StoreUserWorkRecordService storeUserWorkRecordService;

    /**
     * 交接班列表查询
     */
    @GetMapping
    public ApiRes list() {
        StoreUserWorkRecord queryRecord = getObject(StoreUserWorkRecord.class);
        LambdaQueryWrapper<StoreUserWorkRecord> gw = StoreUserWorkRecord.gw();
        gw.eq(StoreUserWorkRecord::getMchNo, getCurrentMchNo());

        String storeId = queryRecord.getStoreId();
        // 刷脸设备，只能查看其绑定门店
        if (JWTPayload.LOGIN_PAGE_TYPE.FACE_APP.equals(getCurrentUser().getLoginType())) {
            storeId = getCurrentUser().getStoreIdList().get(0);
        }
        gw.eq(storeId!= null, StoreUserWorkRecord::getStoreId, storeId);

        Byte userType = getCurrentUser().getSysUser().getUserType();
        // 店员 只能看自己
        if (SysUser.UEST_TYPE_CASHIER == userType){
            gw.eq(StoreUserWorkRecord::getSysUserId, getCurrentUser().getSysUserId());
        }
        if (StringUtils.isNotEmpty(queryRecord.getUserNo())){
            gw.eq(StoreUserWorkRecord::getUserNo, queryRecord.getUserNo());
        }
        if (StringUtils.isNotEmpty(queryRecord.getRealname())){
            gw.like(StoreUserWorkRecord::getRealname, queryRecord.getRealname());
        }
        // 时间搜索
        Date[] searchDateRange = queryRecord.buildQueryDateRange();
        gw.ge(searchDateRange[0] != null, StoreUserWorkRecord::getCreatedAt, searchDateRange[0]);
        gw.le(searchDateRange[1] != null, StoreUserWorkRecord::getCreatedAt, searchDateRange[1]);
        gw.orderByDesc(StoreUserWorkRecord::getCreatedAt);
        IPage<StoreUserWorkRecord> page = storeUserWorkRecordService.page(getIPage(true), gw);
        //返回数据
        return ApiRes.page(page);
    }

    /**
     * 交接班详情
     */
    @GetMapping("/{id}")
    public ApiRes detail(@PathVariable("id") Long id) {
        StoreUserWorkRecord workRecord = storeUserWorkRecordService.getById(id);
        workRecord.addExt("payAmount", workRecord.getSuccessAmount());
        workRecord.addExt("payCount", workRecord.getSuccessCount());
        return ApiRes.ok(workRecord);
    }

    /**
     * 员工交接班打卡
     */
    @MethodLog(remark = "员工交接班打卡")
    @PostMapping
    public ApiRes addOrUpdate() {
        Byte workState = getValByte("workState");
        if (workState != StoreUserWorkRecord.WORK_STATE_START && workState != StoreUserWorkRecord.WORK_STATE_END){
            throw new BizException("请选择是上班还是下班打卡！");
        }

        // 目前仅支持刷脸设备上下班打卡
        if (!JWTPayload.LOGIN_PAGE_TYPE.FACE_APP.equals(getCurrentUser().getLoginType())) {
            throw new BizException("仅支持刷脸设备打卡");
        }
        // 设备绑定门店ID
        String storeId = getCurrentUser().getStoreIdList().get(0);

        SysUserEntity sysUserEntity = sysUserService.getById(getCurrentUser().getSysUserId());

        // 获取当前用户的上班状态
        Byte currentWorkState = storeUserWorkRecordService.getWorkState(storeId, sysUserEntity.getSysUserId());
        if (currentWorkState.equals(workState)){
            throw new BizException("请勿重复打卡！");
        }

        try {
            storeUserWorkRecordService.addOrUpdateWorkAndUser(workState, sysUserEntity, getCurrentUser().getLoginType(), storeId);
        } catch (Exception e){
            log.error("【员工交接班打卡】异常", e);
            throw new BizException("打卡失败，请稍后重试！");
        }
        return ApiRes.ok();
    }

    /**
     * 员工交班统计
     */
    @MethodLog(remark = "员工交班统计")
    @GetMapping("/stats")
    public ApiRes stats() {

        StoreUserWorkRecord latestWorkRecord = storeUserWorkRecordService.getOne(StoreUserWorkRecord.gw()
                .eq(StoreUserWorkRecord::getSysUserId, getCurrentUser().getSysUserId())
                .orderByDesc(StoreUserWorkRecord::getCreatedAt)
                .last("limit 1"));
        if (latestWorkRecord == null) {
            return ApiRes.ok();
        }

        String workStartTime = DateUtil.formatDateTime(latestWorkRecord.getWorkStartTime()); // 上班时间
        String workEndTime = DateUtil.now(); // 下班时间
        if (latestWorkRecord.getWorkEndTime() != null) {
            workEndTime = DateUtil.formatDateTime(latestWorkRecord.getWorkEndTime());
        }

        JSONObject reqParamJSON = new JSONObject();
        reqParamJSON.put("storeUserId", getCurrentUser().getSysUserId());
        reqParamJSON.put("workStartTime", workStartTime);
        reqParamJSON.put("workEndTime", workEndTime);

        // 目前仅支持刷脸设备上下班打卡
        if (!JWTPayload.LOGIN_PAGE_TYPE.FACE_APP.equals(getCurrentUser().getLoginType())) {
            throw new BizException("仅支持刷脸设备");
        }

        JSONObject resJSON = storeUserWorkRecordService.workCount(getCurrentUser().getSysUserId(), workStartTime, workEndTime, getCurrentUser().getStoreIdList());
        resJSON.put("workStartTime", workStartTime);
        resJSON.put("workEndTime", workEndTime);

        return ApiRes.ok(resJSON);
    }

}
