<?php
namespace app\adminapi\controller;

use app\adminapi\BaseController;
use support\Request;
use think\facade\Db;

class CateController extends BaseController
{
    public function getCateList(Request $request)
    {
        $param = $request->get();

        $where = [];

        $list = Db::name('category')
            ->where('lang',$param['lang'])
            ->order('sort_order', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();

        $list = $this->genCategoryTree($list);
        
        // foreach($list as $key => $val){

        // }

        return $this->Success($list);
    }

    public function genCategoryTree($list,$parent_id = 0){
        $tree = [];
        foreach($list as $key => $val){
            if($val['parent_id'] == $parent_id){
                $val['children'] = $this->genCategoryTree($list,$val['id']);
                $tree[] = $val;
            }
        }
        return $tree;
    }

    public function getParentCateList(Request $request)
    {
        $param = $request->get();

        $where = [];

        $list = Db::name('category')
            ->where('lang',$param['lang'])
            ->where('parent_id',0)
            ->order('sort_order', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();

        
        // foreach($list as $key => $val){

        // }

        return $this->Success($list);
    }


    public function getCategory(Request $request){
        $id = $request->get('id');

        $result = Db::name('category')
        ->where('id',$id)
        ->find();

        if(!$result){
            return $this->Error('資料不存在');
        }

        return $this->Success($result);
    }

    public function addCategory(Request $request){
        $params = $request->post();
        
        $data = [
            "lang" => isset($params['lang'])?$params['lang']:'tw',
            "parent_id" => isset($params['parent_id'])?$params['parent_id']:0,
            "name" => isset($params['name'])?$params['name']:'',
            "imageurl" => isset($params['imageurl'])?getUrl().$params['imageurl']:'',
        ];
        
        try{
            $id = Db::name('category')->insertGetId($data);

            AdminLog( $this->uid , '新增產品類別 ' . $id);

            return $this->Success('操作成功');
        }catch(\Exception $e){
            AdminLog( $this->uid , '新增產品類別失敗');
            
            return $this->Error('操作失敗:'. $e->getMessage());                
        }
    }

    public function deleteCategory(Request $request){
        $id = $request->get('id');

        try{
            $result = Db::name('category')
            ->where('id',$id)
            ->delete();
    
            AdminLog($this->uid, '刪除產品類別 '. $id);
            return $this->Success('操作成功');    
        }catch(\Exception $e){
            AdminLog($this->uid, '刪除產品類別'.$id.'失敗');
            return $this->Error('操作失敗');                
        }
    }

    public function updateCategory(Request $request){
        $params = $request->post();
        
        $data = [
            "lang" => isset($params['lang'])?$params['lang']:'tw',
            "parent_id" => isset($params['parent_id'])?$params['parent_id']:0,
            "name" => isset($params['name'])?$params['name']:'',
            "imageurl" => getUrl().isset($params['imageurl'])?$params['imageurl']:'',
            "sort_order" => isset($params['sort_order'])?$params['sort_order']:100,
        ];

        try{
            $result = Db::name('category')
            ->where('id',$params['id'])
            ->update($data);

            AdminLog($this->uid, '修改產品類別 [' . $params['id'] .']');
    
            return $this->Success('操作成功');
        }catch(\Exception $e){

            AdminLog($this->uid, '修改產品類別 [' . $params['id'] . '] 失敗');
            
            return $this->Error('操作失敗:'. $e->getMessage());                
        }
    }


    public function uploadImage(Request $request){
        $file = $request->file('file');

        if ($file && $file->isValid()) {
            // 產生唯一的檔名
            $filename = uniqid() . '.' . $file->getUploadExtension();

            $file->move(public_path().'/storage/category/'. $filename);
            $savePath = '/storage/category/'. $filename;
            return $this->Success($savePath);
        }
        return $this->Error('操作失敗');
    }
    
}