<?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\SupplierAttachmentModel;
use App\Model\SupplierChannelModel;
use App\Model\SupplierContactModel;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;

//这个服务是处理数据的,比如导出信息,或者临时修复数据,所以代码会比较多
class DataService
{
    //20210722
    //转移文件数据(之前是只存到一个字段,现在要存到一张表里面去)
    public function transferFileData()
    {
        //先找出所有上传文件非空的供应商
        $model = new SupplierChannelModel();
        $suppliers = $model->where('qualification_photos', '!=', '')
            ->where('is_type', 0)->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();
//        if (count($suppliers) > 1709) {
//            dd("数量有问题");
//        }
        $redis = new RedisModel();
        //非正式供应商中存在渠道员/采购员,将供应商改为正式供应商
        foreach ($suppliers as $supplier) {
            //先查询是否有重复的供应商
            $count = $model->where('supplier_name', $supplier['supplier_name'])->count();
            if ($count > 1) {
                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' => 1
                ]);
        }
    }

    public function initSystemTag()
    {

        $tagList = [
            1 => '标签1',
            2 => '标签2',
            3 => '标签3',
            4 => '标签4',
        ];

        $tagList = [
            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,
            ]);
            dd($response->getBody()->getContents());
        }

    }

    //替换老的品牌选择成为新的标准品牌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)) {
                    continue;
                }
                $standardBrandIds[] = $standardBrandId;
            }
            if (!empty($standardBrandIds)) {
                $standardBrandIdsStr = implode(',', $standardBrandIds);
            } else {
                $standardBrandIdsStr = '';
            }
//            $supplierModel->where('supplier_id', $supplier['supplier_id'])->update([
//                'main_brands' => $standardBrandIdsStr
//            ]);
            print_r($standardBrandIds);
        }
    }
}