<?php


namespace App\Web\Models;



use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;


class ProductTypeRelationModel extends BaseModel
{
    /**
     * 状态字段
     */
    const DELETED_AT = 'status';
    /**
     * @var string
     */
    protected $table = 'product_type_relation';

    /**
     * 产品类型关系保存
     * */
    public function typeRelationSave($params,$userId=0){
        $productId=$params['product_id'];
        $typeIds=$params['type_ids'];
        $time=nowTime();
        if(!empty($typeIds)){
            //获取要保留下来的权限
            $remainedIds= $this->newInstance()
                ->where('product_id',$productId)
                ->where('status',0)
                ->whereIn('type_id',$typeIds)
                ->pluck('type_id')->toArray();
            $addTypeIds=array_diff($typeIds,$remainedIds);//获取要新增的权限
            $insertData=[];
            foreach ($addTypeIds as $value){
                $insertData[]=[
                    'type_id'=>$value,
                    'product_id'=>$productId,
                    'user_id'=>$userId,
                    'create_time'=>$time,
                    'update_time'=>$time
                ];
            }
            //插入新增的权限
            if(!empty($insertData)){
                $this->insert($insertData);
            }
            //删除移除的权限
            $this->where('product_id',$productId)->where('status',0)
                ->WhereNotIn('type_id',$typeIds)
                ->update(['status'=>2,'update_time'=>$time]);
        }else{
            $this->where('product_id',$productId)->where('status',0)
                ->update(['status'=>2,'update_time'=>$time]);
        }
        return $productId;
    }

    /**
     * 根据产品类型 保存产品关系
     * */
    public function addByTypeId($typeId, $productIds,$userId=0)
    {
        if (empty($productIds)) {
            return 0;
        }
        $yetProductIds = $this->newInstance()->alias('a')
            ->leftJoin('product as b','a.product_id','=','b.id')
            ->where('a.status','=',0)
            ->where('b.status','<',2)
            ->where('a.type_id','=',$typeId)
            ->whereIn('a.product_id',$productIds)
            ->pluck('a.product_id')->toArray();
        $addProductIds=$productIds;
        if(!empty($yetProductIds)){
            $addProductIds=array_diff($productIds,$yetProductIds);//获取要新增的权限
        }
        $saveData=[];
        foreach ($addProductIds as $productId) {
            $saveData[] = [
                'user_id' => $userId,
                'product_id' => $productId,
                'type_id' => $typeId
            ];
        }
        if(!empty($saveData)){
            $this->insert($saveData);
        }
        return true;
    }

    /**
     * 产品类型对应的产品数量
     * */
    public function getProductTypeCount($typeId){
        if(!is_array($typeId)){
            $typeId=[$typeId];
        }
        $rst = $this->newInstance()->alias('a')
            ->leftJoin('product as b','a.product_id','=','b.id')
            ->whereIn('a.type_id',$typeId)
            ->where('a.status','=',0)
            ->where('b.status','=',0)
            ->groupBy('a.type_id')
            ->select(DB::raw('a.type_id, count(*) as tmp_count'))
            ->get()
            ->toArray();

        $data = [];
        foreach ($rst as $v) {
            $data[$v['type_id']] = $v['tmp_count'];
        }
        return $data;
    }


    /**
     * 根据类型id及产品id 删除关联关系
     * */
    public function delTypeRelation($typeId, $productIds)
    {
        $ret=$this->newInstance()
            ->where('status','=',0)
            ->where('type_id','=',$typeId)
            ->whereIn('product_id',$productIds)
            ->update(['update_time'=>nowTime(),'status'=>2]);
        return $ret;
    }

    /**
     * 获取产品类型ids
     * */
    public function getTypeIds($productId){
        $typeIds= $this->newInstance()
            ->where('product_id','=',$productId)
            ->where('status','=',0)
            ->pluck('type_id')->toArray();
        return $typeIds;
    }

    public function getByTypeId($typeId)
    {
        if (empty($typeId)) {
            return [];
        }
        if( is_array($typeId)){
            $rst=$this->newInstance()->where('status','<',2)
                ->whereIn('type_id',$typeId)  ->get();
        }else{
            $rst=$this->newInstance()->where('status','<',2)
                ->where('type_id','=',$typeId)  ->get();
        }
        return empty($rst) ? []: $rst->toArray();
    }

    public function deleteByTypeId($typeId){
        $rst=$this->newInstance()
            ->where('type_id','=',$typeId)->update(['status'=>2]);
        return $rst;
    }


    /**
     * 根据产品id列表返回标签列表
     * */
    public function getTypeListByProductIds($productIds){
        $typeList= $this->newInstance()->alias('a')
            ->leftJoin('product_type as b','a.type_id','=','b.id')
            ->leftJoin('web_seo as c', 'b.seo_id', '=', 'c.id')
            ->whereIn('a.product_id',$productIds)
            ->where('a.status','=',0)
            ->where('b.status','=',0)
            ->selectRaw('a.product_id,a.type_id,b.type_name,c.urla,b.expand_content')->get();
        if(!empty($typeList)){
            $typeList=$typeList->toArray();
        }else{
            $typeList=[];
        }
        return $typeList;
    }

    /**
     * 添加关联关系
     * @param $productId
     * @param $typeIds
     */
    public function addByProductId($productId, $typeIds, $userId = 0)
    {
        $types = $this->getByProductId($productId);
        $hadTypeIds = array_column($types, 'type_id');
        $delTypeIds = array_values(array_diff($hadTypeIds, $typeIds));
        $typeIds = array_values(array_diff($typeIds, $hadTypeIds));
        //删除数据
        if ($delTypeIds) {
            $this->newInstance()
                ->where('product_id', $productId)
                ->whereIn('type_id', $delTypeIds)
                ->update(['status' => 2]);
        }
        if (empty($typeIds)) {
            return 0;
        }
        $saveData = [];
        foreach ($typeIds as $typeId) {
            if (empty($typeId)) {
                continue;
            }
            $saveData[] = [
                'user_id' => $userId,
                'product_id' => $productId,
                'type_id' => $typeId,
                'create_time'=>nowTime(),
                'update_time'=>nowTime()
            ];
        }
        return $this->insert($saveData);
    }

    public function getByProductId($productId)
    {
        if (empty($productId)) {
            return [];
        }
        if(!is_array($productId)) {
            $productId = [$productId];
        }
        $rst = $this->newInstance()
              ->whereIn('product_id', $productId)
              ->get();
        return empty($rst) ? []: $rst->toArray();
    }

    public function deleteByProductId($productId)
    {
        if (!is_array($productId)) {
            $productId = [$productId];
        }
        $ret = $this->newInstance()
            ->whereIn('product_id', $productId)
            ->update(['status' => 2]);
        return $ret;
    }

}
