<?php
/**
 * Copyright: Shanghai NuLang Network Technology Co., Ltd.
 * Faith: Some things do not need others to understand.
 * Project: CoverCMS <Your world, your ambition>
 * License: http://www.svipplus.cn/license/
 * Author: The Rain° <rain@svipplus.cn>
 * File: CategoryController.php
 * Time: 11:18
 */

namespace app\dash\controller;


use app\common\controller\BaseController;
use app\common\toolKit\CacheKit;
use app\common\toolKit\CommonKit;
use app\common\toolKit\SiteKit;
use think\Db;

class CategoryController extends BaseController
{
    private $siteId;

    private $categories;

    private $categoryDb;

    public function _initialize()
    {
        $this->siteId = SiteKit::currentSiteId();
        $this->categories = $this->categories();
        $this->categoryDb = Db::name('category');
    }

    public function indexAction()
    {
        if (request()->isPost()) {
            $items = $this->categories();
            foreach ($items as &$item) {
                $item['order'] = '<input style="width:35px;" type="text" name="cv[category][' . $item['id'] . ']" value="' . $item['weight'] . '" />';
                $itemCType = intval($item['c_type']);
                if (($itemCType===0 || $itemCType===3) && !$item['has_children']){
                    $item['items'] = '';
                }
                $c = $item['c_type'];
                $item['c_type'] = CommonKit::getModelByCType($item['c_type'], true);
                if (intval($c)===0){
                    $newUrl = url('new', ['parent_id' => $item['id'], 'new_son' => true,'is_link'=>true]);
                    $editUrl = url('edit', ['category_id' => $item['id'],'is_link'=>true]);
                    $redirectUrl = $item['url'];
                }else{
                    $newUrl = url('new', ['parent_id' => $item['id'], 'new_son' => true]);
                    $editUrl = url('edit', ['category_id' => $item['id']]);
                    $redirectUrl = url('app/distribute/redirect',['site_id'=>$this->siteId,'category_id'=>$item['id']]);
                }
                $item['is_show'] = $item['is_show'] ? '是' : '<span style="color: red;">否</span>';
                $item['visit'] = '<a class="cv-btn red" target="_blank" href="'.$redirectUrl.'">访问</a>';
                $item['actions'] = '<a class="cv-btn primary" href="javascript:openDialog(' . '\'编辑栏目\',' . '\'' . $editUrl . '\',' . '\'520px\',' . '\'480px\'' . ')">编辑</a>&nbsp;&nbsp;' . '<a class="cv-btn primary" href="javascript:openDialog(' . '\'添加子栏目\',' . '\'' . $newUrl . '\',' . '\'520px\',' . '\'480px\'' . ')">添加子栏目</a>';
                if (!$item['has_children'] && intval($item['items']) < 1) {
                    $deleteUrl = url('delete', ['category_id' => $item['id'], 'parent_id' => $item['parent_id']]);
                    $item['actions'] .= '&nbsp;&nbsp;' .
                        '<a class="cv-btn red" href="javascript:deleteCategoryData(\'' . $deleteUrl . '\')">删除</a>';
                }
            }
            return json(['total' => 0, 'rows' => $items]);
        }
        return $this->fetch();
    }

    public function newAction()
    {
        if (request()->isPost()) {
            $dataFromPost = request()->post('cv/a', null);
            if (is_null($dataFromPost) || !is_array($dataFromPost)) {
                return json(['success' => false, 'message' => lang('Failure0')]);
            }
            if (!isset($dataFromPost['parent_id'])) {
                return json(['success' => false, 'message' => lang('Failure1')]);
            }
            $dataFromPost['site_id'] = $this->siteId;
            if (intval($dataFromPost['parent_id']) !== 0) {
                if (CommonKit::isMissing(['title'], $dataFromPost, true)) {
                    return json(['success' => false, 'message' => lang('Failure2')]);
                }
                if (!$parentObject = $this->currentData(intval($dataFromPost['parent_id']))) {
                    return json(['success' => false, 'message' => lang('Failure3')]);
                }
                $parentLayer = $parentObject['layer'];
                $dataFromPost['layer'] = intval($parentLayer) + 1;
                $dataFromPost['c_type'] = $parentObject['c_type'];
                $categoryLastInsertId = $this->categoryDb->insertGetId($dataFromPost);
                if (!$categoryLastInsertId) {
                    return json(['success' => false, 'message' => lang('Failure4')]);
                }
                $this->categoryDb->where('id', $categoryLastInsertId)->update(['weight' => $categoryLastInsertId]);
                $this->updateAllParents(intval($dataFromPost['parent_id']), $categoryLastInsertId);
                CacheKit::updateCategoryCache();
                return json(['success' => true, 'message' => lang('Success')]);
            }
            if (isset($dataFromPost['c_type']) && intval($dataFromPost['c_type'])===0){
            }else{
                if (CommonKit::isMissing(['c_type', 'title'], $dataFromPost, true)) {
                    return json(['success' => false, 'message' => lang('Failure5')]);
                }
            }
            $categoryLastInsertId = $this->categoryDb->insertGetId($dataFromPost);
            if (!$categoryLastInsertId) {
                return json(['success' => false, 'message' => lang('Failure6')]);
            }
            $this->categoryDb->where('id', $categoryLastInsertId)->update(['weight' => $categoryLastInsertId]);
            CacheKit::updateCategoryCache();
            return json(['success' => true, 'message' => lang('Success')]);
        }
        $is_son = false;
        if (input('?get.new_son')){
            $is_son = true;
        }
        $viewFile = '';
        if (input('?get.is_link')){
            $viewFile = 'link';
        }
        $parentId = intval(input('get.parent_id', 0));
        $this->assign([
            'categories' => $this->categories,
            'parent_id' => $parentId,
            'is_son'=>$is_son
        ]);
        return $this->fetch($viewFile);
    }

    public function editAction()
    {
        $categoryId = input('get.category_id', 0);
        if (intval($categoryId) === 0) {
            return json(['success' => false, 'message' => lang('Failure')]);
        }
        if (request()->isPost()) {
            $dataFromPost = request()->post('cv/a', null);
            if (is_null($dataFromPost) || !is_array($dataFromPost)) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            if (CommonKit::isMissing(['title'], $dataFromPost, true)) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            Db::name('category')->where('id', $categoryId)->update($dataFromPost);
            CacheKit::updateCategoryCache();
            return json(['success'=>true, 'message'=>lang('Success')]);
        }
        $category = Db::name('category')->where('id', $categoryId)->find();
        if (!$category) {
            return json(['success' => false, 'message' => lang('Failure')]);
        }
        $models = [
            ['mark' => 1, 'name' => '文章模型'],
            ['mark' => 2, 'name' => '产品模型'],
            ['mark' => 3, 'name' => '单页模型'],
            ['mark' => 4, 'name' => '案例模型'],
            ['mark' => 5, 'name' => '1'],
        ];
        $this->assign([
            'category' => $category,
            'models' => $models,
            'categories' => $this->categories
        ]);
        $viewFile = '';
        if (input('?get.is_link')){
            $viewFile = 'link-edit';
        }
        return $this->fetch($viewFile);
    }

    public function deleteAction()
    {
        if (request()->isPost()) {
            $id = intval(input('?get.category_id') ? input('get.category_id') : input('post.category_id', 0));
            $parentId = intval(input('?get.parent_id') ? input('get.parent_id') : input('post.parent_id', 0));
            if ($id === 0) {
                return json(['success' => false, 'message' => lang('Failure')]);
            }
            $currentCategory = Db::name('category')->where('id', $id)->find();
            if (!$currentCategory){
                return json(['success'=>false, 'message'=>'该栏目已被删除，轻刷新']);
            }
            if ($currentCategory['has_children']){
                return json(['success'=>false, 'message'=>'该栏目仍有子栏目，请刷新']);
            }
            $currentCategoryCType = $currentCategory['c_type'];
            if (intval($currentCategoryCType) === 3) {
                $single = Db::name('single')->where('category_id', $id)->find();
                if ($single) {
                    Db::name('single')->where('category_id', $id)->delete();
                }
            }else{
                if (intval($currentCategory['items'])>0){
                    return json(['success'=>false, 'message'=>'该栏目下仍有内容，请刷新']);
                }
                if ($parentId!==0){
                    $this->removeSpecifyCategory($parentId,$id);
                }
            }
            Db::name('category')->where('id', $id)->delete();
            CacheKit::updateCategoryCache();
            return json(['success' => true, 'message' => lang('Success')]);
        }
    }

    /**
     * @return mixed
     */
    private function categories()
    {
        return cache('categories.list.tree.site.' . $this->siteId);
    }

    /**
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    private function currentData($id)
    {
        return $this->categoryDb->where('id', $id)->find();
    }

    /**
     * @param $parentId
     * @param $id
     */
    private function updateAllParents($parentId, $id)
    {
        $parentObject = $this->currentData($parentId);
        $parentAllChildren = $parentObject['all_children'];
        if (empty($parentAllChildren)) {
            $parentAllChildren = [];
        } else {
            $parentAllChildren = json_decode($parentAllChildren);
        }
        array_push($parentAllChildren, intval($id));
        $this->categoryDb->where('id', $parentId)->update(['all_children' => json_encode($parentAllChildren), 'has_children' => 1]);
        $grantParentId = $parentObject['parent_id'];
        if (intval($grantParentId) !== 0) {
            $this->updateAllParents($grantParentId, $id);
        }
    }

    private function removeSpecifyCategory($parentId, $id)
    {
        $parentObject = $this->currentData($parentId);
        $parentObjectAllChildren = json_decode($parentObject['all_children']);
        $parentObjectAllChildrenCount = count($parentObjectAllChildren);
        if ($parentObjectAllChildrenCount === 1) {
            Db::name('category')->where('id', $parentObject['id'])->update(['all_children' => json_encode([]), 'has_children' => 0]);
        } else {
            $key = array_keys($parentObjectAllChildren, $id);
            array_splice($parentObjectAllChildren, $key[0], 1);
            Db::name('category')->where('id', $parentObject['id'])->update(['all_children' => json_encode($parentObjectAllChildren)]);
        }
        if (intval($parentObject['parent_id']) !== 0) {
            $this->removeSpecifyCategory($parentObject['parent_id'], $id);
        }
    }

    public function orderAction()
    {
        $dataFromPost = request()->post('cv/a', null);
        $needOrders = $dataFromPost['category'];
        foreach ($needOrders as $key => $value) {
            Db::name('category')->where('id', $key)->update(['weight' => $value]);
        }
        CacheKit::updateCategoryCache();
        return json(['success' => true, 'message' => lang('Success')]);
    }
}