<?php

namespace App\Distributor\Controllers;

use App\Admin\Repositories\BaseProductImage;
use App\Distributor\Repositories\SmmPost;
use App\Distributor\Repositories\SmmUserAccount;
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;

class SmmPostController extends AdminDistController
{
    use HasUploadedFile;

    /**
     * page index
     */
    public function index(Content $content)
    {
        return $content
            ->header('发报帖子')
            ->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(false)
                ->width('950px')
                ->add('选择本地媒体', function ($step) {
                    $step->radio('send_type',admin_trans_label('send_type'))
                        ->when([1], function ($step) {
                            $step->datetime('send_time', admin_trans_label('send_time'))->required();
                        })
                        ->options([ 0=>admin_trans_label('immediate'), 1=>admin_trans_label('timing')])->required()->default(0);
                            $step->text('message', admin_trans_label('post_title'))->required()->maxLength(20);
                            $step->radio('media_type',admin_trans_label('media_type'))
                        ->when([0], function ($step) {
                            $step->multipleImage('image_url', admin_trans_label('images'))
                                ->disk('local')
                                ->retainable()//禁止删OSS图
                                ->sortable() // 可拖动排序
                                ->removable() // 可移除图片
                                ->autoUpload() // 自动上传
                                ->uniqueName()
                                ->limit(config('admin.upload.oss_image.limit'))
                                ->accept(config('admin.upload.oss_image.accept'))
                                ->maxSize(config('admin.upload.oss_image.max_size'))
                                ->required()
                                ->saving(function ($reslut) {
                                    return json_encode($reslut);
                                });
                        })
                        ->when([1], function ($step)  {
                            $step->file('video_url')
                                ->disk('local') // 使用本地存储
                                ->uniqueName()
                                ->autoUpload()
                                ->required()
                                ->accept(config('admin.upload.oss_video.accept'))
                                ->maxSize(config('admin.upload.oss_video.max_size'))
                                ->chunkSize(1024)
                                ->required()
                                ->saving(function ($reslut) {
                                    return json_encode($reslut);
                                });
                        })
                        ->options([ 0=>admin_trans_label('images'), 1=>admin_trans_label('videos')])->required()->default(0);
                })
                ->add('选择传单社媒平台', function ($step) {
                    $rootAccounts = SmmUserAccount::getUserAccounts();
                    $listBoxOptions = [];
                    foreach ($rootAccounts as $account) {
                        $listBoxOptions[$account->id] = $account->name . ' ('.$account->getParent->name.')';
                    }
                    $step->listbox('account_ids', admin_trans_label('accountsSelect'))->required()->options($listBoxOptions);
                });
        });
    }

    /*
     * 保存数据
     */
    public function store() {
        $post = $_POST;
        if (isset($post['upload_column']) && $post['upload_column'] == 'image_url') {
            // 上传图片或视频
            return $this->upload();
        }
        if (isset($post['ALL_STEPS']) && $post['ALL_STEPS'] == '1') {
            $media_type = $post['media_type'];
            if ($media_type == 0) {
                $image_video_url = $post['image_url'];
            } else {
                $image_video_url = $post['video_url'];
            }
            if ($this->checkStoragePath($image_video_url) === false) {
                return '发送失败,请检查上传文件是否存在';
            }
            if ($post['send_type'] == 0) {
                $send_time = Carbon::now();
            } else {
                //转换时间格式
                $send_time = Carbon::createFromFormat('Y-m-d H:i:s', $post['send_time']);
            }
            //保存数据
            SmmPost::create($post,$send_time,$image_video_url);
            //最后一步
            $data = [
                'title'       => '操作成功',
                'description' => '系统已生成发送队列,详情请查看日志。',
            ];
            return view('distributor.form_custom.completion-page', $data);
        }
    }


    /**
     * 上传图片到本地
     */
    public function upload() {
        $disk = $this->disk('local');
        // 获取上传的文件
        $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'));
    }


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