<?php


namespace App\Http\Transformers;


use App\Http\Services\AdminUserService;
use App\Http\Services\DepartmentService;
use App\Http\Services\SkuService;
use App\Http\Services\SupplierPayTypeService;
use App\Http\Services\SupplierService;
use App\Http\Services\SupplierSkuAuditRulerService;
use App\Http\Services\SupplierSkuUploadRulerService;
use App\Http\Services\ViewCheckService;
use App\Model\IntracodeModel;
use App\Model\LogModel;
use App\Model\RedisModel;
use App\Model\SupplierChannelModel;
use App\Model\SupplierContactModel;
use App\Model\SupplierExtendModel;

class SupplierTransformer
{
    public function transformList($list)
    {
        $intraCodeModel = new IntracodeModel();
        $users = $intraCodeModel->getSampleEncode(true);
        $supplierIds = array_column($list, 'supplier_id');
        $viewCheckService = new ViewCheckService();
        $viewData = $viewCheckService->checkSupplierView($supplierIds);
        $adminUserService = new AdminUserService();

        //获取基石上传记录情况,展示第一次上传时间和最后一次上传时间
        $lastUploadSkuTimes = SkuService::getUploadTimeBySupplierCodes(array_column($list, 'supplier_code'), 'last');

        foreach ($list as &$supplier) {
            $supplier['viewed'] = array_get($viewData, $supplier['supplier_id'], false);
            $supplier = $this->getStockupType($supplier);
            $supplier['supplier_group'] = array_get(config('fixed.SupplierGroup'), $supplier['supplier_group'], '未设置');
            $supplier['purchase_type_name'] = array_get(config('field.PurchaseType'), $supplier['purchase_type'], '无');
            $supplier['region_name'] = array_get(config('fixed.Region'), $supplier['region']);
            $supplier['create_time'] = $supplier['create_time'] ? date('Y-m-d H:i:s', $supplier['create_time']) : '';
            $supplier['audit_time'] = $supplier['audit_time'] ? date('Y-m-d H:i:s', $supplier['audit_time']) : '';
            $supplier['update_time'] = $supplier['update_time'] ? date('Y-m-d H:i:s', $supplier['update_time']) : '';
            $supplier['sku_create_time'] = $supplier['sku_create_time'] ? date('Y-m-d H:i:s', $supplier['sku_create_time']) : '';
            $supplier['sku_update_time'] = $supplier['sku_update_time'] ? date('Y-m-d H:i:s', $supplier['sku_update_time']) : '';
            $supplier['channel_username'] = $this->getChannelUserNames($supplier['channel_uid']);
            $supplier['purchase_username'] = array_get($users, $supplier['purchase_uid']);
            $supplier['yunxin_channel_username'] = array_get($users, $supplier['yunxin_channel_uid']);
            $supplier['status_name'] = array_get(config('fixed.SupplierStatus'), $supplier['status']);
            $supplier['supplier_type_name'] = array_get(config('field.SupplierType'), $supplier['supplier_type']);
            $supplier['company_nature_name'] = array_get(config('field.CompanyNature'), $supplier['company_nature']);
            $supplier['region_name'] = array_get(config('fixed.Region'), $supplier['region'], '暂无');
            $supplier['contact_num'] = $this->getContactNum($supplier['supplier_id']);
            $supplier['has_sku'] = $supplier['sku_num'] ? '是' : '否';
            $supplier['is_business_abnormal_name'] = $supplier['is_business_abnormal'] == 1 ? '是' : '否';
            if (isset($supplier['attachment'])) {
                $supplier['has_quality_assurance_agreement'] = $this->checkHasSpecificAttachment('quality_assurance_agreement', $supplier['attachment']) ? '有' : '无';
                $supplier['has_cooperation_agreement'] = $this->checkHasSpecificAttachment('cooperation_agreement', $supplier['attachment']) ? '有' : '无';
            } else {
                $supplier['has_quality_assurance_agreement'] = '无';
            }
            $supplier['is_own'] = $supplier['create_uid'] == request()->user->userId ? "创建" : "指派";
            if (empty($supplier['create_name'])) {
                $userInfo = $adminUserService->getAdminUserInfo($supplier['create_uid']);
                $supplier['create_name'] = array_get($userInfo, 'name');
            }

            $supplier['last_upload_sku_time'] = array_get($lastUploadSkuTimes,$supplier['supplier_code']) ? date('Y-m-d H:i:s',
                $lastUploadSkuTimes[$supplier['supplier_code']]) : '';

            //获取最新修改人以及下级审核员
            $log = LogModel::getLastLog($supplier['supplier_id']);
            $supplier['last_update_name'] = $log ? $log['admin_name'] : '';
            $supplier['last_update_time'] = $log ? date('Y-m-d H:i:s', $log['add_time']) : '';
            //黑名单
            if (!empty($supplier['blacklist'])) {
                $supplier['blacklist_name'] = $supplier['blacklist']['blacklist_name'];
                $supplier['blacklist_time'] = date('Y-m-d H:i:s', $supplier['blacklist']['add_time']);
                $supplier['blacklist_reason'] = $supplier['blacklist']['reason'];
            }
        }
        unset($supplier);
        return $list;
    }

    //这个是用来区分采购员里面哪些是离职的,那些是不离职的,显示在前端
    public function transformResignChannelUser($suppliers)
    {
        foreach ($suppliers as &$supplier) {
            $onJobChannelUsers = (new IntracodeModel())->getSampleEncode();
            $onJobUserNameList = array_values($onJobChannelUsers);
            $channelUserNameList = !empty($supplier['channel_username']) ? explode(',',
                $supplier['channel_username']) : [];
            if (empty($supplier['channel_uid'])) {
                $supplier['resign_channel_username'] = $supplier['on_job_channel_username'] = '';
                continue;
            }
            $resignChannelUserNameList = $onJobChannelUserNameList = [];
            //然后判断哪些是离职,哪些是在职的
            foreach ($channelUserNameList as $username) {
                if (!in_array($username, $onJobUserNameList)) {
                    $resignChannelUserNameList[] = $username;
                } else {
                    $onJobChannelUserNameList[] = $username;
                }
            }
            $supplier['resign_channel_username'] = $resignChannelUserNameList ? implode(',',
                $resignChannelUserNameList) : '';
            $supplier['on_job_channel_username'] = $onJobChannelUserNameList ? implode(',',
                $onJobChannelUserNameList) : '';
        }
        unset($supplier);
        return $suppliers;
    }

    //判断是否有特定的协议
    public function checkHasSpecificAttachment($specificAttacmentName, $attachments)
    {
        if (!$attachments) {
            return false;
        }
        foreach ($attachments as $key => $value) {
            if ($value['field_name'] == $specificAttacmentName) {
                return true;
            }
        }
        return false;
    }

    public function getContactNum($supplierId)
    {
        $model = new SupplierContactModel();
        return $model->where('supplier_id', $supplierId)->count();
    }

    //获取采购员名字(权限分离)
    public function getChannelUserNames($channelUid)
    {
        $canViewAllChannelUser = checkPerm('ViewAllChannelUser');
        $intraCodeModel = new IntracodeModel();
        $userCodes = $intraCodeModel->getAllSampleEncode();
        $data = [];
        $channelUidList = explode(',', $channelUid);
        $channelUidList = array_unique($channelUidList);
        foreach ($channelUidList as $codeId) {
            if ($canViewAllChannelUser) {
                if (!empty($codeId)) {
                    $data[] = array_get($userCodes, $codeId);
                }
            } else {
                if ($codeId == request()->user->codeId) {
                    $data[] = array_get($userCodes, $codeId);
                }
            }
        }
        return implode(',', $data);
    }

    public function transformInfo($supplier)
    {
        if (empty($supplier)) {
            return [];
        }
        $intraCodeModel = new IntracodeModel();
        $users = $intraCodeModel->getSampleEncode(true);
        $supplier['stockup_type_data'] = $this->transformStockupTypeData($supplier['stockup_type']);
        $supplier['established_time'] = !empty($supplier['established_time']) ? date('Y-m-d',
            $supplier['established_time']) : '';
        $supplier = $this->getStockupType($supplier);
        $supplier['status_name'] = array_get(config('fixed.SupplierStatus'), $supplier['status']);
        $supplier['region_name'] = array_get(config('fixed.Region'), $supplier['region']);
        $supplier['currency_name'] = array_get(config('fixed.Currency'), $supplier['currency']);
        $supplier['supplier_group_name'] = array_get(config('fixed.SupplierGroup'), $supplier['supplier_group']);
        $supplier['is_business_abnormal_name'] = array_get($supplier, 'is_business_abnormal') == 1 ? '是' : '否';
        $supplier['has_legal_ID_card_name'] = array_get($supplier, 'has_legal_ID_card') == 1 ? '是' : '否';
        $supplier['pay_type_name'] = array_get(config('fixed.SupplierPayType'), $supplier['pay_type']);
        $supplier['trading_method_name'] = array_get(config('fixed.TradingMethod'), $supplier['trading_method']);
        if (isset($supplier['settlement_type'])) {
            $supplier['settlement_type_name'] = array_get(config('field.SettlementType'), $supplier['settlement_type']);
        }
        $supplier['main_brand_names'] = $this->getMainBrandNames($supplier['main_brands']);
        if (!empty($supplier['agency_brands'])) {
            $supplier['agency_brand_names'] = $this->getMainBrandNames($supplier['agency_brands']);
        }
        $supplier['update_time'] = $supplier['update_time'] ? date('Y-m-d H:i:s', $supplier['update_time']) : '';
        $supplier['create_time'] = $supplier['create_time'] ? date('Y-m-d H:i:s', $supplier['create_time']) : '';
        $supplier['channel_username'] = $this->getChannelUserNames($supplier['channel_uid']);
        $supplier['purchase_username'] = array_get($users, $supplier['purchase_uid']);
        $supplier['yunxin_channel_username'] = array_get($users, array_get($supplier, 'yunxin_channel_uid'));
        $uploadRulerService = new SupplierSkuUploadRulerService();
        $supplier['sku_upload_ruler'] = $uploadRulerService->getSkuUploadRuler($supplier['sku_upload_ruler']);
        $ruleService = new SupplierSkuAuditRulerService();
        $supplier['sku_audit_ruler'] = $ruleService->getSkuAuditRuler(array_get($supplier, 'sku_audit_ruler'));
        $supplier = $this->transformDeliveryTimeData($supplier);
        $ExtendModel = new SupplierExtendModel();
        //获取该supplier_code对应的数据
        $supplier['extra_fee'] = $ExtendModel->getExtendExtra($supplier['supplier_code'], $supplier['supplier_id']);
        //获取供应商地址信息
        $supplier = $this->getSupplierAddress($supplier);
        if (isset($supplier['supplier_type'])) {
            $supplier['supplier_type_name'] = array_get(config('field.SupplierType'), $supplier['supplier_type']);
        }
        //获取最近修改信息
        $log = LogModel::getLastLog($supplier['supplier_id']);
        $supplier['last_update_name'] = $log['admin_name'] ?: '无';
        $supplier['last_update_time'] = empty($supplier['last_update_time']) ? ($log['add_time'] ? date('Y-m-d H:i:s',
            $log['add_time']) : '无') : '无';
        $supplier['has_certification_name'] = array_get(config('fixed.CertificationStatus'),
            array_get($supplier, 'has_certification', ''), '');
        $supplier['sku_tag_name'] = array_get(config('field.SkuTag'), array_get($supplier, 'sku_tag', ''), '无');
        $supplier['sku_mode_name'] = array_get(config('field.SkuMode'), array_get($supplier, 'sku_mode', ''), '无');
        $supplier['purchase_type_name'] = array_get(config('field.PurchaseType'), $supplier['purchase_type'], '无');
        $supplier['cp_time_format'] = ('现货 : ' . ($supplier['cp_time_day'] == -1 ? '无限制' : $supplier['cp_time_day'] . '天')) . ' | '
            . ('期货 : ' . ($supplier['futures_cp_time_day'] == -1 ? '无限制' : $supplier['futures_cp_time_day'] . '天'));
        return $supplier;
    }

    private function transformDeliveryTimeData($supplier)
    {
        $supplier['cn_delivery_time_full'] = $supplier['cn_delivery_time'];
        $supplier['us_delivery_time_full'] = $supplier['us_delivery_time'];
        $supplier['cn_delivery_time_period'] = strpos($supplier['cn_delivery_time'], '天') !== false ? '天' : '周';
        $supplier['us_delivery_time_period'] = strpos($supplier['us_delivery_time'], '天') !== false ? '天' : '周';
        $supplier['cn_delivery_time'] = str_replace('天', '', $supplier['cn_delivery_time']);
        $supplier['cn_delivery_time'] = str_replace('周', '', $supplier['cn_delivery_time']);
        $supplier['us_delivery_time'] = str_replace('天', '', $supplier['us_delivery_time']);
        $supplier['us_delivery_time'] = str_replace('周', '', $supplier['us_delivery_time']);
        return $supplier;
    }

    private function getSupplierAddress($supplier)
    {
        $supplierService = new SupplierService();
        $address = $supplierService->getAddress($supplier['supplier_id']);
        $supplier['shipping_address'] = array_get($address, 'shipping_address', '');
        $supplier['return_address'] = array_get($address, 'return_address', '');
        $supplier['return_consignee'] = array_get($address, 'return_consignee', '');
        $supplier['return_phone'] = array_get($address, 'return_phone', '');
        return $supplier;
    }

    public function getStockupType($supplier)
    {
        $supplier['stockup_type'] = explode(',', $supplier['stockup_type']);
        $supplier['stockup_type'] = array_map(function ($value) {
            return array_get(config('fixed.StockupType'), $value);
        }, $supplier['stockup_type']);
        $supplier['stockup_type_name'] = $supplier['stockup_type'] = implode(' | ', $supplier['stockup_type']);
        return $supplier;
    }

    public function getMainBrandNames($mainBrandsIds)
    {
        $mainBrandsIds = explode(',', $mainBrandsIds);
        $redis = new RedisModel();
        $brands = $redis->hmget('standard_brand', $mainBrandsIds);
        $brandNames = '';
        foreach ($brands as $brand) {
            $brand = json_decode($brand, true);
            $brandNames = $brandNames . ' | ' . $brand['brand_name'];
        }
        return $brandNames;
    }

    public function transformStockupTypeData($stockupType)
    {
        if (!empty($stockupType)) {
            return explode(',', $stockupType);
        }
        return [];
    }

    //转换表单数据
    public function transformPostData($channel)
    {

        $channel['supplier_name'] = trim($channel['supplier_name']);
        if (!empty($channel['stockup_type'])) {
            $stockupType = array_keys($channel['stockup_type']);
            $stockupType = !empty($stockupType) ? implode(",", $stockupType) : '';
            $channel['stockup_type'] = $stockupType;
        }

        if (empty($channel['purchase_uid'])) {
            unset($channel['purchase_uid']);
        }

        if (!empty($channel['system_tags'])) {
            $channel['system_tags'] = rtrim($channel['system_tags'], ',');
        }

        if (!empty($channel['customer_tags'])) {
            $channel['customer_tags'] = rtrim($channel['customer_tags'], ',');
        }

        $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'] . $channel['cn_delivery_time_period'] : '';
        $channel['us_delivery_time'] = $channel['us_delivery_time'] ? $channel['us_delivery_time'] . $channel['us_delivery_time_period'] : '';
        unset($channel['upload_file']);
        $channel['established_time'] = strtotime($channel['established_time']);


        //省市选择的处理
        if (!empty($channel['province_city'])) {
            $regionData = explode(',', $channel['province_city']);
            $channel['province_id'] = !empty($regionData[0]) ? $regionData[0] : 0;
            $channel['city_id'] = !empty($regionData[1]) ? $regionData[1] : 0;
        }
        //判断所在区域,如果不是中国,则要把省市去掉
        if ($channel['region'] != SupplierChannelModel::REGION_CN) {
            $channel['province_id'] = $channel['city_id'] = 0;
        }
        unset($channel['province_city']);

        $skuUploadRulerService = new SupplierSkuUploadRulerService();
        $channel['sku_upload_ruler'] = $skuUploadRulerService->getSkuUploadRulerForDB($channel['sku_upload_ruler']);

        $attachment = [];
        $attachmentFields = config('field.AttachmentFields');
        foreach ($channel as $key => $field) {
            if (in_array($key, $attachmentFields)) {
                $attachment[$key] = $field;
                unset($channel[$key]);
            }
        }

        //国内才有税号
        if ($channel['region'] != SupplierChannelModel::REGION_CN) {
            $channel['tax_number'] = '';
        }

        $channel['attachment'] = $attachment;
        //没有值就是无限制,就是-1
        $channel['main_brands_limit'] = $channel['main_brands_limit_type'] == 2 ? -1 : $channel['main_brands_limit'];
        unset($channel['main_brands_limit_type']);
        return $channel;
    }

    public static function transformSearch($suppliers)
    {
        if (!empty($suppliers)) {
            foreach ($suppliers as &$supplier) {
                foreach ($supplier['pay_type'] as &$payType) {
                    $payType['pay_type_name'] = array_get(config('fixed.SupplierPayType'), $payType['pay_type']);
                }
                unset($payType);
            }
            unset($supplier);
        }
        return $suppliers;
    }

    //供应商审核详情
    public function transformSupplierDetail($supplier)
    {
        $supplier['contact'] = $supplier['contact'] ? (new SupplierContactTransformer())->transformList($supplier['contact']) : [];
        $supplier['receipt'] = $supplier['receipt'] ? (new ReceiptTransformer())->transformList($supplier['receipt']) : [];
        $supplier['attachment'] = $supplier['attachment'] ? (new SupplierAttachmentTransformer())->transformList($supplier['attachment']) : [];
        //还要把附件都转成https,小程序那边只能https
        $supplier['receipt'] = array_map(function ($receipt) {
            $receipt['certificate'] = str_replace('http://', 'https://', $receipt['certificate']);
            return $receipt;
        }, $supplier['receipt']);
        $supplier['attachment'] = array_map(function ($attachment) {
            $attachment['file_url'] = str_replace('http://', 'https://', $attachment['file_url']);
            return $attachment;
        }, $supplier['attachment']);
        return $supplier;
    }

}