<?php

namespace App\Distributor\Controllers;

use App\Admin\Repositories\BaseProductImage;
use App\Distributor\Repositories\SmmPost;
use App\Distributor\Repositories\SmmPostLog;
use App\Distributor\Repositories\SmmUserAccount;
use App\Services\SmmService;
use Carbon\Carbon;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Grid\Model;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;
use Dcat\Admin\FormStep\Form as StepForm;
use Dcat\Admin\Traits\HasUploadedFile;
use Dcat\Admin\Widgets\Alert;
use App\Console\Commands\TimerSsmPost;
use phpseclib3\Crypt\EC\BaseCurves\Montgomery;

class SmmPostController extends AdminDistController
{
    use HasUploadedFile;

    /**
     * page index
     */
    public function index(Content $content)
    {
        return $content
            ->header(admin_trans_label('send_post'))
            ->body($this->form());
    }

    protected function form()
    {
        return Form::make(new SmmPost(), function (Form $form) {
            $form->title(admin_trans_label('local_materials'));
            $form->action('ssm-post');
            $form->disableListButton();

            $form->radio('post_type',admin_trans_label('post_type'))
                ->when([0], function ($step) {
                    $step->textarea('image_message', '<span style="color:#bd4147;">*</span> '.admin_trans_label('post_message'))
                        ->rows(3)
                        ->help(admin_trans_label('post_message_help'))
                        ->placeholder(' ');
                    $step->multipleImage('image_url', '<span style="color:#bd4147;">*</span> '.admin_trans_label('images'))
                        ->retainable()//禁止删OSS图
                        ->sortable() // 可拖动排序
                        ->removable() // 可移除图片
                        ->autoUpload() // 自动上传
                        ->uniqueName()
                        ->limit(4)
                        ->accept('jpg,png')
                        ->help('jpg,png (Max 3M)')
                        ->maxSize(3072);
                })
                ->when([1], function ($step)  {
                    $step->select('youtube_category','<span style="color:#bd4147;">*</span> '.admin_trans_label('youtube_category'))->setView('distributor.form_custom.select_hide')->options(SmmUserAccount::getYoutubeCategory())->default(22)->placeholder(' ');
                    $step->text('yutube_title','<span style="color:#bd4147;">*</span> '.admin_trans_label('yutube_title'))->setView('distributor.form_custom.text_hide')->placeholder(' ');
                    $step->textarea('video_message', '<span style="color:#bd4147;">*</span> '.admin_trans_label('post_message'))
                        ->rows(3)
                        ->help(admin_trans_label('post_message_help'))
                        ->placeholder(' ');
                    $step->file('video_url','<span style="color:#bd4147;">*</span> '.admin_trans_label('video'))
                        ->uniqueName()
                        ->autoUpload()
                        ->accept(config('admin.upload.oss_video.accept'))
                        ->maxSize(20480)
                        ->chunked()
                        ->help('mp4 (Max 20M)')
                        ->removable();
                    //->chunked()
                })
                ->options([ 0=>admin_trans_label('graphic'), 1=>admin_trans_label('videos')])->default(0)->required();

            //用户当前时间
            $now = utcToLocalTime();
            $form->datetime('send_time', admin_trans_label('send_time'))->placeholder(' ')->default($now)->required();

            $rootAccounts = SmmUserAccount::getUserAccounts();
            $listBoxOptions = [];
            foreach ($rootAccounts as $account) {
                    //限额大于0才显示
                    $listBoxOptions[$account->id] = $account->name . ' ('.$account->getParent->name.')';
            }

            $form->checkbox('account_ids', admin_trans_label('accountsSelect'))->options($listBoxOptions)->required();

            $form->disableViewButton();
            $form->disableViewCheck();
            $form->disableDeleteButton();
            $form->disableEditingCheck();
            $form->disableCreatingCheck();
            $this->addJs();

        });
    }

    /*
     * 保存数据
     */
    public function store() {
        $post = $_POST;
        if (isset($post['_file_del_'])) {
            // 删除上传的文件
            header('Content-Type: application/json');
            echo json_encode(['status' => true, 'data' => []]);
            exit;
        }
        if (isset($post['upload_column']) && ($post['upload_column'] == 'image_url' || $post['upload_column'] == 'video_url')) {
            // 上传图片或视频
            return $this->upload();
        }
        //保存数据
        if (isset($post['post_type'])) {
            if ($post['account_ids'] == [] || count($post['account_ids']) == 0 || $post['account_ids'] == '' || empty($post['account_ids'][0])) {
                return Admin::json()->error(admin_trans_label('choose_account'));
            }
            if (SmmUserAccount::findYoutubeAccount($post['account_ids'],getDistributorId())->count() > 0) {
                if (empty($post['yutube_title']) || empty($post['youtube_category'])) {
                    return Admin::json()->error(admin_trans_label('input_yutube_fields'));
                }
                $charCount = mb_strlen($post['yutube_title'], 'UTF-8');
                if ($charCount > 90) {
                    return Admin::json()->error(admin_trans_label('yutube_title_limit'));
                }
            }

            $post_type = $post['post_type'];
            if ($post_type == 0) {
                $image_video_url = $post['image_url'];
                $post['message'] = $post['image_message'];
            } else {
                $image_video_url = $post['video_url'];
                $post['message'] = $post['video_message'];
            }
            if (empty($post['message'])) {
                return Admin::json()->error(admin_trans_label('fill_post_message'));
            }
            $messageCount = mb_strlen($post['message'], 'UTF-8');
            if ($messageCount > 500) {
                return Admin::json()->error(admin_trans_label('post_message_limit'));
            }
            if ($this->checkStoragePath($image_video_url) === false) {
                return Admin::json()->error(admin_trans_label('check_upload'));
            }
            if ($post['send_time'] == '' || $post['send_time'] == null) {
                return Admin::json()->error(admin_trans_label('select_send_time'));
            }

            //判断是否超过发送限制
            $checkResult = SmmUserAccount::checkAccountCanSendPost($post['account_ids'],getDistributorId());
            if ($checkResult['status'] == false) {
                return Admin::json()->error($checkResult['mediaName'].' '.admin_trans_label('account_send_limit'));
            }

            // 從北京時間字符串創建 Carbon 對象
//            $sendTime = Carbon::createFromFormat('Y-m-d H:i:s', $post['send_time'], 'Asia/Shanghai');
//
//            // 轉換為 UTC 時間
//            $send_time = $sendTime->setTimezone('UTC');
            $sendTime = localTimeToUtc($post['send_time']);

            //保存数据
            SmmPost::create($post,$sendTime,$image_video_url,getDistributorId());
            // 生成发送记录
            $timer = new TimerSsmPost();
            $timer->createLog();

            return Admin::json()->success(admin_trans_label('operation_successful'))->refresh();
        }
    }


    /**
     * 上传图片到本地
     */
    public function upload() {
        try {
            //保存到本地
            $disk = $this->disk('local');
            // 判断是否是删除文件请求
            if ($this->isDeleteRequest()) {
                // 删除文件并响应
                return $this->deleteFileAndResponse($disk);
            }

            // 获取上传的文件
            $file = $this->file();
            $dir = 'ssm/'.getDistributorId();
            $newName = md5(uniqid() . mt_rand()) .'.'.$file->getClientOriginalExtension();

            //保存在本地
            $result = $disk->putFileAs($dir, $file, $newName);


            return $result
                ? $this->responseUploaded($result, $disk->url($result))
                : $this->responseErrorMessage(admin_trans_label('upload_failed'));
        } catch (\Exception $e) {
            return $this->responseErrorMessage($e->getMessage());
        }
    }

    /*
     * 判断路径是否正确
     */
    public function checkStoragePath ($filePath) {
        $storagePath = 'ssm/'.getDistributorId();
        if (strpos($filePath, $storagePath) === 0) {
            return true;
        }
        return false;
    }


    public function addJs()
    {
        Admin::script(
<<<JS
     var hideYouTubeAccount = function(postType) {
        // 查找所有 account_ids 的 checkbox
        $('input[name="account_ids[]"]').each(function() {
            var label = $(this).closest('.vs-checkbox-con').find('span').last().text();
            // 检查是否包含 YouTube
            if (label.includes('YouTube')) {
                // 如果 post_type 值为 1（视频），显示 YouTube 选项；否则隐藏
                if (postType === '1') {
                    $(this).closest('.vs-checkbox-con').show();
                    //
                    const youtubeElements = ['#select_hide_youtube_category', '#text_hide_yutube_title'];
                    youtubeElements.forEach(id => $(id).toggle(false));
                } else {
                    $(this).closest('.vs-checkbox-con').hide();
                    // 可选择取消选中状态
                    $(this).prop('checked', false);
                }
            }
        });
     }
     var changeCount = 0

    $('input[name="post_type"]').on('change', function() {
        changeCount++;
        console.log(changeCount);
        if (changeCount > 2) {
            // 获取当前选中的 post_type 值
            var postType = $(this).val();
            hideYouTubeAccount(postType);
        } else {
            hideYouTubeAccount(0);
        }
    });



    // 定义需要控制的表单元素ID
    const youtubeElements = ['#select_hide_youtube_category', '#text_hide_yutube_title'];

    // 检查是否包含YouTube账号的函数
    function checkYouTubeSelection() {
        let hasYouTube = false;
        // 遍历所有选中的复选框
        $('input[name="account_ids[]"]:checked').each(function() {
            // 获取父容器内的账号名称文本
            const labelText = $(this).closest('.vs-checkbox-con').find('span:last').text().trim();
            if (labelText.includes('YouTube')) {
                hasYouTube = true;
                return false; // 发现后提前终止循环
            }
        });

        // 统一控制元素的显隐
        youtubeElements.forEach(id => $(id).toggle(hasYouTube));
    }

    // 绑定所有账号复选框的change事件
    $('input[name="account_ids[]"]').change(checkYouTubeSelection);

    // 初始化执行一次
    checkYouTubeSelection();

JS
        );

    }
}
