<?php

namespace app\common\model;

use think\Model;

/**
 * 模型
 */
class TaskLog extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 增加任务完成进度
     */
    public static function tofinish($user_id,$task_id,$number = 1) {
        if(!$user_id || !$task_id || !$number) {
            return false;
        }
        // 查询任务明细
        $taskModel = new \app\common\model\Task();
        $tasklogModel = new \app\common\model\TaskLog();

        $where = [];
        $where["id"] = $task_id;
        $taskInfo = $taskModel->where($where)->find();
        if(!$taskInfo) {
            return false;
        }
        if($taskInfo['is_show'] != 1){
            return true;
        }
        // 添加/修改任务日志
        $where = [];
        $where["user_id"] = $user_id;
        $where["task_id"] = $taskInfo["id"];

        if($taskInfo["type_id"] == 2){
            $where["finish_date"] = date("Ymd");
        };

        $tasklogInfo = $tasklogModel->where($where)->lock(true)->find();
        if($tasklogInfo) {
            if($tasklogInfo["finish_number"] >= $taskInfo["number"] || $tasklogInfo["is_finish"] == 1) {
                return true;
            }
            $finish_number = $tasklogInfo["finish_number"]+$number;
            $where = [];
            $where["id"] = $tasklogInfo["id"];
            $data = [];
            $data["finish_number"] = $finish_number;
            $data["pace"] = round($finish_number/$taskInfo["number"],2)*100;
            $data["finish_date"] = date("Ymd");
            if($finish_number >= $taskInfo["number"]) {
                $data["is_finish"] = 1;
                $data["finish_time"] = time();
            }
            $res = $tasklogModel->update($data,$where);
        } else {
            $data = [];
            $data["user_id"] = $user_id;
            $data["task_id"] = $taskInfo["id"];
            $data["finish_number"] = $number;
            $data["pace"] = round($number/$taskInfo["number"],2)*100;
            $data["finish_date"] = date("Ymd");
            if($number >= $taskInfo["number"]) {
                $data["is_finish"] = 1;
                $data["finish_time"] = time();
            }
            $data["createtime"] = time();
            $res = $tasklogModel->insertGetId($data);
        }
        return $res;
    }
}
