<?php

namespace App\Repositories;


use App\Models\CmsSubject;
use App\Models\CmsSubjectProduct;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Dingo\Api\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;

class CmsSubjectRepository {
    public function __construct(CmsSubject $cmsSubject,CmsSubjectProduct $cmsSubjectProduct) {

        $this->cmsSubject = $cmsSubject;
        $this->cmsSubjectProduct = $cmsSubjectProduct;
    }
    //专题列表
    public function index($request)
    {
        $where = [];
        if(isset($request['id'])){
            $where[] = ['id', '=', $request['id']];
        }

        return $this->cmsSubject->where($where)->orderBy('id', 'asc')->paginate(20);

    }

    /**
     * 添加专题
     */
    public function create($request)
    {
        if($this->cmsSubject->where('title', trim($request['title']))->exists()){
            throw new HttpException(500, '该专题已经存在');
        }

        $subject = [
            'title' => $request['title'],
            'city_id' => $request['city_id'],
            'city_name' => $request['city_name'],
            'show_type' => $request['show_type'],
            'is_open' => $request['is_open'],
        ];
        $date = date('Y-m-d H:i:s');

        DB::beginTransaction();
        try{
            $res = $this->cmsSubject->create($subject);
            if ($res && $request['product_id']){
                $products = explode(',',$request['product_id']);
                $sort = explode(',',$request['sort']);

                $product_num = count($products);
                $sort_num = count($sort);
                if ($sort_num != $product_num){
                    throw new HttpException(500, '请检查商品与排序数目是否对应');
                }

                $subject_product = new CmsSubjectProduct();
                for ($i = 0;$i < $product_num;$i++){
                    $resert_data =[
                        'product_id' => $products[$i],
                        'sort' => $sort[$i],
                        'subject_id' => $res['id'],
                        'created_at' => $date,
                        'updated_at' => $date,
                    ];
                 $subject_product->insert($resert_data);

                }
            }
            DB::commit();
            return Response::create();

        }catch (QueryException $exception){
            DB::rollBack();
            return Response::create([
                'message'  => '添加失败,请重试',
                'error' => $exception->getMessage(),
                'status_code'   => 500
            ]);
        }
    }

    public function edit($request)
    {
        $subject = $this->cmsSubject->find($request['id']);

        $subject->title = $request['title'];
        $subject->city_id = $request['city_id'];
        $subject->city_name = $request['city_name'];
        $subject->show_type = $request['show_type'];
        $subject->is_open = $request['is_open'];

        $date = date('Y-m-d H:i:s');

        DB::beginTransaction();
        try{
            $res = $subject->save();

            if($res && $request['product_id']) {
                $this->cmsSubjectProduct->where('subject_id',$subject->id)->delete();

                $products = explode(',', $request['product_id']);
                $sort = explode(',', $request['sort']);

                $product_num = count($products);
                $sort_num = count($sort);
                if ($sort_num != $product_num) {
                    throw new HttpException(500, '请检查商品与排序数目是否对应');
                }

                $subject_product = new CmsSubjectProduct();
                for ($i = 0; $i < $product_num; $i++) {
                    $resert_data = [
                        'product_id' => $products[$i],
                        'sort' => $sort[$i],
                        'subject_id' => $subject->id,
                        'created_at' => $date,
                        'updated_at' => $date,
                    ];
                    $subject_product->insert($resert_data);
                }
            }
            DB::commit();
            return Response::create();

        }catch (QueryException $exception){
            DB::rollBack();
            return Response::create([
                'message'  => '编辑失败,请重试',
                'error' => $exception->getMessage(),
                'status_code'   => 500
            ]);
        }
    }

    public function delete($request)
    {
        $subject = $this->cmsSubject->find($request['id']);

        DB::beginTransaction();
        try{
            $res = $subject->delete();
            if ($res){
                $this->cmsSubjectProduct->where('subject_id',$subject->id)->delete();
            }
                DB::commit();
                return Response::create();

        }catch (QueryException $exception){
            DB::rollBack();
            return Response::create([
                'message'  => '删除失败,请重试',
                'error' => $exception->getMessage(),
                'status_code'   => 500
            ]);
        }

    }

}