/*
 * Copyright 2017-2020 吴学文 and java110 team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.java110.user.cmd.property;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.po.property.AttendanceRecordPo;
import com.java110.user.dao.property.IAttendanceRecordV1ServiceDao;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 上下班打卡接口：记录打卡时间、地点、坐标，校验重复打卡
 * 服务编码：property.attendancePunch
 * 请求路径：/app/property.attendancePunch
 */
@Java110Cmd(serviceCode = "property.attendancePunch")
public class AttendancePunchCmd extends Cmd {

    private static Logger logger = LoggerFactory.getLogger(AttendancePunchCmd.class);

    @Autowired
    private IAttendanceRecordV1ServiceDao attendanceRecordV1ServiceDao;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) {
        Assert.hasKeyAndValue(reqJson, "userId", "未包含用户ID");
        Assert.hasKeyAndValue(reqJson, "punchType", "未包含打卡类型");
        String punchType = reqJson.getString("punchType");
        Assert.isTrue("ON".equals(punchType) || "OFF".equals(punchType),
                "打卡类型必须为: ON(上班)/OFF(下班)");
        // 打卡必须关联定位坐标
        Assert.hasKeyAndValue(reqJson, "longitude", "未包含经度，打卡需要定位信息");
        Assert.hasKeyAndValue(reqJson, "latitude", "未包含纬度，打卡需要定位信息");
    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        String userId = reqJson.getString("userId");
        String punchType = reqJson.getString("punchType");
        String typeName = "ON".equals(punchType) ? "上班" : "下班";

        // 1. 当天同类型打卡不超过3次
        Map countParams = new HashMap<>();
        countParams.put("userId", userId);
        countParams.put("punchType", punchType);
        int todayCount = attendanceRecordV1ServiceDao.countTodayByType(countParams);
        if (todayCount >= 3) {
            throw new CmdException("今日" + typeName + "打卡已达3次，无法继续打卡");
        }

        // 2. 检查最近一次打卡时间，同类型需间隔7小时
        Map lastPunchParams = new HashMap<>();
        lastPunchParams.put("userId", userId);
        Map lastPunch = attendanceRecordV1ServiceDao.getLastPunch(lastPunchParams);
        if (lastPunch != null) {
            Date lastPunchTime = (Date) lastPunch.get("punch_time");
            Calendar cal = Calendar.getInstance();
            cal.setTime(lastPunchTime);
            cal.add(Calendar.HOUR_OF_DAY, 7);
            if (new Date().before(cal.getTime())) {
                String lastType = "ON".equals(lastPunch.get("punch_type")) ? "上班" : "下班";
                throw new CmdException("上次" + lastType + "打卡时间不足7小时，请" +
                    new java.text.SimpleDateFormat("HH:mm").format(cal.getTime()) + "后再打卡");
            }
        }

        AttendanceRecordPo po = new AttendanceRecordPo();
        po.setId(GenerateCodeFactory.getGeneratorId("10"));
        po.setUserId(userId);
        po.setUserName(reqJson.containsKey("userName") ? reqJson.getString("userName") : "");
        po.setWorkType(reqJson.containsKey("workType") ? reqJson.getString("workType") : "");
        po.setPunchType(punchType);
        po.setPunchTime(new Date());
        po.setPunchAddress(reqJson.containsKey("punchAddress") ? reqJson.getString("punchAddress") : "");
        po.setLongitude(reqJson.getBigDecimal("longitude"));
        po.setLatitude(reqJson.getBigDecimal("latitude"));
        po.setPhotoUrl(reqJson.containsKey("photoUrl") ? reqJson.getString("photoUrl") : "");

        attendanceRecordV1ServiceDao.saveAttendanceRecord(po);
        context.setResponseEntity(ResultVo.success());
    }
}
