<?php


namespace App\Http\Services;

use App\Http\Controllers\Filter\SupplierFilter;
use App\Http\Transformers\SupplierTransformer;
use App\Http\Validators\SupplierValidator;
use App\Model\BigData\DataManageModel;
use App\Model\LogModel;
use App\Model\RedisModel;
use App\Model\SupplierAccountModel;
use App\Model\SupplierAddressModel;
use App\Model\SupplierAttachmentsModel;
use App\Model\SupplierChannelModel;
use App\Model\SupplierContactModel;
use App\Model\SupplierReceiptModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class SupplierService
{

    public $newSupplierId = 0;

    //获取供应商列表
    public function getSupplierList($map)
    {
        $model = new SupplierChannelModel();
        $query = $model->orderBy('update_time', 'desc');
        $filter = new SupplierFilter();
        $query = $filter->listFilter($map, $query);
        $limit = array_get($map, 'limit', 10);
        if (!empty($map['is_export'])) {
            $list = $query->get()->toArray();
        } else {
            $list = $query->paginate($limit)->toArray();
            $transformer = new SupplierTransformer();
            $list['data'] = $transformer->transformList($list['data']);
            //这里还要单独去处理采购员是否离职的显示,考虑到性能,所以再单独搞个方法出来了
            $list['data'] = $transformer->transformResignChannelUser($list['data']);
        }


        return $list;
    }


    public function getSupplier($supplierId, $getExtraInfo = false)
    {
        $model = new SupplierChannelModel();
        $query = $model->where('supplier_id', $supplierId)->with('contact');
        if ($getExtraInfo) {
            $query->with(['attachment', 'receipt']);
        }
        $supplier = $query->first();
        $transformer = new SupplierTransformer();
        $supplier = $transformer->transformInfo($supplier);
        return $supplier ? $supplier->toArray() : [];
    }


    //保存供应商信息的方法,逻辑很多,需要多多注意
    public function saveSupplier($channel)
    {
        $supplierTransformer = new SupplierTransformer();
        //先处理下数据
        $channel = $supplierTransformer->transformPostData($channel);
        $logService = new LogService();
        $model = new SupplierChannelModel();

        //获取未修改前的供应商,做日志数据比较存储
        $oldSupplier = $newSupplier = [];
        if (!empty($channel['supplier_id'])) {
            $oldSupplier = $model->where('supplier_id', $channel['supplier_id'])->first();
            $oldSupplier = $supplierTransformer->transformInfo($oldSupplier);
        }

        //判断是否要审核,默认是要审核的
        $needAudit = true;

        $isDirectApply = request()->get('direct_apply');

        //走事务
        $supplierId = DB::connection('web')->transaction(function () use ($channel, $model, $oldSupplier, &$needAudit) {

            //是否直接申请审核,如果是直接申请审核,那就变成待审核
            $isDirectApply = request()->get('direct_apply');

            $tagService = new SupplierTagService();
            //获取附加税数据
            $extraFax = [
                'supplier_id' => $channel['supplier_id'],
                'supplier_code' => $channel['supplier_code'],
                'hk' => $channel['hk'],
                'cn' => $channel['cn'],
            ];
            unset($channel['hk'], $channel['cn']);

            //获取收发货地有关的数据
            $address = array_only($channel, [
                'supplier_id',
                'shipping_address',
                'return_address',
                'return_consignee',
                'return_phone'
            ]);
            $shippingAddress = array_get($channel, 'shipping_address');
            unset(
                $channel['return_phone'],
                $channel['return_address'],
                $channel['return_consignee']
            );
            unset(
                $channel['shipping_address'],
                $channel['cn_delivery_time_period'],
                $channel['us_delivery_time_period'],
                $channel['attachment']
            );

            //sku上传规则相关设置
            $skuAuditRulerService = new SupplierSkuAuditRulerService();
            $channel['sku_audit_ruler'] = $skuAuditRulerService->getSkuAuditRulerForDB($channel['sku_audit_ruler']);

            /**新增供应商操作**/
            if (empty($channel['supplier_id'])) {
                //处理附件信息,新增的时候才会有附件信息提交过来
                $attachmentField = [
                    'file_name',
                    'file_url',
                    'field_name',
                    'field_name',
                    'validity_type',
                    'validity_period',
                    'description',
                ];
                $attachmentData = array_only($channel, $attachmentField);
                $channel = array_except($channel, $attachmentField);

                //处理银行信息,新增的时候才会有附件信息过来
                $receiptField = [
                    'receipt_type',
                    'bank_name',
                    'bank_adderss',
                    'account_no',
                    'account_name',
                    'account_adderss',
                    'certificate',
                    'swift_code',
                    'nation_id',
                    'intermediary_bank',
                ];
                $receiptData = array_only($channel, $receiptField);
                $channel = array_except($channel, $receiptField);

                //先去插入到channel表
                $channel['create_uid'] = request()->user->userId;
                $channel['create_name'] = request()->user->name;
                $channel['create_time'] = time();
                $channel['update_time'] = time();
                $channel = array_map(function ($value) {
                    if ($value === null) {
                        $value = (strval($value));
                    }
                    return $value;
                }, $channel);
                //默认是待提审
                //判断是否是直接添加并且申请审核
                if ($isDirectApply) {
                    $channel['status'] = SupplierChannelModel::STATUS_IN_REVIEW;
                } else {
                    $channel['status'] = SupplierChannelModel::STATUS_PENDING;
                }

                //第一次新增的供应商,都需要进行复审
                $channel['need_review'] = 1;

                //构建联系人的数据,只有新增的时候才有联系人数据
                $contactField = [
                    'supplier_consignee',
                    'supplier_position',
                    'supplier_email',
                    'supplier_mobile',
                    'supplier_telephone',
                    'supplier_qq',
                    'supplier_fax',
                    'can_check_uids',
                ];
                $contact = array_only($channel, $contactField);
                $channel = array_except($channel, $contactField);
                $channel['channel_uid'] = $contact['can_check_uids'];

                $channel['sku_upload_ruler'] = $this->getInitSkuUploadRuler();

                //插入供应商返回供应商id
                $supplierId = $this->newSupplierId = $model->insertGetId($channel);

                //插入sku上传规则
                $this->saveSkuUploadRulerToRedis($supplierId, $channel['sku_upload_ruler']);

                //添加联系人
                //要有数据才新增,麻烦得要死
                if (!checkArrayAllValueNull($contact)) {
                    $contact['supplier_id'] = $supplierId;
                    $contact['add_time'] = time();
                    $contact['admin_id'] = request()->user->userId;
                    SupplierContactModel::insert($contact);
                }
                if (!checkArrayAllValueNull($attachmentData)) {
                    //添加附件
                    SupplierAttachmentService::addAttachmentFromAddPage($supplierId, $attachmentData);
                }
                //添加银行信息,也是有填一个表单域也要新增,排除receipt_type字段,因为这个肯定有的
                if (!checkArrayAllValueNull($receiptData, ['receipt_type'])) {
                    $receiptData['supplier_id'] = $supplierId;
                    SupplierReceiptModel::insert($receiptData);
                }

                //如果是临时供应商,要打上临时供应商的标签
                if ($channel['supplier_type'] == SupplierChannelModel::SUPPLIER_TYPE_TEMPORARY) {
                    $tagService->saveTags($supplierId, SupplierTagService::TAG_TYPE_SYSTEM, '临时供应商', '');
                }

                //保存生成的内部编码
                $this->saveSupplierCode($supplierId);

                //新增的时候也要去添加地址了
                $supplierAddressService = new SupplierAddressService();
                $supplierAddressService->saveShippingAddress($supplierId, $shippingAddress);
            } else {
                /**这里的是更新供应商的操作**/
                $supplierId = $this->newSupplierId = $channel['supplier_id'];
                //要做进一步判断,部分字段修改不需要审核
                $auditService = new SupplierAuditService();
                $needAudit = $auditService->checkNeedAudit($supplierId, $channel);
                if ($needAudit) {
                    $channel['status'] = SupplierChannelModel::STATUS_PENDING;
                } else {
                    //不需要审核的话,那么还要直接同步到金蝶
                    $syncService = new SyncSupplierService();
                    $syncService->syncSupplierToErp($supplierId);
                }
                $channel['update_time'] = time();

                //这里有个逻辑,就是如果供应商类型是临时,那么要打上临时供应商的标签,如果不是,那么就要去掉这个标签
                if ($channel['supplier_type'] == SupplierChannelModel::SUPPLIER_TYPE_TEMPORARY) {
                    $channel['system_tags'] = explode(',', $channel['system_tags']);
                    if (!in_array('临时供应商', $channel['system_tags'])) {
                        $channel['system_tags'][] = '临时供应商';
                    }
                } else {
                    $channel['system_tags'] = explode(',', $channel['system_tags']);
                    foreach ($channel['system_tags'] as $key => $tag) {
                        if ($tag == '临时供应商') {
                            unset($channel['system_tags'][$key]);
                        }
                    }
                }
                //还有个逻辑就是,如果是临时供应商修改成正式供应商,就又要走一次复审
                if (
                    $channel['supplier_type'] == SupplierChannelModel::SUPPLIER_TYPE_OFFICIAL &&
                    $oldSupplier['supplier_type'] == SupplierChannelModel::SUPPLIER_TYPE_TEMPORARY
                ) {
                    $channel['need_review'] = 1;
                }

                $channel['system_tags'] = trim(implode(',', $channel['system_tags']), ',');

                $supplierAddressService = new SupplierAddressService();
                //校验是否需要同步修改地址给一体化
                $supplierAddressService->updateUnitedAddress($supplierId, $channel['supplier_address'], $address['shipping_address'], $address['return_address']);

                $model->where('supplier_id', $supplierId)->update($channel);
                //保存地址
                $supplierAddressService->saveAddress($address);

                //保存附加费
                $extraFaxService = new SupplierExtraFeeService();
                $extraFaxService->saveSupplierExtraFee($extraFax);
                //插入系数到redis
                $this->saveRatioToRedis($supplierId);
                //各种规则
                $this->saveSkuAuditRulerToRedis($supplierId, $channel['sku_audit_ruler']);
                $this->saveSkuUploadRulerToRedis($supplierId, $channel['sku_upload_ruler']);
                //判断是否要移出待跟进
                $this->updateIsFollowUp($supplierId);
                //保存标签到标签系统
                $oldCustomerTags = array_get($oldSupplier, 'customer_tags');
                $oldSystemTags = array_get($oldSupplier, 'system_tags');
                $tagService->saveTags(
                    $supplierId,
                    SupplierTagService::TAG_TYPE_SYSTEM,
                    $channel['system_tags'],
                    $oldSystemTags
                );
                $tagService->saveTags(
                    $supplierId,
                    SupplierTagService::TAG_TYPE_CUSTOMER,
                    $channel['customer_tags'],
                    $oldCustomerTags
                );
            }

            //新增供应商的话,还要去初始化有效期
            if (empty($channel['supplier_id'])) {
                //初始化有效期
                $this->initialCpTimeDays($supplierId, $channel['supplier_group']);
            }

            //重新生成外部显示的编码
            $this->generateSupplierSn($supplierId, $channel['supplier_group']);
            //保存和搜索相关的标签情况
            $supplierSearchTagService = new SupplierSearchTagService();
            $supplierSearchTagService->saveSupplierSearchTags($supplierId);
            //统一保存过期时间规则到redis
            $redis = new RedisModel();
            if (trim($channel['main_brands'], ',')) {
                $mainBrands = trim($channel['main_brands'], ',');
                $mainBrands = explode(',', $mainBrands);
                $mainBrands = array_map(function ($value) {
                    return (int)$value;
                }, $mainBrands);
                $supplierSkuCpTimeRuler = $redis->hget('supplier_sku_upload_ruler_v2', $supplierId);
                if ($supplierSkuCpTimeRuler) {
                    $supplierSkuCpTimeRuler = json_decode($supplierSkuCpTimeRuler, true);
                    $supplierSkuCpTimeRuler['upload_allow_brands'] = $mainBrands;
                } else {
                    $supplierSkuCpTimeRuler = ['upload_allow_brands' => $mainBrands];
                }
                $this->saveSkuCpTimeRulerToRedis($supplierId, $supplierSkuCpTimeRuler);
            }

            return $supplierId;
        });

        //保存日志
        $newSupplier = $model->where('supplier_id', $this->newSupplierId)->first();
        $newSupplier = $supplierTransformer->transformInfo($newSupplier);
        $logType = !empty($channel['supplier_id']) ? LogModel::UPDATE_OPERATE : LogModel::ADD_OPERATE;
        $logAction = !empty($channel['supplier_id']) ? "修改供应商基本资料" : "新增供应商";
        $logContent = !empty($channel['supplier_id']) ? '修改供应商' : '新增供应商基础信息' . ($isDirectApply ? '(直接申请审核)' : '(草稿)');
        //判断是不是申请重新入驻
        if (!empty($oldSupplier['status']) && $oldSupplier['status'] == -2) {
            $logAction = "申请重新入驻";
        }
        if (!empty($oldSupplier['status']) && $oldSupplier['status'] == -1) {
            $logType = 2;
            $logAction = '新增供应商';
            $logContent = '确认新增供应商';
        }

        //一体化新流程,如果是新建,新建完了以后还要去请求一次验证实体名单的接口,因为只有新建完才有具体的地址source_id这些东西,为什么不放到数据库事务里面,因为校验完
        //但是供应商还没有插入db的时候,可能会提前广播到,导致没法操作供应商的状态(因为供应商都还没有生成)
        if (empty($channel['supplier_id'])) {
            (new CompanyService())->checkSupplierCompanyAndAddress($supplierId);
        }

        $contentChange = true;
        //过滤掉没有修改的操作,但是需要记录一条更新记录(用于判断是否可以审核)
        if (!empty($oldSupplier) && !empty($newSupplier)) {
            $oldSupplier = $oldSupplier->toArray();
            $newSupplier = $newSupplier->toArray();
            unset($oldSupplier['update_time']);
            unset($newSupplier['update_time']);
            if ($oldSupplier == $newSupplier) {
                $contentChange = false;
                $logService->AddLog($this->newSupplierId, LogModel::UPDATE_OPERATE, '修改供应商基本资料', '没有内容变化');
            }
        }

        if ($contentChange) {
            $logService->AddLog($this->newSupplierId, $logType, $logAction, $logContent, json_encode([
                'old_supplier' => $oldSupplier,
                'new_supplier' => $newSupplier
            ]));
        }

        $isAudit = (bool)request()->input('is_audit');

        //这里还要判断一体化实体名单,如果是待确认,那么也不能修改状态为审核中
        //新增的时候,一体化是待确认
        if ($newSupplier['is_entity'] == 0) {
            //这里还涉及到一体化的状态变更,要去判断is_entity字段
            //如果是0的话,那么就要去禁用,并且记录禁用前的原始状态
            $reason = '待确认实体名单,系统自动拉入禁止交易,请联系“运营合规部门”进行确认;';
            // 禁用供应商
            SupplierChannelModel::where('supplier_id', $supplierId)->update([
                'update_time' => time(),
                'disable_reason' => $reason,
                'status' => SupplierChannelModel::STATUS_DISABLE,
            ]);
            $logService = new LogService();
            $logService->AddLog($this->newSupplierId, LogModel::UPDATE_OPERATE, '实体名单设置', $reason);
            // 记录禁用前的原始状态
            $redis = new RedisModel();
            $redis->hset('supplier_status_before_disable', $supplierId, $newSupplier['status']);
        }

        //这里有个申请审核的判断逻辑
        //如果是申请审核,并且原来的状态不是已通过,无论什么情况,都要变成审核中,如果是已通过,那么就要走下面的判断是否要忽略审核流程
        if ($isAudit && $oldSupplier['status'] == SupplierChannelModel::STATUS_PASSED && !$needAudit && !empty($channel['supplier_id'])) {
            //什么都不需要操作
        } else if ($isAudit && $newSupplier['is_entity'] != 0) {
            $auditData[] = [
                'supplier_id' => $supplierId,
                //供应商类型为临时供应商,才会去存申请理由
                'apply_audit_reason' => $channel['supplier_type'] == 2 ? request()->input('apply_audit_reason') : '',
            ];
            $this->batchApplyInReviewSupplier($auditData);
        }
        return $supplierId;
    }


    //生成供应商编码(外部用,展示用),supplierCode是供应商的核心编码,内部使用,可以理解为唯一标识
    public function generateSupplierSn($supplierId, $supplierGroup)
    {
        $model = new SupplierChannelModel();
        $supplier = $model->where('supplier_id', $supplierId)->first()->toArray();
        $snMap = config('fixed.SupplierSnMap');
        $supplierCodeNumber = substr($supplier['supplier_code'], 1);
        $supplierSn = array_get($snMap, $supplierGroup, "ERR") . $supplierCodeNumber;
        $model->where('supplier_id', $supplierId)->update(['supplier_sn' => $supplierSn]);
    }

    //保存价格系数到redis
    public function saveRatioToRedis($supplierId)
    {
        $model = new SupplierChannelModel();
        $supplier = $model->where('supplier_id', $supplierId)->first()->toArray();
        $Redis = new RedisModel();
        $pre = config('fixed.SUPPLIER_RATION');
        $data = array_only($supplier, ['cn_delivery_time', 'us_delivery_time', 'cn_ratio', 'us_ratio', 'supplier_id']);
        $data['supplier_id'] = strval($data['supplier_id']);
        $Redis->hset($pre, $supplier['supplier_code'], json_encode($data));
    }

    //报错供应商编码,包括系统生成的和自定义规则生成的
    public function saveSupplierCode($supplierId)
    {
        $model = new SupplierChannelModel();
        $supplier = $model->where('supplier_id', $supplierId)->first();
        if (!empty($supplier)) {
            $supplierCode = 'L' . str_pad($supplierId, 7, "0", STR_PAD_LEFT);
            return $model->where('supplier_id', $supplierId)->update([
                'supplier_code' => $supplierCode,
            ]);
        } else {
            return false;
        }
    }

    public function saveSkuAuditRulerToRedis($supplierId, $ruler)
    {
        $redis = new RedisModel();
        $redis->hset('supplier_sku_audit_ruler', $supplierId, $ruler);
    }


    public function saveSkuUploadRulerToRedis($supplierId, $ruler)
    {
        $redis = new RedisModel();
        $redis->hset('supplier_sku_upload_ruler', $supplierId, $ruler);
    }

    public function saveSkuCpTimeRulerToRedis($supplierId, $ruler)
    {
        if (is_array($ruler)) {
            $ruler = json_encode($ruler);
        }
        $redis = new RedisModel();
        $redis->hset('supplier_sku_upload_ruler_v2', $supplierId, $ruler);
    }

    //初始化过期天数限制
    public function initialCpTimeDays($supplierId, $supplierGroup)
    {
        $cpTimeDay = 7;
        $futuresCpTimeDay = 365;
        if ($supplierGroup == SupplierChannelModel::SUPPLIER_GROUP_ORIGINAL) {
            $futuresCpTimeDay = $cpTimeDay = -1;
        }
        SupplierChannelModel::where('supplier_id', $supplierId)->update([
            'cp_time_day' => $cpTimeDay,
            'futures_cp_time_day' => $futuresCpTimeDay,
        ]);
        $redis = new RedisModel();
        $ruler = $redis->hget('supplier_sku_upload_ruler_v2', $supplierId);
        if ($ruler) {
            $ruler = json_decode($ruler, true);
        }
        $ruler['upload_validity_period'] = $cpTimeDay;
        $ruler['upload_futures_goods_validity_period'] = $futuresCpTimeDay;
        $ruler = json_encode($ruler);
        $redis->hset('supplier_sku_upload_ruler_v2', $supplierId, $ruler);
    }


    public function getAddress($supplierId)
    {
        $model = new SupplierAddressModel();
        $address = $model->where('supplier_id', $supplierId)->limit(2)->get();
        $data = [
            'shipping_address' => '',
            'return_address' => '',
            'return_consignee' => '',
            'return_phone' => '',
        ];
        if ($address) {
            $address = $address->toArray();
            //区分发货还是退货,1是发货,2是退货
            foreach ($address as $key => $item) {
                if ($item['address_type'] == 1) {
                    $data['shipping_address'] = $item['address'];
                } else {
                    $data['return_address'] = $item['address'];
                    $data['return_consignee'] = $item['consignee'];
                    $data['return_phone'] = $item['phone'];
                }
            }
            return $data;
        }
        return [];
    }

    //分配开发员
    public function allocatePurchaseUser($supplierId, $purchaseUid)
    {
        $result = DB::connection('web')->transaction(function () use ($supplierId, $purchaseUid) {
            $model = new SupplierChannelModel();
            $supplier = $model->where('supplier_id', $supplierId)->first();
            $supplier = $supplier ? $supplier->toArray() : [];
            $prePurchaseUid = $supplier['purchase_uid'];
            $result = $model->where('supplier_id', $supplierId)->update([
                'update_time' => time(),
                'purchase_uid' => $purchaseUid,
            ]);
            if ($result) {
                //重新分配渠道开发并且开发人员有变更的时候,就去检查是否需要跟进
                if ($supplier['purchase_uid'] != $purchaseUid) {
                    $auditService = new SupplierAuditService();
                    //还要判断是否为待跟进供应商
                    if ($auditService->checkIsNeedToFollowUpSupplier($supplierId)) {
                        $model->where('supplier_id', $supplierId)->update([
                            'to_follow_up' => 1,
                        ]);
                    }
                    //判断是否是非正式供应商,如果是,自动转正,并且修改为待提审状态
                    $this->autoChangeIsType($supplier);
                }

                //还要去记录日志
                $adminUserService = new AdminUserService();
                $prePurchaseUser = $adminUserService->getAdminUserInfoByCodeId($prePurchaseUid);
                $prePurchaseUserName = array_get($prePurchaseUser, 'name', ' ');
                $purchaseUser = $adminUserService->getAdminUserInfoByCodeId($purchaseUid);
                $purchaseUserName = array_get($purchaseUser, 'name', '');
                $logService = new LogService();
                $content = "将渠道开发员由 [${prePurchaseUserName}] 改为 [${purchaseUserName}]";
                $logService->AddIgnoreAuditCheckLog($supplierId, LogModel::UPDATE_OPERATE, '分配渠道开发员', $content);
            }
        });

        return $result;
    }

    //分配开发员
    public function batchAllocatePurchaseUser($supplierIds, $purchaseUid)
    {
        foreach ($supplierIds as $supplierId) {
            $this->allocatePurchaseUser($supplierId, $purchaseUid);
        }
        return true;
    }

    //批量分配线上采购员
    public function batchAllocateYunxinChannelUser($supplierIds, $yunxinChannelUid)
    {
        $yunxinChannelUserName = (new AdminUserService())->getAdminUserNameByCodeId($yunxinChannelUid);
        $logService = new LogService();
        $redis = new RedisModel();
        foreach ($supplierIds as $supplierId) {
            $supplier = SupplierChannelModel::where('supplier_id', $supplierId)->select(['supplier_code', 'yunxin_channel_uid'])
                ->first()->toArray();
            $preYunxinChannelUid = $supplier['yunxin_channel_uid'];
            SupplierChannelModel::where('supplier_id', $supplierId)->update([
                'yunxin_channel_uid' => $yunxinChannelUid
            ]);
            //去查找数据对接系统是否有这个供应商,有的话,把采购员也改成这个
            DataManageModel::where('canal', $supplier['supplier_code'])->update([
                'pur_uid' => $yunxinChannelUid,
                'update_time' => time(),
            ]);
            $supplier = SupplierChannelModel::where('supplier_id', $supplierId)->first()->toArray();
            //还要丢队列给批量修改sku的内部编码
            $redisKey = 'lie_supplier_change_yunxin_user_' . $supplierId;
            if ($redis->get($redisKey)) {
                $data = [
                    'canal' => $supplier['supplier_code'],
                    "encoded" => $yunxinChannelUid,
                ];
                //改成队列
                (new SkuService())->batchUpdateEncodedQueue($data);
                $redis->set($redisKey, 1);
                $redis->expire($redisKey, 60 * 60 * 3);
            }
            $preYunxinChannelUserName = (new AdminUserService())->getAdminUserNameByCodeId($preYunxinChannelUid);
            $content = "将线上采购员由 [${preYunxinChannelUserName}] 改为 [${yunxinChannelUserName}]";
            $logService->AddIgnoreAuditCheckLog($supplierId, LogModel::UPDATE_OPERATE, '分配渠道开发员', $content);
        }
        return true;
    }

    //检测是否可以批量分配线上采购员(分配的采购员必须供应商要有的)
    //$filterChannelUid筛选出来的采购员ID
    public function checkCanAllocatYunxinChannelUid($supplierIds, $skuChannelUid)
    {
        foreach ($supplierIds as $supplierId) {
            $channelUid = SupplierChannelModel::where('supplier_id', $supplierId)->value('channel_uid');
            if (empty($channelUid)) {
                return false;
            }
            $channelUid = explode(',', trim($channelUid, ','));
            if (!in_array($skuChannelUid, $channelUid)) {
                return false;
            }
        }
        return true;
    }

    //分配采购员
    public function allocateChannelUser($supplierId, $channelUid, $needLog = true)
    {
        $supplier = SupplierChannelModel::where('supplier_id', $supplierId)->first();
        if (empty($supplier)) {
            return true;
        }
        $supplier = $supplier->toArray();
        $preChannelUid = explode(',', $supplier['channel_uid']);
        //如果之前已经存在对应的采购,直接返回
        if (in_array($channelUid, $preChannelUid)) {
            return true;
        }
        $result = DB::connection('web')->transaction(function () use ($supplierId, $channelUid, $needLog) {
            $supplier = SupplierChannelModel::where('supplier_id', $supplierId)->first();
            $supplier = $supplier ? $supplier->toArray() : [];
            $preChannelUid = $supplier['channel_uid'];
            $preChannelUid = explode(',', $preChannelUid);
            $preChannelUid[] = $channelUid;
            $preChannelUid = array_unique($preChannelUid);
            $preChannelUid = implode(',', $preChannelUid);
            $preChannelUid = trim($preChannelUid, ',');
            if ($needLog) {
                $data = [
                    'update_time' => time(),
                    'channel_uid' => $preChannelUid,
                ];
                $result = SupplierChannelModel::where('supplier_id', $supplierId)->update($data);
            } else {
                $result = SupplierChannelModel::where('supplier_id', $supplierId)->update([
                    'channel_uid' => $preChannelUid,
                ]);
            }


            $contactResult = false;
            if ($result) {
                $contactModel = new SupplierContactModel();
                $contact = [
                    'supplier_id' => $supplierId,
                    'can_check_uids' => $channelUid,
                    'add_time' => time(),
                    'admin_id' => !empty(request()->user->userId) ? request()->user->userId : 1000,
                ];
                $contactResult = $contactModel->insert($contact);
            }
            if ($contactResult && $needLog) {
                //判断是否是非正式(is_type=1)供应商,如果是,自动转正,并且修改为待提审状态
                $this->autoChangeIsType($supplier);
                //记录日志
                $adminUserService = new AdminUserService();
                $channelUser = $adminUserService->getAdminUserInfoByCodeId($channelUid);
                $channelUserName = array_get($channelUser, 'name', ' ');
                $logService = new LogService();
                $content = "添加采购员 : " . $channelUserName;
                $logService->AddIgnoreAuditCheckLog($supplierId, LogModel::UPDATE_OPERATE, '添加采购员', $content);
            }
            return $contactResult;
        });
        $syncService = new SyncSupplierService();
        $syncService->syncSupplierToErp($supplierId);
        return $result;
    }

    //判断并且修改待跟进
    private function updateIsFollowUp($supplierId)
    {
        $model = new SupplierChannelModel();
        $auditService = new SupplierAuditService();
        //还要判断是否为待跟进供应商
        if ($auditService->checkIsNeedToFollowUpSupplier($supplierId)) {
            $model->where('supplier_id', $supplierId)->update([
                'to_follow_up' => 1,
            ]);
        } else {
            $model->where('supplier_id', $supplierId)->update([
                'to_follow_up' => 0,
            ]);
        }
    }

    //修改is_type
    public function changeSupplierIsType($supplierId, $isType)
    {
        $model = new SupplierChannelModel();
        $data = [
            'supplier_type' => 1,
            'update_time' => time(),
            'is_type' => $isType,
            'status' => SupplierChannelModel::STATUS_PENDING,
        ];
        $createTime = $model->where('supplier_id', $supplierId)->value('create_time');
        if (!$createTime) {
            $data['create_time'] = time();
        }
        $result = $model->where('supplier_id', $supplierId)->update($data);
        if ($result) {
            $logService = new LogService();
            $content = '转正供应商';
            $logService->AddLog($supplierId, LogModel::UPDATE_OPERATE, '转正供应商', $content);
        }
        return $result;
    }

    //获取打印需要的数据
    public function getSupplierPrintData($supplierId)
    {
        $supplierModel = new SupplierChannelModel();
        $supplier = $supplierModel->where('supplier_id', $supplierId)->first()->toArray();
        $transformer = new SupplierTransformer();
        $supplier = $transformer->transformInfo($supplier);
        $printData = $supplier;
        $printData['apply_name'] = request()->user->name;
        $printData['apply_time'] = date('Y-m-d H:i:s', time());
        $contactService = new SupplierContactService();
        $contact = $contactService->getContactForPrint($supplierId);
        $printData['contact'] = $contact;
        $attachmentModel = new SupplierAttachmentsModel();
        $hasAgreement = $attachmentModel->where('supplier_id', $supplierId)
            ->where('field_name', 'quality_assurance_agreement')->exists() ? '已签' : '未签';
        $printData['has_agreement'] = $hasAgreement;
        $adminUserService = new AdminUserService();
        $user = $adminUserService->getAdminUserInfo(request()->user->userId);
        $printData['department_name'] = $user['department_name'];
        return $printData;
    }

    //批量申请审核供应商
    public function batchApplyInReviewSupplier($auditData = [])
    {
        $model = new SupplierChannelModel();
        foreach ($auditData as $data) {
            $result = $model->where('supplier_id', $data['supplier_id'])->update([
                'update_time' => time(),
                'apply_audit_reason' => $data['apply_audit_reason'],
                'status' => SupplierChannelModel::STATUS_IN_REVIEW
            ]);
            if (!$result) {
                return $result;
            }
        }
        return true;
    }

    //判断是否自动转正,并且还要修改为待提审状态给相关人员进行补充资料
    public function autoChangeIsType($supplier)
    {
        if ($supplier['is_type'] == 1) {
            $model = new SupplierChannelModel();
            $model->where('supplier_id', $supplier['supplier_id'])->update([
                'update_time' => time(),
                'status' => SupplierChannelModel::STATUS_PENDING,
                'is_type' => 0
            ]);
        }
    }

    //搜索供应商
    public static function searchSupplier($params)
    {
        $filter = new SupplierFilter();
        $limit = array_get($params, 'limit', 10);
        $query = SupplierChannelModel::with('pay_type')->select([
            'supplier_id',
            'supplier_code',
            'supplier_name',
            'pay_type',
            'channel_uid'
        ]);
        $query = $filter->listFilter($params, $query);
        $suppliers = $query->paginate($limit);
        $suppliers = $suppliers->toArray();
        $suppliers['data'] = SupplierTransformer::transformSearch($suppliers['data']);
        return $suppliers;
    }

    //校验供应商是否必填都完整了
    public static function checkSupplierFieldCompleted($supplierId)
    {
        $supplier = SupplierChannelModel::where('supplier_id', $supplierId)->first()->toArray();
        //要将部分字段从0改成'',要不然表单验证会有问题
        $needChangeField = [
            'pay_type',
            'currency',
            'supplier_group',
            'supplier_type',
            'settlement_type',
        ];
        foreach ($supplier as $key => &$value) {
            if (in_array($key, $needChangeField) && empty($value)) {
                $value = '';
            }
        }
        unset($value);
        $validator = new SupplierValidator();
        return $validator->checkSave($supplier, true);
    }

    //检验供应商是否有设置对应的阶梯价格系数
    public static function checkHasLadderPriceSetting($supplierId)
    {
        $supplierCode = SupplierChannelModel::where('supplier_id', $supplierId)->value('supplier_code');
        $redis = new RedisModel();
        $rule = $redis->hget('magic_cube_price_rule_v2', $supplierCode);
        return (bool)$rule;
    }

    //检查是否有查看权限
    public function checkCanViewSupplier($supplierId)
    {
        $map = [
            'supplier_id' => $supplierId,
            'source_type' => 'all'
        ];
        $list = $this->getSupplierList($map);
        return (bool)$list['total'];
    }


    //导出供应商
    public function exportSupplier()
    {
        $params['is_export'] = 1;
        $params['source_type'] = 'all_channel_user_resigned';
        $list = $this->getSupplierList($params);
        foreach ($list as &$supplier) {
            $supplier['channel_username'] = (new SupplierTransformer())->getChannelUserNames($supplier['channel_uid']);
        }
        unset($supplier);
        $csvData = [];
        foreach ($list as $supplier) {
            $item = [
                $supplier['supplier_code'],
                $supplier['supplier_name'],
                $supplier['channel_username'],
            ];
            $csvData[] = $item;
        }
        $header = [
            '供应商编码',
            '供应商名称',
            '采购员',
        ];
        exportCsv($csvData, '导出供应商列表', $header);
    }

    //查询供应商
    public function querySupplier($supplierName)
    {
        $supplier = SupplierChannelModel::where('supplier_name', $supplierName)->first();
        $supplier = !empty($supplier) ? $supplier->toArray() : [];
        if ($supplier) {
            //查询是否是芯链商家
            $existsYunxinAccount = SupplierAccountModel::where('supplier_id', $supplier['supplier_id'])->exists();
            $supplier['is_yunxin_supplier'] = $existsYunxinAccount ? 1 : 0;
        }
        return $supplier;
    }

    public function getInitSkuUploadRuler()
    {
        return '{"allow_stock_lte_0":0,"allow_moq_lte_0":0,"allow_stock_lt_moq":0,"allow_price_null":0,"futures_allow_stock_lte_0":1,"futures_allow_moq_lte_0":0,"futures_allow_price_null":1}';
    }

    //修改供应商名称
    public function changeSupplierName($supplierId, $supplierName)
    {
        $supplier = SupplierChannelModel::where('supplier_id', $supplierId)->first()->toArray();
        $originSupplierName = $supplier['supplier_name'];
        //修改名称,修改后要重新提交数据给一体化那边进行审核
        $businessLicense = SupplierAttachmentsModel::where('supplier_id', $supplierId)
            ->where('field_name', 'business_license')->value('file_url');
        //如果是非大陆的供应商,那么商业登记证的优先级大于营业执照
        if ($supplier['region'] != SupplierChannelModel::REGION_CN) {
            $registrationCertificate = SupplierAttachmentsModel::where('supplier_id', $supplierId)
                ->where('field_name', 'registration_certificate')->value('file_url');
            if ($registrationCertificate) {
                $businessLicense = $registrationCertificate;
            }
        }
        $signComName = array_get(CrmService::getSignCompanyListMap(), $supplier['sign_com_id']);
        $checkCompanyEntity = (new CompanyService())->checkCompanyEntity($supplierName, $supplier['supplier_name_en'], $supplier['supplier_address'], $businessLicense, $signComName);
        //还要去检测是否是一体化黑名单
        //新增的时候要先去检验下一体化的数据,如果是实体黑名单用户,那么就不允许新增
        //还要校验提交上来的公司是否有合法信息
        if ($checkCompanyEntity == -1) {
            return ('该供应商为实体名单,不允许修改');
        }

        if ($checkCompanyEntity == -2) {
            return ('该供应商为黑名单,不允许修改');
        }

        if ($checkCompanyEntity == -3) {
            return ('该供应商被驳回,不允许修改');
        }
        //都通过以后,可以先修改名称,然后等一体化那边审核通过
        SupplierChannelModel::where('supplier_id', $supplierId)->update([
            'is_entity' => SupplierChannelModel::IS_ENTITY_NEED_CONFIRM,
            'supplier_name' => $supplierName,
            'update_time' => time(),
        ]);

        //打日志
        $logService = new LogService();
        $content = '修改供应商名称';
        $msg = '供应商名称手动修改,由[ ' . $originSupplierName . ' ]修改成[ ' . $supplierName . ' ],等待一体化审核';
        $logService->AddLog($supplierId, LogModel::UPDATE_OPERATE, $content, $msg);
        return true;
    }

    //获取供应商编码给xm-select使用
    public static function getSupplierCodeListForXmSelect()
    {
        $supplierList = SupplierChannelModel::where('status', '!=', SupplierChannelModel::STATUS_DISABLE)
            ->select(['supplier_code', 'supplier_name', 'supplier_id'])->get()->toArray();

        $data = [];
        foreach ($supplierList as $supplier) {
            $data[] = [
                'name' => "{$supplier['supplier_name']} ( {$supplier['supplier_code']} )",
                'value' => $supplier['supplier_code'],
            ];
        }
        return $data;
    }

    //获取供应商id给xm-select使用
    public static function getSupplierIdListForXmSelect()
    {
        $supplierList = SupplierChannelModel::where('status', '!=', SupplierChannelModel::STATUS_DISABLE)
            ->select(['supplier_id', 'supplier_name', 'supplier_code'])->get()->toArray();

        $data = [];
        foreach ($supplierList as $supplier) {
            $data[] = [
                'name' => "{$supplier['supplier_name']} ( {$supplier['supplier_code']} )",
                'value' => $supplier['supplier_id'],
            ];
        }
        return $data;
    }
}