<?php


namespace App\Http\Services;


use App\Model\LogModel;
use App\Model\SupplierChannelModel;
use App\Model\SupplierContactModel;

class SupplierContactService
{
    //获取组装后给数据库使用的联系人数据
    public function getContactData($supplierId, $contact)
    {
        $contactData = [];
        foreach ($contact['supplier_mobile'] as $key => $value) {
            $contactData[] = [
                'supplier_id' => $supplierId,
                'contact_id' => $contact['contact_id'][$key],
                'supplier_consignee' => $contact['supplier_consignee'][$key],
                'supplier_telephone' => $contact['supplier_telephone'][$key],
                'supplier_mobile' => $contact['supplier_mobile'][$key],
                'supplier_qq' => $contact['supplier_qq'][$key],
                'supplier_fax' => $contact['supplier_fax'][$key],
                'supplier_email' => $contact['supplier_email'][$key],
                'supplier_position' => $contact['supplier_position'][$key],
                'add_time' => time(),
                'can_check_uids' => request()->user->userId,
            ];
            $contactData = array_filter($contactData, function ($contact) {
                if (empty($contact['supplier_consignee']) && empty($contact['supplier_telephone'])
                    && empty($contact['supplier_mobile'])) {
                    return false;
                }
                return true;
            });
        }
        return $contactData;
    }

    public function saveContact($contact)
    {
        $model = new SupplierContactModel();
        //判断新增还是编辑
        //还要将采购的数据整理重新写入
        $supplierId = $contact['supplier_id'];
        $supplierModel = new SupplierChannelModel();
        //去判断该供应商是否已经有相同的can_check_uids并且是空联系人
        $needReplaceContact = $this->getNeedReplaceContact($supplierId, $contact['can_check_uids']);
        if (!empty($contact['contact_id'])) {
            $contact['update_time'] = time();
            $contactId = $contact['contact_id'];
            $oldContact = $model->where('contact_id', $contact['contact_id'])->first()->toArray();
            $result = $model->where('contact_id', $contact['contact_id'])->update($contact);
        } else {
            //进行新增操作的时候,还要去判断是否这次新增的采购员ID在库里面是否有空白联系人的记录
            //有的话直接替换就可以
            if ($needReplaceContact) {
                $oldContact = $model->where('contact_id', $needReplaceContact['contact_id'])->first()->toArray();
                $contactId = $needReplaceContact['contact_id'];
                $contact['contact_id'] = $contactId;
                $contact['update_time'] = time();
                $contact['admin_id'] = request()->user->userId;
                $result = $model->where('contact_id', $contactId)->update($contact);
            } else {
                $oldContact = [];
                $contact['add_time'] = time();
                $contact['admin_id'] = request()->user->userId;
                $result = $model->insertGetId($contact);
                $contactId = $result;
            }

        }
        //找出所有的联系人对应的采购id,更新主表
        $canCheckUids = $model->where('supplier_id', $supplierId)->pluck('can_check_uids');
        if (!empty($canCheckUids)) {
            $canCheckUids = array_unique($canCheckUids->toArray());
            $canCheckUids = implode(',', $canCheckUids);
        } else {
            $canCheckUids = '';
        }

        $supplierModel->where('supplier_id', $supplierId)->update([
            'channel_uid' => $canCheckUids,
            'update_time' => time(),
        ]);

        $newContact = $model->where('contact_id', $contactId)->first()->toArray();
        if ($result) {
            //如果修改的只是qq和传真,则不需要转成审核
            $needAudit = $this->checkNeedAudit($oldContact, $newContact);
            if ($needAudit || empty($contact['contact_id'])) {
                //修改供应商为审核状态
                $supplierModel->where('supplier_id', $contact['supplier_id'])->update([
                    'update_time' => time(),
                    'status' => SupplierChannelModel::STATUS_PENDING,
                ]);
            }

            $logService = new LogService();
            $content = !empty($contact['contact_id']) ? '修改联系人' : '添加联系人';
            $remark = json_encode([
                'old_contact' => $oldContact,
                'new_contact' => $newContact,
            ]);
            $logService->AddLog($contact['supplier_id'], LogModel::UPDATE_OPERATE, '修改供应商基本资料', $content, $remark);
        }

        return $result;
    }

    //判断是否需要替换掉空的联系方式而不是新增,因为新增的时候,可能添加的采购已经在数据库有了(之前从金蝶导过来的)
    //有的话,就把这次新增的联系方式更新到这个采购里面去
    public function getNeedReplaceContact($supplierId, $canCheckUids)
    {
        $contactModel = new SupplierContactModel();
        $contact = $contactModel->where('supplier_id', $supplierId)->where('can_check_uids', $canCheckUids)
            ->where('supplier_consignee', '')
            ->where('supplier_position', '')
            ->where('supplier_email', '')
            ->where('supplier_mobile', '')
            ->where('supplier_telephone', '')->first();
        return !empty($contact) ? $contact->toArray() : [];
    }

    //判断是否要进入审核中状态,因为部分字段修改是不需要走审核的
    private function checkNeedAudit($oldContact, $newContact)
    {
        $notNeedAuditField = [
            'supplier_qq',
            'supplier_fax',
        ];
        $diff = array_merge(array_diff($oldContact, $newContact), array_diff($newContact, $oldContact));
        unset($diff['update_time']);
        $changeField = array_keys($diff);
        foreach ($changeField as $filed) {
            //只要有一个不存在于不需要审核的字段,就返回需要审核
            if (!in_array($filed, $notNeedAuditField)) {
                return true;
            }
        }
        return false;
    }

    //如果申请人属于联营采购部/自营采购部,业务负责人取绑定的采购员为申请人的联系人(如果有多条,随机取一条);
    //如果申请人属于渠道部,渠道开发员没有设置采购,则显示为空;如果渠道开发员显示自己为采购,显示自己对应的联系人;如果创建其他采购,显示创建采购对应的联系人(如果有多条,随机取一条)
    //获取用于打印的联系方式
    public function getContactForPrint($supplierId)
    {
        $userId = request()->user->userId;
        $codeId = request()->user->codeId;
        $contactModel = new SupplierContactModel();
        $contact = $contactModel->where('can_check_uids', $codeId)->where('supplier_id', $supplierId)
            ->first();
        $contact = !empty($contact) ? $contact->toArray() : [];
        if (empty($contact)) {
            $contact = $contactModel->where('admin_id', $userId)->where('supplier_id', $supplierId)
                ->first();
            $contact = !empty($contact) ? $contact->toArray() : [];
        }
        return $contact;
    }

    //通过采购员编码直接创建空白的默认联系方式
    public function createContactByChannelUid($supplierId, $channelUid)
    {
        //先去判断是否已经有对应的采购
        $contactModel = new SupplierContactModel();
        $count = $contactModel->where('supplier_id', $supplierId)->where('can_check_uids', $channelUid)->count();
        if ($count) {
            return true;
        }
        $contact['can_check_uids'] = $channelUid;
        $contact['supplier_id'] = $supplierId;
        $contact['add_time'] = time();
        $contact['admin_id'] = request()->user->userId;
        $result = $contactModel->insert($contact);
        if ($result) {
            $channelUids = $contacts = $contactModel->where('supplier_id',$supplierId)->pluck('can_check_uids')->toArray();
            $supplierModel = new SupplierChannelModel();
            $result = $supplierModel->where('supplier_id',$supplierId)->update([
                'channel_uid' => implode(',', $channelUids),
                'update_time' => time(),
            ]);
            $adminService = new AdminUserService();
            $user = $adminService->getAdminUserInfoByCodeId($channelUid);
            $channelUserName = array_get($user, 'name');
            //还要记录日志
            $logService = new LogService();
            $content = "共用申请审核通过,添加采购员 : " . $channelUserName;
            $logService->AddLog($supplierId, LogModel::UPDATE_OPERATE, '添加采购员', $content);
        }
        return $result;
    }

}