<?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('本地素材发布');
            $form->action('ssm-post');
            $form->disableListButton();
            $form->multipleSteps()
                ->remember()
                ->width('950px')
                ->add('选择本地媒体', function ($step) {
                    $step->radio('send_type',admin_trans_label('send_type'))
                        ->when([1], function ($step) {
                            $step->datetime('send_time', '<span style="color:#bd4147;">*</span> '.admin_trans_label('send_time'))->placeholder(' ');
                        })
                        ->options([ 0=>admin_trans_label('immediate'), 1=>admin_trans_label('timing')])->default(0);
                    $step->radio('post_type',admin_trans_label('media_type'))
                        ->when([0], function ($step) {
                            $step->textarea('image_message', '<span style="color:#bd4147;">*</span> '.admin_trans_label('post_message'))->rows(3)->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,不大于3M')
                                ->maxSize(3072);
                        })
                        ->when([1], function ($step)  {
                            $step->textarea('video_message', '<span style="color:#bd4147;">*</span> '.admin_trans_label('post_message'))->rows(3)->placeholder(' ');
                            $step->file('video_url','<span style="color:#bd4147;">*</span> '.admin_trans_label('video'))
                                ->uniqueName()
                                ->autoUpload()
                                ->accept(config('admin.upload.oss_video.accept'))
                                ->maxSize(120400)
                                ->chunked()
                                ->removable();
                                //->chunked()
                        })
                        ->options([ 0=>admin_trans_label('images'), 1=>admin_trans_label('videos')])->default(0);
                    $this->stepLeaving($step,0);
                })
                ->add('选择传单社媒平台', function ($step) {
                    $rootAccounts = SmmUserAccount::getUserAccounts();
                    $listBoxOptions = [];
                    foreach ($rootAccounts as $account) {
                        if (SmmPostLog::getPostQuota($account->getParent->name) > 0) {
                            //限额大于0才显示
                            $listBoxOptions[$account->id] = $account->name . ' ('.$account->getParent->name.')';
                        }
                    }
                    $step->listbox('account_ids', '<span style="color:#bd4147;">*</span> '.admin_trans_label('accountsSelect'))
                        ->options($listBoxOptions);
                    $step->select('youtube_category')->setView('distributor.form_custom.select_hide')->options(SmmUserAccount::getYoutubeCategory())->default(22)->required();
                    $this->stepLeaving($step,1);
                });
            $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['ALL_STEPS']) && $post['ALL_STEPS'] == '1') {
            if ($post['account_ids'] == [] || count($post['account_ids']) == 0 || $post['account_ids'] == '' || empty($post['account_ids'][0])) {
                return Admin::json()->error('请选择社媒帐号');
            }
            $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 ($this->checkStoragePath($image_video_url) === false) {
                return Admin::json()->error('请检查上传文件是否存在');
            }
            if ($post['send_type'] == 0) {
                $send_time = Carbon::now();
            } else {
                // 從北京時間字符串創建 Carbon 對象
                $sendTime = Carbon::createFromFormat('Y-m-d H:i:s', $post['send_time'], 'Asia/Shanghai');
                // 轉換為 UTC 時間
                $send_time = $sendTime->setTimezone('UTC');
               // $send_time = Carbon::createFromFormat('Y-m-d H:i:s', $post['send_time'])->setTimezone('UTC');
            }
            //保存数据
            SmmPost::create($post,$send_time,$image_video_url);
            // 生成发送记录
            $timer = new TimerSsmPost();
            $timer->createLog();
            //最后一步
            $data = [
                'title'       => '操作成功',
                'description' => '系统已生成发送队列,详情请查看日志。 ',
            ];
            return view('distributor.form_custom.completion-page', $data);
        }
    }


    /**
     * 上传图片到本地
     */
    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);

            //oss 保存
//            $disk = $this->disk('oss');
//            $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;
    }

    private function stepLeaving($step,$index=0)
    {
        $lang = config('app.locale');//当前语言
        //JS 验证参数不能为空
        if ($index == 0) {
$step->leaving(<<<JS

// 全局缓存对象,存储被移除的YouTube选项 {selectName: jQueryObject}
function toggleYouTube(flag) {
    var \$this = \$(this);

    // 定义选择器
    var youtubeSelector = 'option:contains("(YouTube)")';
    var \$helper1 = \$('select[name="account_ids[]_helper1"]');
    var \$helper2 = \$('select[name="account_ids[]_helper2"]');
    var \$mainSelect = \$('select[name="account_ids[]"]');

    // 初始化数据存储
    if (!\$this.data('youtubeOptions')) {
        \$this.data('youtubeOptions', {
            helper1: \$helper1.find(youtubeSelector).clone(true),
            helper2: \$helper2.find(youtubeSelector).clone(true),
            main: \$mainSelect.find(youtubeSelector).clone(true),
            positions: {  // 记录原始位置
                helper1: \$helper1.find(youtubeSelector).index(),
                helper2: \$helper2.find(youtubeSelector).index(),
                main: \$mainSelect.find(youtubeSelector).index()
            }
        });
    }

    // 通用移除函数
    function removeYouTubeOptions(\$container) {
        \$container.find(youtubeSelector).each(function() {
            \$(this).detach(); // 使用 detach 保留事件和数据的引用
        });
    }

    // 移除所有 YouTube 选项
    removeYouTubeOptions(\$helper1);
    removeYouTubeOptions(\$helper2);
    removeYouTubeOptions(\$mainSelect);

    // 还原逻辑
    if (flag === false) {
        var saved = \$this.data('youtubeOptions');

        // 精确还原到原始位置
        saved.helper1.insertAfter(
            \$helper1.find('option').eq(saved.positions.helper1 - 1)
        );

        saved.helper2.insertAfter(
            \$helper2.find('option').eq(saved.positions.helper2 - 1)
        );

        saved.main.insertAfter(
            \$mainSelect.find('option').eq(saved.positions.main - 1)
        );
    }
    //把选择账号全部向左移
    $(".removeall ").click();
    //隐藏youtube 分类
    $('#select_hide_youtube_category').toggle(false);
}

function validateForm(formArray) {
    lang = '{$lang}';
    // 仅获取radio类型的post_type值
    let postType = formArray.find(item =>
        item.name === 'post_type' && item.type === 'radio'
    )?.value;

    // 仅获取radio类型的send_type值
    let sendType = formArray.find(item =>
        item.name === 'send_type' && item.type === 'radio'
    )?.value;

    // 验证post_type相关规则
    if (postType === '0') {
        const imageMessage = formArray.find(item => item.name === 'image_message')?.value;
        const imageUrl = formArray.find(item => item.name === 'image_url')?.value;
        if (!imageMessage || !imageUrl) {
            if (lang === 'en') {
                return 'Post message and images cannot be empty';
            } else {
                return '帖子留言和图片不能为空';
            }
        }
        //隐藏youtube的帐号
        toggleYouTube(true);
    } else if (postType === '1') {
        const videoMessage = formArray.find(item => item.name === 'video_message')?.value;
        const videoUrl = formArray.find(item => item.name === 'video_url')?.value;
        if (!videoMessage || !videoUrl) {
            if (lang === 'en') {
                return 'Post message and video cannot be empty';
            } else {
                return '帖子留言和视频不能为空';
            }
        }
        toggleYouTube(false);
    }

    // 验证send_type规则(仅处理radio类型的send_type)
    if (sendType === '1') {
        const sendTime = formArray.find(item => item.name === 'send_time')?.value;
        if (!sendTime) {
            if (lang === 'en') {
                return 'Send time cannot be empty';
            } else {
                return '定时发送时间不能为空';
            }
        }
    }
    return "";
}

var formArray = args.formArray;
rs = validateForm(formArray);
if (rs != "") {
    Dcat.error(rs);
    return false;
}
JS);
        } else {
$step->leaving(<<<JS
var formArray = args.formArray;
var lang = '{$lang}';
//找account_ids
let accountIds = formArray.find(item => item.name === 'account_ids[]')?.value;
if (!accountIds || accountIds.length === 0) {
    if (lang === 'en') {
        Dcat.error('Please select accounts');
    } else {
        Dcat.error('请选择社媒帐号');
    }
    return false;
}

JS);
        }

    }

    public function addJs()
    {
        Admin::script(
<<<JS
function checkYouTubeOption(select) {
    // 检查是否存在包含"YouTube"的option
    var hasYouTube = select.find('option:contains("YouTube")').length > 0;
    // 切换目标元素的显示状态
    $('#select_hide_youtube_category').toggle(hasYouTube);
}
var select = $('select[name="account_ids\\[\\]_helper2"]');
var select_lenght = select.children().length;
let intervalId = setInterval(() => {
    var select = $('select[name="account_ids\\[\\]_helper2"]');
    // 处理变化的逻辑
    if (select_lenght != select.children().length) {
        checkYouTubeOption(select);
    }
}, 300);

JS
        );

    }
}