<?php
namespace app\common\job;

use think\queue\Job;
use think\Db;
use app\common\model\bbfxshop\Sreturn;

class FanhuanJob
{
    public function fire(Job $job, $data)
    {
        error_reporting(0);
        if (!defined('UNIACID')) {
            define('UNIACID', 1);
        }
        // 监听命令（站点根目录运行,开发使用，关闭窗口就失效）：php think queue:listen或sudo /www/server/php/72/bin/php think queue:listen
        // 
        // 宝塔软件商城下载进程守护管理器（生产环境使用）：
        // 添加守护进程
        // 启动用户：www
        // 启动命令：www/server/php/72/bin/php /www/wwwroot/站点目录/think queue:work --queue=default --sleep=3 --daemon --memory=512
        // 进程目录：/www/wwwroot/站点目录，(以实际路径为准)
        // 启动进程：1
        // 启动优先级：999
        // 无法启动操作（可能是文件权限问题，按顺序在根目录执行）：
        // chown -R www:www runtime
        // chmod -R 755 runtime

        echo '====开始执行'.$data['task_id'].'====' . PHP_EOL;
        Db::startTrans();
        try {
            echo '任务开始' . PHP_EOL;

            $result = Sreturn::jiesuan();
            if($result['code'] == 1){
                $list = $result['data'];
                $caseBalanceSql = '';
                $caseScoreSql = '';
                $ids = [];
                $fh_ids = [];
                $money_log = [];
                $release_log = [];
                $uniacid = UNIACID;
                $fanhuan_user_field1 = "";
                $fanhuan_user_field2 = "";
                $time = time();
                $date = date("Y-m-d");
                foreach($list as $item){
                    $user_id = (int)$item['user_id'];
                    $money = floatval($item['return_money']);
                    //去重，防止同一个用户多次push到ids
                    if(!in_array($user_id,$ids)){
                        $ids[] = $user_id;
                    }
                    $fh_ids[] = $item['id'];

                    if($item['surplus'] - $money < 0){
                        $money = $item['surplus'];
                    }

                    $fanhuan_user_field2 .= " WHEN {$item['id']} THEN '{$date}' ";

                    if($money > 0){
                        $fanhuan_user_field1 .= " WHEN {$item['id']} THEN IF((surplus - {$money})>=0,surplus - {$money},surplus) ";
                        
                        if ($item['type'] == 1) {
                            $befores = $item['balance'];
                            $afters = $item['balance'] + $money;
                            $caseBalanceSql .= " WHEN {$user_id} THEN balance + {$money} ";
                        } else {
                            $befores = $item['score'];
                            $afters = $item['score'] + $money;
                            $caseScoreSql .= " WHEN {$user_id} THEN score + {$money} ";
                        }
                        $info = $item['return_info'];
                        $item_id = 0;
                        $extend = "";
                        if(!empty($info['id'])){
                            $item_id = $info['id'];
                            if(!empty($info['extend'])){
                                $extend = $info['extend'];
                            }
                            $info = iserializer($info);
                        }
                        else{
                            $info = "";
                        }

                        $money_log[] = "({$uniacid},{$user_id},{$money},{$befores},{$afters},'{$item['return_title']}',{$item['type']},{$item['return_type']},{$item_id},'{$info}','{$extend}',{$time})";
                        
                        $release_log[] = "({$uniacid},{$user_id},{$money},{$item['type']},0,{$item['return_type']},{$item['id']},1,{$time},{$time})";  
                        
                    }
                    
                }
                

                //动态拼接字段更新部分
                $updateArr = [];
                if(!empty($caseBalanceSql)){
                    $updateArr[] = "`balance` = CASE id {$caseBalanceSql} ELSE balance END";
                }
                if(!empty($caseScoreSql)){
                    $updateArr[] = "`score` = CASE id {$caseScoreSql} ELSE score END";
                }

                if(!empty($updateArr)){
                    $idStr = implode(',', $ids);
                    $updateSql = implode(',',$updateArr);
                    $sql = "UPDATE ".tablename("bbfx_user")." 
SET {$updateSql}
WHERE id IN ({$idStr})";
                    addFileLog("sreturn1",$sql);
                    Db::execute($sql);
                }

                if(!empty($money_log)){
                    $money_log_sql = implode(',',$money_log);
                    $sql = "INSERT INTO ".tablename("bbfx_money_log")." (`uniacid`, `user_id`, `money`, `befores`, `afters`, `remarks`, `type`, `item_type`, `item_id`, `info`, `extend`, `createtime`)
VALUES {$money_log_sql}";
                    addFileLog("sreturn2",$sql);
                    Db::execute($sql);
                }
                
                if(!empty($release_log)){
                    $release_log_sql = implode(',',$release_log);
                    $sql = "INSERT INTO ".tablename("bbfx_sreturn_release_log")." (`uniacid`,`user_id`,`money`,`type`,`itype`,`mtype`,`pid`,`status`,`dztime`,`createtime`)
VALUES {$release_log_sql}";
                    addFileLog("sreturn3",$sql);
                    Db::execute($sql);
                }

                $updateArr = [];
                if(!empty($fanhuan_user_field1)){
                    $updateArr[] = "`surplus` = CASE id {$fanhuan_user_field1} ELSE surplus END";
                }
                if(!empty($fanhuan_user_field2)){
                    $updateArr[] = "`sdate` = CASE id {$fanhuan_user_field2} ELSE sdate END";
                }
                if(!empty($updateArr)){
                    $idStr = implode(',', $fh_ids);
                    $updateSql = implode(',',$updateArr);
                    $sql = "UPDATE ".tablename("bbfx_sreturn_user")." 
SET {$updateSql}
WHERE id IN ({$idStr})";
                    addFileLog("sreturn4",$sql);
                    Db::execute($sql);
                }
            }

            Db::commit();
            $job->delete();
            echo '任务完成' . PHP_EOL;
        } catch (\Exception $e) {
            Db::rollback();
            //失败，重试，最多3次
            if ($job->attempts() < 3) {
                $job->release(2); //延迟2秒后重试
            } else {
                //超过重试次数，丢弃，可以写日志
                $job->delete();
            }
            echo '任务失败' .$e->getMessage(). PHP_EOL;
        }
    }

    public function failed($data)
    {
        echo '进入failed' . PHP_EOL;
    }
}
