<?php

namespace app\adminapi\controller;

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

class ProductController extends BaseController
{
    public function getProductList(Request $request)
    {
        $param = $request->post();
        $page       = isset($param['page']) ? $param['page'] : 1;
        $pageSize   = isset($param['pageSize']) ? $param['pageSize'] : 10;
        $search     = isset($param['search']) ? $param['search'] : [];

        $where = [];

        if(isset($search['cat_id']) && $search['cat_id'] > 0){
            $where[] = ['cat_id','=' ,$search['cat_id']];
        }

        if(isset($search['keyword']) && strlen($search['keyword']) >0){
            $where[] = ['name', 'like', '%'.$search['keyword'].'%'];
        }

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


        $total = Db::name('product')
            ->where($where)
            ->where('lang', $param['lang'])
            ->count();

        foreach($list as $key => $val){
            $list[$key]['cat_name'] = Db::name('category')
                ->where('id',$val['cat_id'])
                ->value('name');
        }

        $result = [
            'list' => $list,
            'total' => $total
        ];

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

    public function addProduct(Request $request){
        $params = $request->post();
        
        $data = [
            'lang' => $params['lang'],
            'name' => isset($params['name'])?$params['name']:'',
            'imageurl' => isset($params['imageurl'])?$params['imageurl']:'',
            'cat_id'    => isset($params['cat_id'])?$params['cat_id']:0,
            'description' => isset($params['description'])?$params['description']:'',
            'content' => isset($params['content'])?$params['content']:'',
            'create_time' => date('Y-m-d H:i:s',time())
        ];
        
        try{
            $id = Db::name('product')->insertGetId($data);

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

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

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

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

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

        $user = Db::name('product')
        ->where('id',$id)
        ->find();

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

        unset($user['password']);

        $result = $user;

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

    public function updateProduct(Request $request){
        $params = $request->post();
        
        $data = [
            'name' => isset($params['name'])?$params['name']:'',
            'imageurl' => isset($params['imageurl'])?$params['imageurl']:'',
            'cat_id'    => isset($params['cat_id'])?$params['cat_id']:0,
            'description' => isset($params['description'])?$params['description']:'',
            'content' => isset($params['content'])?$params['content']:'',
            'sort_order' => isset($params['sort_order'])?$params['sort_order']:100,
            'create_time' => date('Y-m-d H:i:s',time())
        ];

        try{
            $result = Db::name('product')
            ->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/product/'. $filename);
            $savePath = '/storage/product/'. $filename;
            return $this->Success($savePath);
        }
        return $this->Error('操作失敗');
    }

}
