<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\logic\task;


use app\common\model\task\Task;
use app\common\logic\BaseLogic;
use app\common\model\Company;
use app\common\model\informationg\UserInformationg;
use app\common\model\task_scheduling_plan\TaskSchedulingPlan;
use app\common\model\task_template\TaskTemplate;
use app\common\model\user\User;
use think\facade\Db;
use think\facade\Log;

/**
 * 任务逻辑
 * Class TaskLogic
 * @package app\adminapi\logic\task
 */
class TaskLogic extends BaseLogic
{


    /**
     * @notes 添加任务
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/08/05 13:39
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            Task::create([
                'title' => $params['title'],
                'template_id' => $params['template_id'],
                'company_id' => $params['company_id'],
                // 'admin_id' => $params['admin_id'],
                'start_time' => strtotime($params['start_time']),
                'end_time' => strtotime($params['end_time']),
                'director_uid' => $params['director_uid'],
                'type' => $params['type'],
                'status' => $params['status'],
                'content' => $params['content'],
                'extend' => json_encode($params['extend'])
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 定时添加任务
     */
    public static function CronAdd(array $v, $datas): bool
    {
        try {
            if ($v['types'] == 3) {
                $task = Task::where('template_id', $v['id'])->find();
                if ($task) {
                    // Task::where('template_id', $v['id'])->update(['start_time' => strtotime($task['start_time']) + 86400, 'end_time' => strtotime($task['end_time']) + 86400]);
                    // TaskTemplate::where('id', $v['id'])->inc('day_count')->update();
                    return true;
                }
            }
            $time = strtotime(date('Y-m-d'));
            $TaskSchedulingPlan_data = [
                'create_user_id' => 0,
                'company_id' => $v['company_id'],
                'template_id' => $v['id'],
                'scheduling_id' => $v['task_scheduling'],
                'start_time' => $time,
                'end_time' => $time + 86399,
                'sn' => User::createUserSn(),
                'status' => 1
            ];
            $TaskSchedulingPlan = TaskSchedulingPlan::create($TaskSchedulingPlan_data);
            $arr = [
                'template_id' => $v['id'],
                'scheduling_plan_id' => $TaskSchedulingPlan['id'],
                'company_id' => $v['company_id'],
                'title' => $v['title'],
                'money' => $v['money'],
                'type' => $v['type'],
                'content' => $v['content'],
                'start_time' => $time,
                'end_time' => $time + 86399,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $data = $arr;
            $data['money'] = self::task_money($v, $datas);
            $data['extend'] = json_encode($v['extend']);
            //信息更新
            if ($v['type'] == 31) {
                $finds = TaskTemplate::where('id', $v['id'])->field('information_count,information_day_count')->find();
                $update = 0;
                if ($finds['information_count'] > $finds['information_day_count']) {
                    $day_count = $finds['information_count'] - $finds['information_day_count'];
                    if ($day_count >= 5) {
                        $update = 5;
                    } else {
                        $update = $day_count;
                    }
                }
                $data["extend"] = json_encode(['informationg' => ['count' => 5, 'update' => $update]]);
                TaskTemplate::where('id', $v['id'])->inc('information_day_count', 5)->update();
            }
            if ($v['type'] == 32) {
                $data['director_uid'] = $datas['company_info']['user_id'];
            }
            //入股任务
            if ($v['type'] == 35) {
                $responsible_area = Company::where('id', $v['company_id'])->value('responsible_area');
                if ($responsible_area) {
                    $responsible_area = explode(',', $responsible_area);
                } else {
                    Log::error('定时任务添加失败:没有区域' . json_encode($v));
                    return false;
                }
                if (isset($v['extend']['shareholder'])) {
                    $shareholder_user = User::where('id', $v['extend']['shareholder']['user_id'])->field('id,nickname,brigade')->find();

                    $v['extend']['shareholder']['money'] = $v['recharge'];
                    $v['extend']['shareholder']['over_decimal'] = $v['over_decimal'];
                    foreach ($responsible_area as $kkk => $vvv) {
                        $v['extend']['shareholder']['user_list'][$kkk] = ['info' => $shareholder_user['nickname'] . '需缴纳' . $vvv . '队,股金:' . bcdiv($v['recharge'], count($responsible_area), 2), 'time' => $v['create_time']];
                    }
                    $data['director_uid'] = $v['extend']['shareholder']['user_id'];
                }
                $data['extend'] = json_encode($v['extend']);
                $money_one = bcmul($v['stage_day_one'], $v['money'], 2);
                $money_two = bcmul($v['stage_day_two'], $v['money_two'], 2);
                $data['money'] = bcadd($money_one, $money_two);
            }
            //片区交易
            if ($v['type'] == 33) {
                //基础金额*(每日基户数*天数)//且户数小于公司总户数
                $user_count = UserInformationg::where('company_id', $v['company_id'])->count();
                //
                if ($v['day_count'] == 0) {
                    $user_count_two = 5 * 1;
                } else {
                    $user_count_two = 5 * $v['day_count'];
                }
                if ($user_count_two > $user_count) {
                    $user_count_money = 58 * $user_count;
                } else {
                    $user_count_money = 58 * $user_count_two;
                }
                $extend = [
                    'transaction' => ['arr' => ['day_money' => $user_count_money, 'total_price' => 0]]
                ];
                $data['extend'] = json_encode($extend);
            }
            $task_id = (new Task())->insertGetId($data);
            TaskSchedulingPlan::where('id', $TaskSchedulingPlan['id'])->update(['task_id' => $task_id, 'is_execute' => 1]);
            TaskTemplate::where('id', $v['id'])->inc('day_count')->update();
            return true;
        } catch (\Exception $e) {
            Log::error('定时任务添加失败'.$e->getMessage().'。line:'.$e->getLine());
            return false;
        }
    }
    //任务金额
    private static function task_money($v, $datas)
    {
        if ($v['types'] == 1 || $v['types'] == 3) {
            if ($v['day_count'] <= $v['stage_day_one']) {
                return $v['money'];
            } else {
                return  $v['money_two'];
            }
        } elseif ($v['types'] == 2) {
            if ($v['day_count'] <= $v['stage_day_one']) {
                return $v['money'];
            } elseif ($v['day_count'] <= $v['stage_day_two']) {
                return  $v['money_two'];
            } else {
                return  $v['money_three'];
            }
        } else {
            if ($v['day_count'] <= $v['stage_day_one']) {
                $a = $v['money'];
            } else {
                $a =  $v['money_two'];
            }
            if ($v['day_count'] >= $v['stage_day_two']) {
                TaskTemplate::where('id', $v['id'])->update(['status' => 0]);
            }
            return $a;
        }
    }

    /**
     * @notes 更新任务状态
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/08/05 13:39
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            Task::where('id', $params['id'])->update(['status' => 3, 'update_time' => time()]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除任务
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2023/08/05 13:39
     */
    public static function delete(array $params): bool
    {
        return Task::destroy($params['id']);
    }


    /**
     * @notes 获取任务详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2023/08/05 13:39
     */
    public static function detail($params): array
    {
        $task = Task::findOrEmpty($params['id'])->toArray();
        if ($task) {
            if (isset($task['extend']['informationg'])) {
                $task['extend']['informationg'] = UserInformationg::where('id', $task['extend']['informationg'])->field('name,phone,sex,age,update_time')
                    ->find()->toArray();
            }
        }
        return $task;
    }
}