<?php

namespace app\controller\manager;

use app\validate\CasesValidate;
use app\model\{CasesModel, Category as MCategory, Log as MLog, System};
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

/**
 * 案例
 * Class Cases
 * @package app\controller\manager
 */
class Cases extends Base
{
    /**
     * @return Json|View
     */
    public function add()
    {
        if (request()->isPost()) {
            $images                 = input('img_images/a');
            $params                 = input('post.item/a', []);
            $params['image']        = input('img');
            $params['image_mobile'] = input('img_mobile');
            $params['images']       = json_encode($images, JSON_UNESCAPED_UNICODE);
            try {
                validate(CasesValidate::class)->check($params);
                $newItem = CasesModel::create($params);
                MLog::write('cases', 'add', '新增案例,ID:'.$newItem->id);
            } catch (ValidateException $e) {
                return $this->json(1, $e->getError());
            }
            return $this->json();
        } else {
            $categoryId = input('category_id/d', 0);
            $category   = MCategory::getById($categoryId);

            $this->getImgSize($categoryId);

            $this->data['category'] = $category;
            return $this->view();
        }
    }

    /**
     * @return Json|View
     */
    public function edit()
    {
        $id   = input('param.id/d', 0);
        $item = CasesModel::getById($id);
        if (count($item) == 0) {
            return $this->json(1, '该案例不存在');
        }
        if (request()->isPost()) {
            $params                 = input('post.item/a', []);
            $params['image']        = input('img');
            $params['image_mobile'] = input('img_mobile');
            $params['images']       = json_encode(array_values(input('img_images/a', [])), JSON_UNESCAPED_UNICODE);
            try {
                validate(CasesValidate::class)->check($params);
                CasesModel::updateById($id, $params);
                MLog::write('honour', 'edit', '修改案例,ID:'.$id);
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
            return $this->json();
        } else {
            $category = MCategory::getById($item['category_id']);

            $this->getImgSize($item['category_id']);

            $this->data['item']     = $item;
            $this->data['category'] = $category;
            return $this->view();
        }
    }

    public function sort()
    {
        if (request()->isPost()) {
            $id   = input('post.id/d');
            $sort = input('post.sort');
            $num  = input('post.num/d', 1);
            if ($num <= 0) {
                $num = 1;
            }
            if (!in_array($sort, ['up', 'down'], true)) {
                return $this->json(2, '参数错误');
            }
            $item = CasesModel::getById($id);
            if (empty($item)) {
                return $this->json(3, '该案例不存在');
            }
            if ($sort == 'up') {
                $where = "category_id='{$item['category_id']}' and sort < {$item['sort']}";
                $order = "sort desc";
            } else {
                $where = "category_id='{$item['category_id']}' and sort > {$item['sort']}";
                $order = "sort asc";
            }
            $forSortItems = CasesModel::getListByWhereAndOrder($where, $order, $num);
            if (!empty($forSortItems)) {
                $updateData   = [];
                $forSortCount = count($forSortItems);
                for ($i = 0; $i < $forSortCount; $i++) {
                    if ($i == 0) {
                        $updateData[] = [
                            'id'   => $forSortItems[$i]['id'],
                            'sort' => $item['sort']
                        ];
                    } else {
                        $updateData[] = [
                            'id'   => $forSortItems[$i]['id'],
                            'sort' => $forSortItems[$i - 1]['sort']
                        ];
                    }
                }
                $updateData[] = [
                    'id'   => $item['id'],
                    'sort' => $forSortItems[$i - 1]['sort']
                ];
                if (!empty($updateData)) {
                    $model = new CasesModel();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    MLog::write('cases', 'sort', "案例排序,ID:{$id} ,{$sortStr}了{$num}位");
                    return $this->json();
                }
            }
            return $this->json(4, '无须调整排序!');
        }
        return $this->json(1, '无此操作');
    }

    // 删除
    public function del()
    {
        if (request()->isPost()) {
            $historyId = input('param.id/d', 0);
            $item      = CasesModel::getById($historyId);
            if (count($item) == 0) {
                return $this->json(2, '该案例不存在');
            }
            try {
                CasesModel::destroy($historyId);
                MLog::write('cases', 'del', '删除案例,ID:'.$historyId);
            } catch (\Exception $e) {
                return $this->json(3, '删除失败,'.$e->getMessage());
            }
            return $this->json();
        }
        return $this->json(1, '无此操作');
    }
}