<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Services\LogService;
use App\Http\Services\SupplierContactService;
use App\Http\Transformers\SupplierContactTransformer;
use App\Http\Validators\SupplierContactValidator;
use App\Model\SupplierChannelModel;
use App\Model\SupplierContactModel;
use Illuminate\Http\Request;

//通用API,比如获取品牌列表,分类列表等
class SupplierContactApiController extends Controller
{
    public function Entrance(Request $request, $id)
    {
        $this->$id($request, $id);
    }

    //获取供应商收款信息
    public function GetSupplierContactList($request)
    {
        $supplierId = $request->get('supplier_id');
        $limit = $request->get('limit', 10);
        $model = new SupplierContactModel();
        $model->where('supplier_id', $supplierId)->paginate();
        $list = $model->where('supplier_id', $supplierId)->orderBy('contact_id', 'desc')
            ->paginate($limit)->toArray();
        $transformer = new SupplierContactTransformer();
        $list['data'] = $transformer->transformList($list['data']);
        $this->response(0, 'ok', $list['data'], $list['total']);
    }

    public function SaveSupplierContact($request)
    {
        $data = $request->only([
            'contact_id',
            'supplier_id',
            'supplier_consignee',
            'supplier_telephone',
            'supplier_fax',
            'supplier_qq',
            'supplier_mobile',
            'supplier_email',
            'supplier_position',
            'can_check_uids'
        ]);
        //先去表单验证
        $validator = new SupplierContactValidator();
        $validateResult = $validator->checkSave($request);
        if ($validateResult) {
            $this->response(-1, $validateResult);
        }
        $service = new SupplierContactService();
        $result = $service->saveContact($data);
        if (!$result) {
            $this->response(-1, '操作失败');
        }
        $this->response(0, '保存成功');
    }

    public function DeleteSupplierContact($request)
    {
        $contactId = $request->get('contact_id');
        if ($contactId) {
            $model = new SupplierContactModel();
            $supplierId = $model->where('contact_id', $contactId)->value('supplier_id');
            $contactCount = $model->where('supplier_id', $supplierId)->count();
            if ($contactCount == 1) {
                $this->response(-1, '供应商至少要有一个联系方式');
            }
            $result = $model->whereIn('contact_id', $contactId)->delete();
            if (!$result) {
                $this->response(-1, '删除失败');
            }
            $supplierModel = new SupplierChannelModel();
            $supplierModel->where('supplier_id', $supplierId)->update([
                'update_time' => time(),
                'status' => 1,
            ]);
            $this->response(0, '删除成功');
        }
        $this->response(-1, '找不到删除对象');
    }
}