<?php
declare (strict_types = 1);

namespace app\model\admin;

use library\basic\BaseModel;
use library\traits\JwtAuthModelTrait;
use library\traits\ModelTrait;
use think\Model;

/**
 * @mixin \think\Model
 */
class Product extends BaseModel
{
    use ModelTrait;
    use JwtAuthModelTrait;
    //仓库
    private $warehouse;




    /**
     * 获取列表数据
     * @param $page
     * @param $where
     * @param $pageCount
     * @param $desc
     */
    public function getList($page,$where = [],$pageCount = 20,$filed = '*',$desc = ''){
        $data =  $this
            ->field("p.*,(SELECT cate_name from table_category where p.cate_id = id) as cate_name")
            ->alias("p")
            ->order($desc)
            ->paginate(['list_rows'=>$pageCount,'page'=>$page])
            ->toArray();
        foreach ($data['data'] as $k=>$v) {
            $data['data'][$k]['warehouseAr'] = $this->getWarehouse($v['warehouse_ids']);
            $data['data'][$k]['add_time'] = date('Y-m-d',$v['add_time']);
        }
        return [$data['total'],$data['data']];
    }


    /**
     * 保存产品数据
     * @param $post
     * @return bool|int|string
     */
    public function saveProduct($post){
        if(!empty($post['id'])) {
            $this->where('id',$post['id'])->save($post);
            return true;
        } else {
            unset($post['id']);
            $post['add_time'] = time();
            $bool = $this->insert($post);
            return $bool;
        }
    }


    /**
     * 删除数据
     * @param $id
     */
    public function delProduct($id) {
        $this->where('id',$id)->delete();
        return true;
    }


    /**
     * 获取仓库数据
     * @param $ids
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getWarehouse($ids) {
        $idAr = explode(',',$ids);
        $rAr = [];
        if(empty($this->warehouse))
            $this->warehouse = (new Warehouse)->select()->toArray();
        foreach ($this->warehouse as $v) {
            if(in_array($v['id'],$idAr)) {
                $rAr[] = $v;
            }
        }
        return $rAr;
    }


}
