<?php


namespace App\Http\Validators;

use App\Http\Services\SupplierPayTypeService;
use App\Model\SupplierAttachmentModel;
use App\Model\SupplierChannelModel;
use App\Model\SupplierContactModel;
use Validator;

class SupplierValidator
{
    //保存相关的验证,别问我为什么不用laravel自带的form-request类
    //因为控制器那边已经被之前的人魔改的难用的一比,而且控制器那边还接收了一大堆统一变量
    public function checkSave($validateData, $isAudit)
    {
        //整理下请求数据
        $validateData = $this->transformRequestData($validateData);

        $supplierId = $validateData['supplier_id'];

        //如果是直接提交,不是点申请审核的,只需要校验供应商名称是否存在即可
        if (!$isAudit) {
            if (empty($validateData['supplier_name'])) {
                return '供应商名称不能为空';
            }
            if (empty($supplierId)) {
                $count = SupplierChannelModel::where('supplier_name', $validateData['supplier_name'])->count();
            } else {
                $count = SupplierChannelModel::where('supplier_name', $validateData['supplier_name'])
                    ->where('supplier_id', '!=', $supplierId)->count();
            }
            if ($count) {
                return "该供应商名称已经存在,请核验后再提交";
            }

            return null;
        }

        $rules = [
            'supplier_type' => 'required',
            'supplier_name' => 'required',
            'legal_representative' => 'required',
            'stockup_type' => 'required',
            'main_brands' => 'required',
            'currency' => 'required',
            'main_customers' => 'max:100',
            'ticket_time' => 'max:20',
            'region' => 'required',
            'cn_delivery_time' => 'regex:/^\d+\-\d$/',
            'us_delivery_time' => 'regex:/^\d+\-\d$/',
            'shipping_address' => 'max:100',
            'billing_period_detail' => 'required|max:100',
            'return_address' => 'max:100',
            'return_consignee' => 'max:50',
            'return_phone' => 'max:50',
            'cn_ratio' => 'min:1',
            'us_ratio' => 'min:1',
        ];
        $contactRuler = [
            'supplier_consignee' => 'required|max:50',
            'supplier_mobile' => 'required|max:30',
            'supplier_telephone' => 'required|max:30',
            'supplier_email' => 'required|email',
            'supplier_position' => 'required|max:30',
            'can_check_uids' => 'required',
        ];

        //只有在提交供应商是正式的时候,才会去校验附件
        if ($validateData['supplier_type'] == 1) {
            //产品要把表单校验改成审核的时候才去校验,这个时候附件就要单独去取值了,要不然这个时候提交上来的肯定没有附件信息
            $attachments = SupplierAttachmentModel::where('supplier_id', $supplierId)->first();
            $attachments = !empty($attachments) ? $attachments->toArray() : [];
            $validateData = array_merge($validateData, $attachments);
            //校验附件,只要营业执照、商业登记证、公司注册证至少其中一个上传了附件,就判定已经上传了附件
            $attachmentValidateFields = [
                'business_license',
                'registration_certificate',
                'incorporation_certificate'
            ];
            $attachmentValidateFieldsExist = false;
            foreach ($attachmentValidateFields as $field) {
                if (array_get($validateData, $field)) {
                    $attachmentValidateFieldsExist = true;
                    break;
                }
            }
            if (!$attachmentValidateFieldsExist) {
                return '附件里营业执照、商业登记证、公司注册证至少要上传一个';
            }

            //如果供应商性质是现货商,那么品质协议也不能为空
            if ($validateData['supplier_group'] == 2) {
                if (empty($validateData['quality_assurance_agreement'])) {
                    return '该供应商为现货商,请上传品质协议!';
                }
            }
        }


        //第一次新增的时候,是要校验联系人的
        if (empty($validateData['supplier_id'])) {
            $rules = array_merge($rules, $contactRuler);
        }

        //币种为人民币的话需要验证税号
        if ($validateData['currency'] == 1) {
            $rules['tax_number'] = 'required';
        }

        //新增的时候,渠道开发不能为空
        if (empty($validateData['supplier_id'])) {
            $rules['purchase_uid'] = 'required';
        }

        $messages = $this->messages();
        $validator = Validator::make($validateData, $rules, $messages);
        if ($validator->fails()) {
            return $validator->errors()->first();
        }


        //检验名称是否已经存在数据库
        $companyNameCount = 0;
        if (empty($supplierId)) {
            $count = SupplierChannelModel::where('supplier_name', $validateData['supplier_name'])->count();
            $companyNameCount = SupplierChannelModel::where('register_company_name',
                $validateData['register_company_name'])->where('register_company_name', '!=', '')->count();
        } else {
            $count = SupplierChannelModel::where('supplier_name', $validateData['supplier_name'])
                ->where('supplier_id', '!=', $supplierId)->count();
            //至少要有一个联系方式
            $contactCount = SupplierContactModel::where('supplier_id', $supplierId)->count();
            if (!$contactCount) {
                return "供应商至少要有一个联系人,请补全";
            }
        }
        if ($count) {
            return "该供应商名称已经存在,请核验后再提交";
        }
        if ($companyNameCount) {
            return "该注册公司名已经存在,请核验后再提交";
        }

        if (!empty($supplierId)) {
            //还要去判断当前提交人是否存在与其关联的联系人没有完善
            $codeId = request()->user->codeId;
            $notCompleteContacts = SupplierContactModel::where('supplier_id', $supplierId)
                ->where('can_check_uids', $codeId)
                ->where(function ($q) {
                    $q->where('supplier_consignee', '')
                        ->orWhere('supplier_position', '')
                        ->orWhere('supplier_email', '')
                        ->orWhere('supplier_mobile', '')
                        ->orWhere('supplier_telephone', '');
                })->get();
            $notCompleteContacts = !empty($notCompleteContacts) ? $notCompleteContacts->toArray() : [];
            if ($notCompleteContacts) {
                return "存在和你相关的联系人没有完善,请先去完善相关联系人";
            }
        }
    }

    private function messages()
    {
        return [
            'supplier_type.required' => '供应商类别不能为空',
            'supplier_name.required' => '供应商名称不能为空',
            'currency.required' => '结算币种不能为空',
            'legal_representative.required' => '法人代表不能为空',
            'stockup_type.required' => '合作类型不能为空',
            'register_company_name.required' => '注册公司名不能为空',
            'supplier_group.required' => '公司性质不能为空',
            'supplier_address.required' => '注册地址不能为空',
            'region.required' => '所在区域不能为空',
            'purchase_uid.required' => '渠道开发员不能为空',
            'cn_ratio.min' => '人民币系数必须是大于1的浮点数',
            'business_license.required' => '营业执照不能为空',
            'established_time.required' => '成立时间不能为空',
            'us_ratio.min' => '美金系数必须是大于1的浮点数',
            'us_delivery_time.regex' => '香港货期格式不正确',
            'cn_delivery_time.regex' => '大陆货期格式不正确',
            'tax_number.required' => '如果选择币种为人民币,则公司税号不能为空',
            'supplier_consignee.required' => '联系方式的联系人不能为空',
            'supplier_consignee.max' => '联系方式的联系人不能超过50个字符',
            'supplier_position.required' => '联系方式的职称不能为空',
            'supplier_position.max' => '联系方式的职称不能超过30个字符',
            'supplier_telephone.required' => '联系方式的座机号不能为空',
            'supplier_mobile.required' => '联系方式的手机号不能为空',
            'supplier_mobile.max' => '联系方式的手机号不能超过30个字符',
            'supplier_email.required' => '联系方式的邮箱不能为空',
            'supplier_email.email' => '联系方式的邮箱格式不对',
            'can_check_uids.required' => '联系方式对应的采购员不能为空',
            'shipping_address.required' => '发货地址不能为空',
            'shipping_address.max' => '发货地址不能超过100个字符',
            'return_address.max' => '退货地址不能超过100个字符',
            'return_consignee.max' => '退货收货人不能超过50个字符',
            'return_phone.max' => '退货收货人电话不能超过50个字符',
            'main_brands.required' => '主营品牌不能为空',
            'main_customers.max' => '3-5家客户描述不能超过100个字符',
            'ticket_time.max' => '到票时间不能超过20个字符',
            'billing_period_detail.required' => '账期详情不能为空',
            'billing_period_detail.max' => '账期详情不能超过100个字符',
        ];
    }

    public function transformRequestData($validateData)
    {
        foreach ($validateData as &$item) {
            if (!is_array($item)) {
                $item = trim($item);
            }
        }
        return $validateData;
    }
}