<?php


namespace App\Http\Services;

use App\Http\Transformers\SupplierTransformer;
use App\Model\LogModel;
use App\Model\RedisModel;
use App\Model\SupplierAddressModel;
use App\Model\SupplierChannelModel;
use App\Model\SupplierContactModel;
use Illuminate\Support\Facades\DB;

class SupplierService
{

    public $newSupplierId = 0;

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

    //生成供应商编码(外部用,展示用),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);
        return array_get($snMap, $supplierGroup, "ERR") . $supplierCodeNumber;
    }

    //保存价格系数到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 saveSupplier($channel)
    {
        //先处理下数据
        if (!empty($channel['stockup_type'])) {
            $stockupType = array_keys($channel['stockup_type']);
            $stockupType = !empty($stockupType) ? implode(",", $stockupType) : '';
            $channel['stockup_type'] = $stockupType;
        }
        if (!empty($channel['currency'])) {
            if ($channel['currency'] != 1) {
                $channel['tax_number'] = '';
            }
        }
        if (empty($channel['purchase_uid'])) {
            unset($channel['purchase_uid']);
        }

        $channel['cn_ratio'] = empty($channel['cn_ratio']) ? 1 : $channel['cn_ratio'];
        $channel['us_ratio'] = empty($channel['us_ratio']) ? 1 : $channel['us_ratio'];

        $channel['cn_delivery_time'] = $channel['cn_delivery_time'] . $channel['cn_delivery_time_period'];
        $channel['us_delivery_time'] = $channel['us_delivery_time'] . $channel['us_delivery_time_period'];
        $channel['qualification_photos'] = $this->getPhotosData($channel['upload_file']);
        unset($channel['upload_file']);
        $channel['established_time'] = strtotime($channel['established_time']);
        $skuUploadRulerService = new SupplierSkuUploadRulerService();
        $channel['sku_upload_ruler'] = $skuUploadRulerService->getSkuUploadRulerForDB($channel['sku_upload_ruler']);
        $logService = new LogService();
        $model = new SupplierChannelModel();

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

        //走事务
        $dataResult = DB::connection('web')->transaction(function () use ($channel) {
            $model = new SupplierChannelModel();
            $extraFax = [
                'supplier_id' => $channel['supplier_id'],
                'supplier_code' => $channel['supplier_code'],
                'hk' => $channel['hk'],
                'cn' => $channel['cn'],
            ];
            $address = array_only($channel,
                ['supplier_id', 'shipping_address', 'return_address', 'return_consignee', 'return_phone']);
            //插入
            unset($channel['hk'], $channel['cn'], $channel['return_phone'], $channel['return_address'],
                $channel['return_consignee'], $channel['shipping_address'], $channel['cn_delivery_time_period'], $channel['us_delivery_time_period']);
            $skuAuditRulerService = new SupplierSkuAuditRulerService();
            $channel['sku_audit_ruler'] = $skuAuditRulerService->getSkuAuditRulerForDB($channel['sku_audit_ruler']);
            if (empty($channel['supplier_id'])) {
                //先去插入到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);
                $channel['status'] = SupplierChannelModel::STATUS_PENDING;
                $supplierId = $this->newSupplierId = $model->insertGetId($channel);
                $this->saveSupplierCode($supplierId);
            } else {
                $supplierId = $this->newSupplierId = $channel['supplier_id'];
                $channel['status'] = SupplierChannelModel::STATUS_IN_REVIEW;
                $channel['update_time'] = time();
                $model->where('supplier_id', $supplierId)->update($channel);
                $this->saveSupplierCode($supplierId);
                //插入系数到redis
                $supplierAddressService = new SupplierAddressService();
                $supplierAddressService->saveAddress($address);
                $extraFaxService = new SupplierExtraFeeService();
                $extraFaxService->saveSupplierExtraFee($extraFax);

                $this->saveRatioToRedis($supplierId);
                $this->saveSkuAuditRulerToRedis($supplierId, $channel['sku_audit_ruler']);
                $this->saveSkuUploadRulerToRedis($supplierId, $channel['sku_upload_ruler']);
            }
            //重新生成外部显示的编码
            $supplierSn = $this->generateSupplierSn($supplierId, $channel['supplier_group']);
            //修改数据
            $model->where('supplier_id', $supplierId)->update(['supplier_sn' => $supplierSn]);
            return true;
        });

        //保存日志
        $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']) ? '修改供应商' : '新增供应商';
        //判断是不是申请入驻
        if (!empty($oldSupplier['status']) && $oldSupplier['status'] === -2) {
            $logAction = "申请重新入驻";
        }
        $logService->AddLog($this->newSupplierId, $logType, $logAction, $logContent, json_encode([
            'old_supplier' => $oldSupplier,
            'new_supplier' => $newSupplier
        ]));
        return $dataResult;
    }

    public function getPhotosData($uploadFiles)
    {
        $data = [];
        foreach ($uploadFiles as $name => $file) {
            if (empty($file)) {
                $data[$name] = [
                    'name' => $name,
                    'url' => '',
                    'file_name' => ''
                ];
            } else {
                $file = explode('|_|', $file);
                $data[$name] = [
                    'name' => $name,
                    'url' => $file[0],
                    'file_name' => $file[1],
                ];
            }
        }
        $data = json_encode($data);
        return $data;
    }

    public function getSkuRulerData($skuUploadRuler)
    {
        $defaultRuler = config('fixed.SkuUploadRuler');
        $rule = [];
        foreach ($defaultRuler as $ruleName => $value) {
            if (isset($skuUploadRuler[$ruleName])) {
                $rule[$ruleName] = 1;
            } else {
                $rule[$ruleName] = 0;
            }
        }
        $rule = json_encode($rule);
        return $rule;
    }

    //报错供应商编码,包括系统生成的和自定义规则生成的
    private function saveSupplierCode($supplierId)
    {
        $model = new SupplierChannelModel();
        $supplier = $model->where('supplier_id', $supplierId)->first();
        if (!empty($supplier)) {
            $supplier = $supplier->toArray();
            $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 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)
    {
        $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,
                    ]);
                }
            }

            //还要去记录日志
            $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->AddLog($supplierId, LogModel::UPDATE_OPERATE, '分配渠道开发员', $content);

        }
        return $result;
    }

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