<?php

namespace App\Http\Services;

//后台用户相关信息服务
use App\Http\Transformers\SupplierContactTransformer;
use App\Http\Transformers\SupplierTransformer;
use App\Model\IntracodeModel;
use App\Model\LogModel;
use App\Model\RedisModel;
use App\Model\StandardBrandModel;
use App\Model\SupplierAttachmentModel;
use App\Model\SupplierChannelModel;
use App\Model\SupplierContactModel;
use App\Model\SupplierPayTypeModel;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

//这个服务是处理数据的,比如导出信息,或者临时修复数据,所以代码会比较多
class DataService
{

    public function initSystemTag()
    {

        $tagList = [
//            1 => '临时供应商',
//            2 => '优质供应商',
//            3 => '客户指定供应商',
//            4 => '开票不及时',
//            5 => '跳票',
            '见票见货后付款供应商',

        ];

        $client = new Client([
            'base_uri' => config('website.TagUrl'),
        ]);

        foreach ($tagList as $tag) {
            //构建请求参数
            $params = [
                $tag => [
                    'tag_use' => 14,
                    'tag_type' => 2,
                    'remark' => '',
                    'creator' => 1000,
                    'creator_name' => 'admin',
                    'status' => 1,
                ]
            ];
            $response = $client->post('/create', [
                RequestOptions::JSON => $params,
            ]);
            var_dump($response->getBody()->getContents());
        }
    }

    //20210722
    //转移文件数据(之前是只存到一个字段,现在要存到一张表里面去)
    public function transferFileData()
    {
        //先找出所有上传文件非空的供应商
        $model = new SupplierChannelModel();
        $suppliers = $model->where('qualification_photos', '!=', '')->get()->toArray();
        $attachmentModel = new SupplierAttachmentModel();
        foreach ($suppliers as $key => $supplier) {
            $supplierId = $supplier['supplier_id'];
            $files = json_decode($supplier['qualification_photos'], true);
            $count = $attachmentModel->where('supplier_id', $supplierId)->count();
            if (!$count) {
                foreach ($files as $key => &$file) {
                    if (empty($file['url']) && empty($file['file_name'])) {
                        $file = '';
                    }
                }
                unset($file);
                $business_license = array_get($files, 'business_license');
                $billing_information = array_get($files, 'billing_information');
                $registration_certificate = array_get($files, 'registration_certificate');
                $incorporation_certificate = array_get($files, 'incorporation_certificate');
                $certification_notice = array_get($files, 'certification_notice');
                $supplier_survey = array_get($files, 'supplier_survey');
                $proxy_certificate = array_get($files, 'proxy_certificate');
                $quality_assurance_agreement = array_get($files, 'quality_assurance_agreement');
                $confidentiality_agreement = array_get($files, 'confidentiality_agreement');
                $cooperation_agreement = array_get($files, 'cooperation_agreement');
                $other_attachment = array_get($files, 'other_attachment');
                $attachment = [
                    'business_license' => $business_license ? [$business_license] : '',
                    'billing_information' => $billing_information ? [$billing_information] : '',
                    'registration_certificate' => $registration_certificate ? [$registration_certificate] : '',
                    'incorporation_certificate' => $incorporation_certificate ? [$incorporation_certificate] : '',
                    'certification_notice' => $certification_notice ? [$certification_notice] : '',
                    'supplier_survey' => $supplier_survey ? [$supplier_survey] : '',
                    'proxy_certificate' => $proxy_certificate ? [$proxy_certificate] : '',
                    'quality_assurance_agreement' => $quality_assurance_agreement ? [$quality_assurance_agreement] : '',
                    'confidentiality_agreement' => $confidentiality_agreement ? [$confidentiality_agreement] : '',
                    'cooperation_agreement' => $cooperation_agreement ? [$cooperation_agreement] : '',
                    'other_attachment' => $other_attachment ? [$other_attachment] : '',
                    'create_time' => time(),
                    'update_time' => time(),
                    'supplier_id' => $supplierId,
                ];
                $attachment = array_filter($attachment, function ($item) {
                    return !empty($item);
                });
                $attachment = array_map(function ($item) {
                    return json_encode($item);
                }, $attachment);
                $attachmentModel->insert($attachment);
            }
        }
    }

    //历史数据处理
    public function changeSupplierIsTypeByCheckChannelUidOrPurchaseUid()
    {
        $model = new SupplierChannelModel();
        $suppliers = $model->where(function ($q) {
            $q->where('channel_uid', '!=', '')->orWhere('purchase_uid', '!=', '');
        })->where('is_type', 1)->get()->toArray();
//        dd(count($suppliers));
        if (count($suppliers) > 1670) {
            dd("数量有问题");
        }
        $redis = new RedisModel();
        //非正式供应商中存在渠道员/采购员,将供应商改为正式供应商
        foreach ($suppliers as $supplier) {
            //先查询是否有重复的供应商
            $count = $model->where('supplier_name', $supplier['supplier_name'])->count();
            if ($count > 1) {
                dd($supplier['supplier_name']);
                continue;
            }
            //同时记录被修改的supplier_id列表到redis以防万一
            $redis->hset('lie_change_is_type_suppliers', $supplier['supplier_id'], json_encode($supplier));
            //没有的话直接修改成待审核,并且转正
            $model->where('supplier_id', $supplier['supplier_id'])
                ->update([
//                    'update_time' => time(),
                    'is_type' => 0,
                    'status' => 0
                ]);
        }
    }

    //替换老的品牌选择成为新的标准品牌id
    public function replaceStandardBrandId()
    {
        $supplierModel = new SupplierChannelModel();
        $suppliers = $supplierModel->where('main_brands', '!=', '')->get()->toArray();
        $redis = new RedisModel();
        foreach ($suppliers as $supplier) {
            $mainBrands = explode(',', $supplier['main_brands']);
            $standardBrandIds = [];
            foreach ($mainBrands as $brandId) {
                //找标准品牌ID,没有直接跳过
                $standardBrandId = $redis->hget('standard_brand_mapping', $brandId);
                if (empty($standardBrandId) or empty($brandId)) {
                    continue;
                }
                $standardBrandIds[] = $standardBrandId;
            }
            print_r($mainBrands);
            print_r($standardBrandIds);
            echo PHP_EOL;
            if (!empty($standardBrandIds)) {
                $standardBrandIdsStr = implode(',', $standardBrandIds);
            } else {
                $standardBrandIdsStr = '';
            }
            $supplierModel->where('supplier_id', $supplier['supplier_id'])->update([
                'main_brands' => $standardBrandIdsStr
            ]);

        }
    }

    //导入黑名单供应商(前提是不存在)
    public function importBlockSupplier()
    {
        $supplierNames = [
            'Electronics Depot',
            'Assured Electronics Corp.',
            '深圳市力特电子有限公司',
            '深圳市铭盛微电子科技有限公司',
            'Aegis Components Inc',
            '深圳市亿博创电子公司',
        ];
        //构建插入数据
        $supplierModel = new SupplierChannelModel();
        foreach ($supplierNames as $supplierName) {
            $supplierName = trim($supplierName);
            $exist = $supplierModel->where('supplier_name', $supplierName)->count();
            if (!$exist) {
                $insertData = [
                    'supplier_name' => $supplierName,
                    'create_uid' => 1000,
                    'create_time' => time(),
                    'status' => $supplierModel::STATUS_BLOCK,
                    'is_type' => 0,
                    'create_name' => 'admin',
                    'block_reason' => '系统拉黑',
                ];
                $supplierId = $supplierModel->insertGetId($insertData);
                $supplierService = new SupplierService();
                $supplierService->saveSupplierCode($supplierId);
            }
        }
    }

    //给特定类型的供应商打上标签
    //找出 国内/港台 + 现货商性质的,而且没有上传品质协议的供应商,自动打上临时供应商标签
    public function makeSupplierSystemTag()
    {
        $channelModel = new SupplierChannelModel();
        $suppliers = $channelModel->leftjoin('supplier_attachment', 'supplier_channel.supplier_id', '=',
            'supplier_attachment.supplier_id')
            ->whereIn('region', [2, 4])
            ->where('supplier_group', 2)
            ->where('quality_assurance_agreement', '')->where('system_tags', 'not like', '%临时供应商%')
            ->get()->toArray();
        $tagService = new SupplierTagService();
        //找到后打上标签
        foreach ($suppliers as $supplier) {
            $supplierId = $supplier['supplier_id'];
            $oldTags = $supplier['system_tags'];
            $newTags = $supplier['system_tags'] ? rtrim($supplier['system_tags'], ',') . ',临时供应商' : '临时供应商';
            if ($tagService->saveTags($supplierId, 14, $newTags, $oldTags)) {
                $channelModel->where('supplier_id', $supplierId)->update([
                    'system_tags' => $newTags
                ]);
            }
        }
    }

    //打上历史检测异常标签
    public function makeSupplierSystemTagAbnormal()
    {
        ini_set('memory_limit', '-1');
        $channelModel = new SupplierChannelModel();
        //读取excel
        $filePath = public_path('data') . DIRECTORY_SEPARATOR . 'abnormal_supplier.xlsx';
        try {
            Excel::selectSheetsByIndex(0)->load($filePath, function ($reader) {
                $reader->sheet('QC不良记录', function () use ($reader) {
                    $supplierModel = new SupplierChannelModel();
                    $suppliers = [];
                    foreach ($reader->all()->toArray() as $key => $item) {
                        if ($key == 0 || $key == 1) {
                            continue;
                        }
                        $supplierName = trim($item[2]);
                        if (empty($supplierName)) {
                            continue;
                        }
                        $supplier = $supplierModel->where('supplier_name', $supplierName)->first();
                        if (!empty($supplier)) {
                            $suppliers[] = $supplier->toArray();
                        }
                    }
                    $tagService = new SupplierTagService();
                    //找到后打上标签
                    foreach ($suppliers as $supplier) {
                        $supplierId = $supplier['supplier_id'];
                        $oldTags = $supplier['system_tags'];
                        if (strpos($supplier['system_tags'], '历史检测异常') !== false) {
                            continue;
                        }
                        $newTags = $supplier['system_tags'] ? rtrim($supplier['system_tags'],
                                ',') . ',历史检测异常' : '历史检测异常';
                        if ($tagService->saveTags($supplierId, 14, $newTags, $oldTags)) {
                            $supplierModel->where('supplier_id', $supplierId)->update([
                                'system_tags' => $newTags
                            ]);
                        }
                    }
                });
            });
        } catch (\Exception $exception) {
            dd($exception);
        }

    }

    //初始化供应商对应的搜索标签到redis
    public function initSupplierSearchTags()
    {
        //初始化所有正式服务器的标签情况到redis
        $supplierModel = new SupplierChannelModel();
        $suppliers = $supplierModel->where('is_type', 0)->get()->toArray();
        $redis = new RedisModel();
        foreach ($suppliers as $supplier) {
            //1精选,2原厂直供,3认证,4猎芯自营,100无标签
            $tagFlags = [];
            //先去判断供应商性质是否为原厂,如果是的话,写入标签2
            if ($supplier['supplier_group'] == 4) {
                $tagFlags[] = 2;
            }

            if ($supplier['has_certification'] == 1) {
                $tagFlags[] = 3;
            }
            $redis->hset('supplier_search_tags', $supplier['supplier_code'], json_encode([
                'supplier_code' => $supplier['supplier_code'],
                'tags' => $tagFlags,
            ]));
        }
    }

    //推送更新供应商的队列
    public function pushSupplierSKu()
    {
        $supplierModel = new SupplierChannelModel();
        $suppliers = $supplierModel->where('is_type', 0)->where('supplier_group', 4)->orderBy('supplier_id', 'desc')
            ->limit(130)->get()->toArray();
        $redis = new RedisModel();
        foreach ($suppliers as $supplier) {
            $supplierTag = $redis->hget('supplier_search_tags', $supplier['supplier_code']);
            if (!$supplierTag) {
                continue;
            }
            $message = json_encode([
                'supplier_code' => $supplier['supplier_code'],
            ]);
            $conn = new AMQPStreamConnection(config('database.connections.rabbitmq.host'),
                config('database.connections.rabbitmq.port'),
                config('database.connections.rabbitmq.login'),
                config('database.connections.rabbitmq.password'));
            $channel = $conn->channel();
            $channel->queue_declare('supplier_zhuanmai_update', false, true, false, false);

            $msg = new AMQPMessage($message,
                array('content_type' => 'text/plain'));
            $channel->basic_publish($msg, '', 'supplier_zhuanmai_update');
        }
    }

    //导入等级修改供应商并且找出没有等级的供应商(针对正式的)
    public function importSupplierLevel()
    {
        $filePath = public_path('data') . DIRECTORY_SEPARATOR . 'supplier_level.xls';
        try {
            Excel::selectSheetsByIndex(0)->load($filePath, function ($reader) {
                $supplierChannelModel = new SupplierChannelModel();
                $reader->sheet('供应商清单', function ($sheet) use ($reader, $supplierChannelModel) {
                    $number = 0;
                    foreach ($reader->all()->toArray() as $key => $item) {
                        $supplierName = trim($item[1]);
                        $level = trim($item[3]);
                        //先去判断是否存在
                        $exist = $supplierChannelModel->where('supplier_name', $supplierName)
                            ->exists();
                        if (!$exist) {
                            $number++;
                            //然后修改excel
                            $sheet->cell('E' . ($key + 2), function ($cell) {
                                $cell->setValue('供应商不存在');
                            });
                        } else {
                            $supplierChannelModel->where('supplier_name', $supplierName)->update([
                                'level' => $level,
                            ]);
                            $sheet->cell('E' . ($key + 2), function ($cell) {
                                $cell->setValue('修改成功');
                            });
                        }

                    }
                    var_dump("一共有${number}个不存在的供应商");
                });
            })->store('xls');
        } catch (\Exception $exception) {
            var_dump($exception);
        }
    }

    //导入主营品牌数据
    public function importMainBrandData()
    {
        $filePath = public_path('data') . DIRECTORY_SEPARATOR . 'supplier_main_brand.xlsx';
        try {
            Excel::selectSheetsByIndex(0)->load($filePath, function ($reader) {
                $reader->sheet('产出', function () use ($reader) {
                    $supplierMainBrandData = [];
                    $standardBrandModel = new StandardBrandModel();
                    foreach ($reader->all()->toArray() as $key => $item) {
                        $supplierName = trim($item[0]);
                        $brandName = $item[1];
                        $brandId = $standardBrandModel->where('brand_name',
                            trim($brandName))->value('standard_brand_id');
                        if (empty($brandId)) {
                            continue;
                        }
                        if (!isset($supplierMainBrandData[$supplierName])) {
                            $supplierMainBrandData[$supplierName][] = $brandId;
                        } else {
                            $supplierMainBrandData[$supplierName][] = $brandId;
                        }
                    }
                    $supplierModel = new SupplierChannelModel();
                    foreach ($supplierMainBrandData as $supplierName => $mainBrandIds) {
                        $result = $supplierModel->where('supplier_name', $supplierName)->update([
                            'main_brands' => implode(',', $mainBrandIds),
                        ]);
                        if ($result) {
                            var_dump('更新供应商主营品牌成功,供应商 : ' . $supplierName);
                        }
                    }
                });
            });
        } catch (\Exception $exception) {
            var_dump($exception);
        }
    }

    //从excel导入供应商
    public function importSupplier()
    {
        $filePath = public_path('data') . DIRECTORY_SEPARATOR . 'supplier_import.xls';
        try {
            Excel::selectSheetsByIndex(0)->load($filePath, function ($reader) {
                $supplierChannelModel = new SupplierChannelModel();
                $supplierService = new SupplierService();
                $reader->sheet('供应商清单', function ($sheet) use ($reader, $supplierChannelModel, $supplierService) {
                    $number = 0;
                    foreach ($reader->all()->toArray() as $key => $item) {
                        $supplierName = trim($item[1]);
                        //先去判断是否存在
                        $exist = $supplierChannelModel->where('supplier_name', $supplierName)
                            ->exists();
                        if (!$exist) {
                            $number++;
                            //往库里面插入
                            $data = [
                                'supplier_name' => $supplierName,
                                'create_uid' => 1000,
                                'create_time' => time(),
                                'status' => 2,
                                'is_type' => 1,
                                'create_name' => 'admin',
                            ];
                            $supplierId = $supplierChannelModel->insertGetId($data);
                            $supplierService->saveSupplierCode($supplierId);
                            //然后修改excel
                            $sheet->cell('E' . ($key + 2), function ($cell) {
                                $cell->setValue('供应商不存在,已经新增');
                            });
                        } else {
                            $sheet->cell('E' . ($key + 2), function ($cell) {
                                $cell->setValue('供应商已经存在,不做新增');
                            });
                        }
                    }
                    var_dump("一共新增了${number}个不存在的供应商");
                });
            })->store('xls');
        } catch (\Exception $exception) {
            var_dump($exception);
        }
    }

    //转移付款方式到新添加的付款方式
    public function TransferPayTypeDataToNewTable()
    {
        ini_set('memory_limit', '-1');
        $suppliers = SupplierChannelModel::where('pay_type', '!=', '0')->get()->toArray();
        $payTypeData = [];
        foreach ($suppliers as $supplier) {
            //3代表是全款,对应新表的预付款 100%
            if ($supplier['pay_type'] == 3) {
                $payTypeData[] = [
                    'supplier_id' => $supplier['supplier_id'],
                    'pay_type' => $supplier['pay_type'],
                    'pay_type_value' => 100,
                    'pay_type_extra' => '%',
                ];
            } else {
                $payTypeData[] = [
                    'supplier_id' => $supplier['supplier_id'],
                    'pay_type' => $supplier['pay_type'],
                    'pay_type_value' => '',
                    'pay_type_extra' => '天',
                ];
            }
        }
        foreach ($payTypeData as $key => $data) {
            //先检查是否存在
            $exist = SupplierPayTypeModel::where('supplier_id', $data['supplier_id'])->exists();
            if ($exist) {
                unset($payTypeData[$key]);
            }
        }
        SupplierPayTypeModel::insert($payTypeData);
    }

    //将未转正的供应商的供应商类型改成未转正
    public function changeSupplierTypeFromIsType()
    {
        SupplierChannelModel::where('is_type', 1)->update([
            'supplier_type' => 3,
        ]);
    }
}