<?php
namespace app\shared\logic\store;
use app\shared\model\Goods;
use app\shared\model\GoodsCat;
use app\shared\model\GoodsAttr;
use think\exception\ValidateException;
use app\BaseController;
class GoodsForm extends  Base
{
    //获取数据
    public  function index(){
        $query=Goods::where(['acid'=>$this->acid,'is_delete'=>0,'store_id'=>$this->store_id]);
        $queryCount=Goods::where(['acid'=>$this->acid,'is_delete'=>0,'store_id'=>$this->store_id]);
        if($status=input('status')){
            if($status==1){
                $query->where('status',1);
                $queryCount->where('status',1);
            }
            if($status==-1){
                $query->where('status',0);
                $queryCount->where('status',0);
            }
        }
        if($keyword=input('keyword')){
            $query->where('name','like',"%{$keyword}%");
            $queryCount->where('name','like',"%{$keyword}%");
        }
        $list=$query
        ->page($this->page)
        ->limit($this->limit)
        ->order('id DESC')
        ->select()
        ->toArray();
        foreach ($list as $key => &$value) {
            $value['cover_url']=get_file_url($value['cover']);
            $value['images_url']=get_file_urls($value['images']);
            $value['cat_str']=GoodsCat::where('id','in',$value['cat_id'])->column('title');
            if($value['use_attr']==0){
                $value['attr']=[];
                $value['attribe_list']=[];
            }else{
                $attr=GoodsAttr::where(['is_delete'=>0,'goods_id'=>$value['id']])->order('index ASC')->column('attr_list,price,stock,integral,index');
                foreach ($attr as $k=>&$v){
                    $v['attr_list']=json_decode($v['attr_list'],1);
                }
                $value['attr']=$attr;
                $value['attribe_list']=json_decode($value['attribe_list'],1);
            }
        }
        $count=$queryCount->count();
        return fetchJson([
            'list'=>$list,
            'count'=>$count
        ]);
    }
    //商品编辑
    public function edit(){
        try {
            $data=request()->post();
            $rule = [
                'id|ID' =>'require|number',
                'name|商品名称'   => 'require',
                'price|售价'=>'require',
                'original_price|原价'=>'require',
                'detail|商品详情'=>'require',
                'cat_id|商品类别'=>'require',
                'status|上架状态'=>'require',
                'service|商品服务'=>'require',
                'sort|排序'=>'require',
                'virtual_sales|虚拟销量'=>'require',
                'cover|商品封面'=>'require|number',
                'images|商品图片'=>'require',
                'unit|单位'=>'require',
                'weight|重量'=>'require',
                'use_attr|是否使用规格'=>'require',
                'cost_price|成本价'=>'require|float|>:0.01',
            ];
            $this->validate($data,$rule);
        } catch (ValidateException $e){
            return fetchJson([],$e->getError(),1);
        }
        $form=Goods::where(['acid'=>$this->acid,'id'=>$data['id']])->find();
        if(!$form){
            $form=new Goods();
            $form->acid=$this->acid;
            $form->store_id=$this->store_id;
        }
        $form->name=$data['name'];
        $form->price=$data['price'];
        $form->original_price=$data['original_price'];
        $form->detail=$data['detail'];
        $form->cat_id=$data['cat_id'];
        $form->status=$data['status'];
       
        $form->attribe_list=$data['attribe_list'];
        $form->service=$data['service'];
        $form->virtual_sales=$data['virtual_sales'];
        $form->cover=$data['cover'];
        $form->images=$data['images'];
        //$form->video_url=$data['video_url'];
        $form->unit=$data['unit'];
        $form->use_attr=$data['use_attr'];
        $form->cost_price=$data['cost_price'];
        $form->goods_num=input('goods_num')?input('goods_num'):0;
        $form->integral=input('integral')?input('integral'):0;
        $form->pay_type=input('pay_type')?input('pay_type'):0;
        $attr=$data['attr'];
        if($form->use_attr==0){
            $attr='[{"attr_list":[{"attr_id":1,"attr_name":"默认"}],"price":"'.$form->price.'","stock":"'.$form->goods_num.'","integral":"'.$form->integral.'","weight":"","index":0}]';
            $form->attribe_list='[{"attr_group_id":1,"attr_group_name":"默认","is_check_img":false,"attr_list":[{"img":"","attr_id":1,"attr_name":"默认"}]}]';
        }
        $form->save();
        $attrList=json_decode($attr,1);
        GoodsAttr::where(['goods_id'=>$form->id])->update(['is_delete'=>1]);
        foreach($attrList as $key=>$value){
            $attr=GoodsAttr::where([
                'goods_id'=>$form->id,
                'index'=>$value['index'],
                'attr_list'=> json_encode($value['attr_list'])
            ])->find();
            if(!$attr){
                $attr=new GoodsAttr();
                $attr->index=$value['index'];
                $attr->goods_id=$form->id;
                $attr->attr_list=json_encode($value['attr_list']);
            }
            $attr->save([
                'price'=>$value['price'],
                'stock'=>$value['stock'],
                'is_delete'=>0
            ]);
        }
        $form->save();
        return fetchJson([],'保存成功');

    }
    //快速编辑
    public function quickedit(){
        $id=input('id');
        $field=input('field');
        $edittext=input('edittext');
        $fieldArray=['sort','status','name','is_store_hotsell','is_store_choiceness','is_delete'];

        $form=Goods::where(['acid'=>$this->acid,'id'=>$id])->find();
        if(!$form){
             return fetchJson([],'该数据未找到',1);
        }
        if(in_array($field,$fieldArray)){
            try {
               $form->save([
                   "{$field}"=>$edittext
               ]);
            } catch (ValidateException $e) {
                return fetchJson([],$e->getError(),1);
            } catch (\Exception $e) {
                return fetchJson([],$e->getMessage(),1);
            }
           return fetchJson([],'保存成功');
        }   
        return fetchJson([],'该字段不能编辑',1);
    }
    //删除
    public function delete(){
         $id=input('id');
         Goods::where(['acid'=>$this->acid,'id'=>$id])->update(['is_delete'=>1]);
         return fetchJson([],'删除成功');
    }
}