<?php

namespace app\model;

use think\model\relation\HasOne;

/**
 * 薪资日志
 * 以天为周期记录每个工人、工地的基本工资及加班工资情况
 * 记录的创建,每一次打卡或加班申请就添加当天的记录(每天、每个工地、每个工人最多一条记录)
 *
 * !!!不要删除此表的任何数据!!!
 * !!!不要删除此表的任何数据!!!
 * !!!不要删除此表的任何数据!!!
 *
 * Class PayLog
 * @package app\model
 */
class PayLog extends Base
{
    public function account(): HasOne
    {
        return $this->hasOne(Account::class, 'id', 'account_id');
    }

    /**
     * 创建日工资初始记录
     *
     * 若当日记录已存在则不创建
     * 此时创建的记录 金额等数据都默认为0 需要等审核通过后在指定时间(如每日凌晨)统计相应金额并追加到此记录
     *
     * 使用场景举例:每日凌晨2点定时任务 => 对审核通过的申请计算基本工资及加班工资追加到此记录
     *
     * !!!千万不要因为金额记录为0就把记录删除 后续的统计操作都默认使用update进行追加。若记录不存在则会出现统计不准确的严重后果。!!!
     * @param  int  $accountId  工人ID
     * @param  int  $worksiteId  工地ID
     * @param  int  $time  工作日期(打卡、加班) 格式为Ymd 如:20220925
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function createWhenNotExists(int $accountId, int $worksiteId, int $time): bool
    {
        $indexs = $accountId.'-'.$worksiteId.'-'.$time;
        if (self::where('indexs', $indexs)->count() > 0) {
            return true;
        }

        $year  = date('Y', strtotime($time));
        $month = date('m', strtotime($time));
        $day   = date('d', strtotime($time));

        try {
            self::create([
                'account_id'  => $accountId,
                'worksite_id' => $worksiteId,
                'time'        => $time,
                'indexs'      => $indexs,
                'year'        => $year,
                'month'       => $month,
                'day'         => $day,
            ]);
        } catch (\Exception $exception) {
            //弱网时,可能会出现并发提交,忽略indexs唯一索引报错
            \think\facade\Log::error('创建pay_log失败:message:'.$exception->getMessage().' line:'.$exception->getLine());
        }

        return true;
    }
}