<?php
namespace app\common\model;

use think\Db;

class GGoods extends Base
{

    public function updates(){
        $data = request()->post();
        $data['org_id'] = cur_org_id();

        $result = validate('GGoods')->check($data,[],'');
        if(true !== $result){
            $this->error = validate('GGoods')->getError();
            return false;
        }
        if(!empty($data['imgs'])){
            $data['imgs']=implode(',',$data['imgs']);;
        }

        $id = $data['id'];
        unset($data['id']);
        if($id > 0){
            $data['update_time'] = date('Y-m-d H:i:s');
            $ret = $this->allowField(true)->save($data,['id'=>$id]);
        }else{
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = $this->allowField(true)->save($data);
        }
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }


    public function lists($cateId,$title,$page,$size,$orgId){
        $map[] = ['org_id','=',$orgId];
        $map[] = ['enable','=',1];
        $map[] = ['del','=',0];
        if($cateId > 0){
            $map[] = ['cate_id','=',$cateId];
        }
        if($title != ''){
            $map[] = ['title','like','%'.$title.'%'];
        }
        $ret=Db::name('g_goods')
            ->field('id,title,price,img,sale_price,type')
            ->where($map)
            ->order(['sort'=>'asc','id'=>'desc'])
            ->page($page,$size)
            ->select();
        foreach ($ret as $k=>$v){
            if($v['type'] == 1){
                $ret[$k]['price']=$v['sale_price'];
            }
            unset($ret[$k]['sale_price']);
        }
        return $ret?$ret:[];
    }

    public function details($id){
        $ret=Db::name('g_goods')
            ->field('id,title,price,img,imgs,sale,stock,content,type,sale_price')
            ->where('id',$id)
            ->find();
        if($ret){
//            $ret['content']=format_editor($ret['content']);
            $ret['imgs']=$ret['imgs']?explode(',',$ret['imgs']):[];
            if($ret['type'] == 1){
                $ret['price']=$ret['sale_price'];
            }
            unset($ret['sale_price']);
        }
        return $ret;
    }
    public function saleList($orgId){
        $map[] = ['org_id','=',$orgId];
        $map[] = ['enable','=',1];
        $map[] = ['del','=',0];
        $map[] = ['type','=',1];
        $ret=Db::name('g_goods')
            ->field('id,title,img,sale_price as price')
            ->where($map)
            ->order(['sort'=>'asc','id'=>'desc'])
            ->limit(4)
            ->select();
        return $ret?$ret:[];
    }

}