<?php

/**
 * link: https://www.wegouer.com/
 * copyright: Copyright (c) 2020 深圳网商天下科技有限公司
 * author: wstianxia
 */

namespace app\commands;

use app\forms\common\attachment\AttachmentRemove;
use app\forms\common\RedisTimeQueue;
use app\forms\mall\setting\ContentForm;
use app\helpers\ArrayHelper;
use app\models\Attachment;
use app\models\AvData;
use app\models\CoreActionLog;
use app\models\CoreExceptionLog;
use app\models\Mall;
use app\models\VisualImage;
use app\models\VisualVideo;
use yii\console\Controller;
use yii\helpers\FileHelper;
use yii\helpers\Json;

class IndexController extends Controller
{
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        ini_set('memory_limit',-1); //没有内存限制
        ini_set('max_execution_time', 0);
    }

    public function actionDelAttachment()
    {
        try{
            $obj = new RedisTimeQueue();
            $dataList = $obj->rangeByTime(Attachment::REDIS_KEY, 0, time());
            $id = [];
            foreach ($dataList as $item){
                $id[] = $item['id'];
            }
            /** @var Attachment[] $attachmentList */
            $attachmentList = Attachment::find()->where(['id' => $id])->with("mall")->all();
            $attachmentList = ArrayHelper::index($attachmentList, 'id');
            foreach ($dataList as $item){
                $attachment = $attachmentList[$item['id']] ?? '';
                if($attachment){
                    \Yii::$app->setMall($attachment->mall);
                    AttachmentRemove::getCommon($attachment)->handle();
                }
                $obj->remove(Attachment::REDIS_KEY, $item);
            }
            (new Attachment())->reset();
        }catch (\Exception $e){
            \Yii::error($this->action->id);
            \Yii::error($e);
        }
    }

    public function actionDelData()
    {
        try{
            $mallList = Mall::find()->all();
            foreach ($mallList as $mall) {
                \Yii::$app->setMall($mall);
                $config = (new ContentForm())->config();
                $dataList = Attachment::find()
                    ->where([
                        'and',
                        ['<', 'created_at', mysql_timestamp(time() - $config['attachment_storage_time'] * 3600)],
                        ['mall_id' => $mall->id],
                        ['>', 'user_id', 0],
                    ])->all();
                foreach ($dataList as $item){
                    AttachmentRemove::getCommon($item)->handle();
                }

                $dataList = VisualImage::find()
                    ->where([
                        'and',
                        ['<', 'updated_at', mysql_timestamp(time() - $config['image_storage_time'] * 3600)],
                        ['mall_id' => $mall->id],
                        ['>', 'user_id', 0],
                        ['is_admin_public' => 0, 'is_saved' => 0]
                    ])->all();
                foreach ($dataList as $item){
                    $data = Json::decode($item->data);
                    if(empty($data['is_saved'])) {
                        $item->deleteData();
                    }else{
                        $item->isLog = false;
                        $item->is_saved = 1;
                        $item->save();
                    }
                }

                $dataList = VisualVideo::find()
                    ->where([
                        'and',
                        ['<', 'updated_at', mysql_timestamp(time() - $config['video_storage_time'] * 3600)],
                        ['mall_id' => $mall->id],
                        ['>', 'user_id', 0],
                        ['is_admin_public' => 0]
                    ])->all();
                foreach ($dataList as $item){
                    $data = Json::decode($item->data);
                    if(empty($data['is_saved'])) {
                        $item->deleteData();
                    }
                }
                $this->delDir("/web/uploads/mall{$mall->id}");
            }
            (new Attachment())->reset();
            (new VisualImage())->reset();
            (new VisualVideo())->reset();

            $sql = sprintf(
                'select * from %s where `created_at` <= "%s" ORDER BY id desc limit 1',
                CoreActionLog::tableName(),
                mysql_timestamp(strtotime("-6 months"))
            );
            $log = \Yii::$app->db->createCommand($sql)->queryOne();
            if($log){
                $time = strtotime($log['created_at']);
                $end = date("Y-m-d 23:59:59", $time);
                CoreActionLog::deleteAll(['<=', "created_at", $end]);
                CoreExceptionLog::deleteAll(['<=', "created_at", $end]);

                foreach (['/console_log', "/logs"] as $dir){
                    $res = FileHelper::findDirectories(\Yii::$app->runtimePath . $dir, ['recursive' => false]);
                    sort($res);
                    foreach ($res as $item) {
                        if(basename($item) == date("Ym", $time)){
                            FileHelper::removeDirectory($item . "/" . date("d", $time));
                        }elseif(basename($item) < date("Ym", $time)){
                            FileHelper::removeDirectory($item);
                        }else{
                            break;
                        }
                    }
                }
            }

            $modelList = AvData::find()->where([
                'and',
                ['<=', "updated_at", date("Y-m-d 00:00:00",  strtotime("-3 day"))],
            ])->all();
            foreach ($modelList as $model){
                $model->deleteData();
            }
            (new AvData())->reset();
            // 把空目录删除了
            foreach ([AvData::FILE_DIR, VisualVideo::FILE_DIR] as $item){
                $this->delDir($item);
            }
        }catch (\Exception $e){
            \Yii::error($this->action->id);
            \Yii::error($e);
        }
    }

    public function delDir($item)
    {
        $fileRes = file_uri($item);
        $dirList = FileHelper::findDirectories($fileRes['local_uri'], ['recursive' => false]);
        foreach ($dirList as $dir) {
            if (empty(FileHelper::findFiles($dir))) {
                FileHelper::removeDirectory($dir);
            }
        }
    }
}
