<?php

namespace plugin\admin\app\controller;

use Exception;
use support\Request;
use support\Response;
use support\think\Db;

/**
 * 内容管理
 *
 * @icon fa fa-circle-o
 */
class ArchivesController extends Crud
{

    /**
     * Archives模型对象
     * @var \app\model\Archives
     */
    protected $model = null;
    protected $type = 'default'; 
    protected $tpl = 'archives'; 
    protected $relationSearch = ['category'];
    protected $noNeedAuth = ['check_element_available', 'suggestion','tags', 'flag'];

    function __construct()
    {
        $this->model = new \app\model\Archives;

        $flagList = $this->model->getFlagList();
        $this->assignconfig("flagList", $flagList);
        $this->assign("flagList", $flagList);

        $statusList = $this->model->getStatusList();
        $this->assign("statusList", $statusList);
        $this->assignconfig("statusList", $statusList);

        $categoryList = $this->model->getCategoryOptions($this->type);
        $this->assign("categoryList", $categoryList);
        $this->assignconfig("categoryList", $categoryList);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index(Request $request):Response
    {
        return view($this->tpl.'/index');
    }
    public function insert(Request $request): Response
    {
        if ($request->method() != 'POST') {
            return view($this->tpl.'/update',[
                'row'   => [
                    'type'      =>  $this->type,
                    'flag'      =>  '',
                    'status'    =>   1
                ],
            ]);
        }
        $params = $request->post();
        if (empty($params)) {
            return $this->fail(__('Parameter %name% can not be empty', []));
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->save($params);
            Db::commit();
        } catch (Exception $e) {
           Db::rollback();
           return $this->fail($e->getMessage());
        }
        if ($result === false) {
            return $this->fail(__('No rows were inserted'));
        }
        return $this->success();
    }
    /**
     * 编辑
     *
     * @param mixed $ids
     * @return string
     */
    public function update(Request $request): Response
    {
        if ($request->method() == 'POST') {
            $params = $request->post();
            if (empty($params)) {
                return $this->fail(__('Parameter %name% can not be empty', []));
            }
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $this->model->validateFailException()->validate($validate);
                }
                $result = $this->model->exists(true)->save($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return $this->fail($e->getMessage());
            }
            if ($result === false) {
                return $this->fail(__('No rows were inserted'));
            }
            return $this->success();
            //return parent::update($request);
        }
        $ids = $request->get('ids');
        $row = $this->model->whereIn('id',$ids)->find();
        if (!$row) {
            return $this->fail(__('No Results were found'));
        }
        $addon = Db::name('content')->where('id', $row['id'])->find();
        if ($addon) {
            $row->setAddonData($addon);
        }

        return view($this->tpl.'/update',[
            'row'   =>  $row
        ]);
    }

    /**
     * 销毁
     * @param string $ids
     */
    public function delete(Request $request):Response
    {
        $ids = $request->get('ids');
        \app\model\Archives::event('after_delete', function ($row) {
            //删除副表
            Db::name('content')->where("id", $row['id'])->delete();
        });
        return parent::delete($request);
    }
    /**
     * 加入标签
     * @param string $ids
     */
    public function tags(Request $request):Response
    {
        $ids = $request->get('ids');
        if ($request->method() != 'POST') {
            return $this->fail(__("Invalid parameters"));
        }
        if ($ids) {
            $tags = $request->post('tags');
            $newTagsArr = array_filter(explode(',', $tags));
            if ($newTagsArr) {
                $pk = $this->model->getPk();
                $archivesList = $this->model->where($pk, 'in', $ids)->select();
                /**
                 * @var \app\model\Archives $item
                 */ 
                foreach ($archivesList as $index => $item) {
                    $tagsArr = explode(',', $item->tags);
                    $tagsArr = array_merge($tagsArr, $newTagsArr);
                    $item->save(['tags' => implode(',', array_unique(array_filter($tagsArr)))]);
                }
                return $this->success();
            } else {
                return $this->fail(__('标签数据不能为空'));
            }
        }
        return $this->fail(__('Please select at least one row'));
    }

    /**
     * 修改标志
     * @param string $ids
     */
    public function flag(Request $request):Response
    {
        if ($request->method() != 'POST') {
            return $this->fail(__("Invalid parameters"));
        }
        $ids = $request->get('ids');
        if ($ids) {
            $type = $request->post('type');
            $flag = $request->post('flag');
            $changeFlagArr = array_filter(explode(',', $flag));
            if ($changeFlagArr) {
                $pk = $this->model->getPk();
                $archivesList = $this->model->where($pk, 'in', $ids)->select();
                /**
                 * @var \app\model\Archives $item
                 */ 
                foreach ($archivesList as $index => $item) {
                    $flagArr = explode(',', $item->flag);
                    if ($type == 'add') {
                        $flagArr = array_merge($flagArr, $changeFlagArr);
                    } else {
                        $flagArr = array_diff($flagArr, $changeFlagArr);
                    }
                    $item->save(['flag' => implode(',', array_unique(array_filter($flagArr)))]);
                }
                return$this->success();
            } else {
                return$this->fail(__('标志数据不能为空'));
            }
        }
        return$this->fail(__('Please select at least one row'));
    }



    /**
     * 检测元素是否可用
     * @internal
     */
    public function check_element_available(Request $request):Response
    {
        $id = $request->get('id');
        $name = $request->get('name');
        $value = $request->get('value');
        $name = substr($name, 4, -1);
        if (!$name) {
            return $this->fail(__('Parameter %name% can not be empty', ['name'=>'name']));
        }
        $model = $this->model;
        if ($id) {
            $model = $model->where('id', '<>', $id);
        }
        $exist = $model->where($name, $value)->find();
        if ($exist) {
            return $this->fail(__('The data already exist'));
        } else {
            return $this->success();
        }
    }

    /**
     * 搜索建议
     * @internal
     */
    public function suggestion(Request $request)    :Response
    {
        $q = trim($request->get("q"));
        $id = trim($request->get("id/d"));
        $list = [];
        $result = $this->model->where("title", "like", "%{$q}%")->where('id', '<>', $id)->limit(10)->order("id", "desc")->select();
        /**
         * @var \app\model\Archives $item
         */ 
        foreach ($result as $index => $item) {
            $item['image'] = $item['image'] ? $item['image'] : '/assets/img/noimage.png';
            $list[] = ['id' => $item['id'],  'image' => cdnurl($item['image']), 'title' => $item['title'], 'create_date' => date('Y-m-d H:i:s',$item->created_at), 'status' => $item['status'], 'status_text' => $item['status_text'], 'deletetime' => $item['deletetime']];
        }
        return json($list);
    }
}
