<?php

namespace App\Http\Controllers;

use App\Http\Services\DepartmentService;
use App\Http\Services\LogService;
use App\Http\Services\RegionService;
use App\Http\Services\SkuUploadLogService;
use App\Http\Services\StandardBrandService;
use App\Http\Services\SupplierAttachmentService;
use App\Http\Services\SupplierService;
use App\Http\Services\SupplierShareApplyService;
use App\Http\Services\SupplierStatisticsService;
use App\Http\Services\SupplierTagService;
use App\Http\Transformers\LogTransformer;
use App\Http\Transformers\SupplierTransformer;
use App\Model\IntracodeModel;
use App\Model\LogModel;
use App\Model\SupplierChannelModel;
use App\Model\SupplierContactModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use function foo\func;

class SupplierController extends Controller
{
    public function info(Request $request, $id = '')
    {
        {
            if ($request->path() == '/') {
                $path = 'web/index';
            } else {
                $path = $request->path();
            }

            $this->data = [
                'menus' => $request->menus,
                'header' => $request->user->header,
                'username' => $request->user->email,
                'user_email' => $request->user->email,
                'uri' => '/' . $path,
                'id' => $id
            ];

            $userId = $request->user->userId;
            $canAudit = perm($userId, 'AuditSupplier');
            $this->data['canAudit'] = $canAudit;
            //把是否是领导查看放到模板,用来区分部门老大能干的权限
            $leaderView = perm($userId, 'LeaderView');
            $this->data['leaderView'] = $leaderView;

            return $this->$id($request);
        }
    }

    public function __call($name, $arr)
    {
        $data['errinfo'] = '访问路径错误';
        return view('errors.error', $data);
    }

    //供应商列表
    public function SupplierList($request)
    {
        //判断权限
        $intraCodeModel = new IntracodeModel();
        $this->data['userCodes'] = $intraCodeModel->getChannelUsersEncode();
        $this->data['users'] = $intraCodeModel->getAdminUserAndCode();
        $this->data['validPerms'] = [];
        //获取共用审核的条数
        $applyService = new SupplierShareApplyService();
        $applyData = $applyService->getAuditSupplierShareApplyList($request->user->userId);
        $this->data['shareApplyCount'] = $applyData['total'];
        $statusData = [];
        foreach (config('fixed.SupplierStatus') as $key => $value) {
            $statusData[] = [
                'name' => $value,
                'value' => $key,
            ];
        }
        $this->data['statusData'] = $statusData;
        $stockupTypeData = [];
        foreach (config('fixed.StockupType') as $key => $value) {
            $stockupTypeData[] = [
                'name' => $value,
                'value' => $key,
            ];
        }
        $this->data['stockupTypeData'] = $stockupTypeData;
        $levelData = [];
        foreach (config('field.LevelMap') as $key => $value) {
            $levelData[] = [
                'name' => $value,
                'value' => $key,
            ];
        }
        $this->data['levelData'] = $levelData;
        $supplierTypeData = [];
        foreach (config('field.SupplierType') as $key => $value) {
            $supplierTypeData[] = [
                'name' => $value,
                'value' => $key,
            ];
        }
        $this->data['supplierTypeData'] = $supplierTypeData;

        //获取创建人部门树
        $this->data['createUserDepartmentList'] = (new DepartmentService())->getCreateUserDepartmentListForXmSelect();

        return $this->view('供应商列表');
    }

    //供应商详情
    public function SupplierDetail($request)
    {
        $supplierId = $request->get('supplier_id');

        //判断是否能查看
        $canCheck = (new SupplierService())->checkCanViewSupplier($supplierId);
        if (!$canCheck) {
            return '没查看该供应商的权限';
        }

        $supplierService = new SupplierService();
        $supplier = $supplierService->getSupplier($supplierId);
        if (empty($supplier)) {
            return '供应商不存在';
        }
        //记录查看日志(1个小时内查看的跳过)
        $logModel = new LogModel();
        $lastViewAddTime = $logModel->where('supplier_id', $supplierId)->where('admin_id', $request->user->userId)
            ->where('type', LogModel::VIEW_OPERATE)->orderBy('id', 'desc')->value('add_time');
        $oneHourTimestamp = 3600;
        if (time() - $lastViewAddTime > $oneHourTimestamp) {
            $logService = new LogService();
            $logService->AddLog($supplierId, LogModel::VIEW_OPERATE, '查看', '查看供应商详情');
        }
        $this->data['operate'] = 'detail';
        $this->data['supplier'] = $supplier;
        $regionService = new RegionService();
        $regionNames = $regionService->getRegionNameByIds([
            $supplier['province_id'],
            $supplier['city_id']
        ]);
        $this->data['province_city'] = implode(' | ', $regionNames);
        $this->data['address'] = $supplierService->getAddress($supplierId);
        $this->data['sku_upload_log_count'] = (new SkuUploadLogService())->getSkuUploadLogCount($supplierId);
        return $this->view('供应商详情');
    }

    //添加供应商
    public function AddSupplier($request)
    {
        $supplierId = $request->get('supplier_id');
        $supplierService = new SupplierService();
        $intraCodeModel = new IntracodeModel();
        $this->data['outside_contact_status'] = Config('fixed.OutsideContactStatus');
        $this->data['outside_contact_type'] = Config('fixed.OutsideContactType');
        $userCodes = $intraCodeModel->getChannelUsersEncode(false);
        $this->data['userCodes'] = $userCodes;
        $this->data['user'] = $userCodes;
        $this->data['purchase_users'] = [];
        foreach ($userCodes as $userId => $code) {
            $this->data['purchase_users'][] = [
                'name' => $code,
                'value' => $userId,
            ];
        }
        $defaultPurchaseUid = $intraCodeModel->getCodeIdByUserName(config('field.DefaultPurchaseName'));
        $this->data['operate'] = 'add';
        $this->data['default_purchase_uid'] = $defaultPurchaseUid;
        //省市区数据放到script模板
        $regionService = new RegionService();
        $this->data['region_data'] = $regionService->getCityRegionData();
        $this->data['brand_init_value'] = [];
        $this->data['agency_brand_init_value'] = [];
        //编辑
        if (!empty($supplierId)) {
            $this->data['title'] = '编辑供应商';
            $this->data['supplierInfo'] = $supplierService->getSupplier($supplierId);
            $DB = DB::connection('yunxin');
            $supplierAccountInfo = $DB->table('supplier_account')->where("supplier_com_id", "=",
                $supplierId)->select('mobile', "password_raw")->first();
            $this->data['supplier_account_info'] = $supplierAccountInfo;
            $this->data['address'] = $supplierService->getAddress($supplierId);
        } else {
            $this->data['title'] = '添加供应商';
        }

        return $this->view('新增供应商');
    }

    //编辑供应商
    public function UpdateSupplier($request)
    {
        $intraCodeModel = new IntracodeModel();
        $userCodes = $intraCodeModel->getSampleEncode();
        $this->data['userCodes'] = $intraCodeModel->getChannelUsersEncode();
        $this->data['user'] = $userCodes;
        $this->data['purchase_users'] = [];
        $this->data['operate'] = 'update';
        foreach ($userCodes as $userId => $code) {
            $this->data['purchase_users'][] = [
                'name' => $code,
                'value' => $userId,
            ];
        }
        //省市区数据放到script模板
        $regionService = new RegionService();
        $this->data['region_data'] = $regionService->getCityRegionData();
        //编辑
        $this->data['title'] = '编辑供应商';
        $supplierId = $request->get('supplier_id');
        $supplierService = new SupplierService();
        $supplier = $supplierService->getSupplier($supplierId);
        if (empty($supplier)) {
            return '供应商不存在';
        }
        //省市id,给控件用
        $this->data['province_city'] = [$supplier['province_id'], $supplier['city_id']];
        //获取标签情况
        $tagService = new SupplierTagService();

        $systemTags = $tagService->getSystemTagsBySupplierId($supplierId, 1);
        $supplier['system_tags'] = array_map(function ($value) {
            return [
                'tag_name' => $value,
            ];
        }, $systemTags);
        $customerTags = $tagService->getTagsBySupplierId($supplierId, 2);
        $supplier['customer_tags'] = $customerTags ? implode(',', $customerTags) : '';
        $supplierModel = new SupplierChannelModel();
        $supplierModel->where('supplier_id', $supplierId)->update([
            'customer_tags' => $supplier['customer_tags'],
        ]);
        $this->data['supplier'] = $supplier;
        $this->data['address'] = $supplierService->getAddress($supplierId);
        $this->data['ignore_supplier_type_change_tips'] = in_array($supplier['supplier_name'],
            config('field.SkipChangeSupplierTypeNames'));
        $this->data['sku_upload_log_count'] = (new SkuUploadLogService())->getSkuUploadLogCount($supplierId);
        $this->data['brand_init_value'] = (new StandardBrandService())->getBrandInitValue($supplier['main_brands']);
        $this->data['exclude_brand_init_value'] = (new StandardBrandService())->getBrandInitValue($supplier['main_brands']);
        $this->data['agency_brand_init_value'] = (new StandardBrandService())->getBrandInitValue($supplier['agency_brands']);
        return $this->view('编辑供应商');
    }

    //审核供应商
    public function AuditSupplier($request)
    {
        $supplierId = $request->get('supplier_id');
        $model = new SupplierChannelModel();
        $supplier = $model->where('supplier_id', $supplierId)->first();
        //获取最后一条非分配渠道员的日志
        $logModel = new LogModel();
        $auditContent = $logModel->where('supplier_id', $supplierId)
            ->where('action', '!=', '')
            ->where('type', '!=', 3)
            ->orderBy('id', 'desc')->first();
        if (!empty($auditContent)) {
            $logTransformer = new LogTransformer();
            $auditContent = $logTransformer->transformInfo($auditContent);
        } else {
            $auditContent = [];
        }
        $this->data['auditContent'] = $auditContent;
        $this->data['supplier'] = $supplier ? $supplier->toArray() : [];
        return $this->view('审核供应商');
    }

    //分配渠道员
    public function AllocatePurchaseUser($request)
    {
        $supplierId = $request->get('supplier_id');
        $model = new SupplierChannelModel();
        $supplier = $model->where('supplier_id', $supplierId)->first();
        $supplier = $supplier ? $supplier->toArray() : [];
        $transformer = new SupplierTransformer();
        $supplier = $transformer->transformInfo($supplier);
        $this->data['supplier'] = $supplier;
        $intraCodeModel = new IntracodeModel();
        $this->data['userCodes'] = $intraCodeModel->getChannelUsersEncode(false);
        $logModel = new LogModel();
        $this->data['logs'] = $logModel->where('supplier_id', $supplierId)
            ->where('action', '分配渠道开发员')->orderBy('id', 'desc')
            ->limit(10)->get();
        return $this->view('审核供应商');
    }

    //批量分配渠道开发员
    public function BatchAllocatePurchaseUser($request)
    {
        $supplierIds = $request->get('supplier_ids');
        $this->data['supplierIds'] = $supplierIds;
        $supplierIds = explode(',', $supplierIds);
        $model = new SupplierChannelModel();
        $suppliers = $model->whereIn('supplier_id', $supplierIds)->get()->toArray();
        $transformer = new SupplierTransformer();
        $suppliers = $transformer->transformList($suppliers);
        $this->data['suppliers'] = $suppliers;
        $intraCodeModel = new IntracodeModel();
        $this->data['userCodes'] = $intraCodeModel->getChannelUsersEncode(false);
        return $this->view('批量分配渠道开发员');
    }

    //批量添加采购员
    public function AllocateChannelUser($request)
    {
        $supplierIds = $request->get('supplier_ids');
        $this->data['supplierIds'] = $supplierIds;
        $supplierIds = explode(',', $supplierIds);
        $model = new SupplierChannelModel();
        $suppliers = $model->whereIn('supplier_id', $supplierIds)->get()->toArray();
        $transformer = new SupplierTransformer();
        $suppliers = $transformer->transformList($suppliers);
        $this->data['suppliers'] = $suppliers;
        $intraCodeModel = new IntracodeModel();
        $this->data['userCodes'] = $intraCodeModel->getChannelUsersEncode(false);
        return $this->view('添加采购员');
    }

    //操作日志列表
    public function LogList($request, $data)
    {
        $intraCodeModel = new IntracodeModel();
        $data['userCodes'] = $intraCodeModel->getSampleEncode();
        $data['title'] = '操作日志记录';
        return view('web', $data);
    }

    //分配线上采购员
    public function SetYunxinChannelUser($request)
    {
        $supplierId = $request->get('supplier_id');
        $model = new SupplierChannelModel();
        $supplier = $model->where('supplier_id', $supplierId)->first();
        $supplier = $supplier ? $supplier->toArray() : [];
        $this->data['supplier'] = $supplier;
        $intraCodeModel = new IntracodeModel();
        $userCodes = $intraCodeModel->getSampleEncode();
        //去除非当前供应商所拥有的采购的人员,只能从当前供应商设置的采购里面选择线上采购员
        $channelUids = explode(',', $supplier['channel_uid']);
        foreach ($userCodes as $codeId => $value) {
            if (!in_array($codeId, $channelUids)) {
                unset($userCodes[$codeId]);
            }
        }
        $this->data['userCodes'] = $userCodes;
        return $this->view('审核供应商');
    }

    //批量分配线上采购员
    public function BatchAllocateYunxinChannelUser($request)
    {
        $supplierIds = $request->get('supplier_ids');
        $this->data['supplierIds'] = $supplierIds;
        $supplierIds = explode(',', $supplierIds);
        $model = new SupplierChannelModel();
        $suppliers = $model->whereIn('supplier_id', $supplierIds)->get()->toArray();
        $transformer = new SupplierTransformer();
        $suppliers = $transformer->transformList($suppliers);
        $this->data['suppliers'] = $suppliers;
        $intraCodeModel = new IntracodeModel();
        $this->data['userCodes'] = $intraCodeModel->getChannelUsersEncode(false);
        return $this->view('批量分配渠道开发员');
    }

    //拉黑供应商
    public function BlockSupplier($request)
    {
        $supplierId = $request->get('supplier_id');
        $supplierModel = new SupplierChannelModel();
        $supplier = $supplierModel->where('supplier_id', $supplierId)->first()->toArray();
        $this->data['supplier'] = $supplier;
        return $this->view('加入黑名单');
    }

    //禁用供应商
    public function DisableSupplier($request)
    {
        $supplierId = $request->get('supplier_id');
        $supplierModel = new SupplierChannelModel();
        $supplier = $supplierModel->where('supplier_id', $supplierId)->first()->toArray();
        $this->data['supplier'] = $supplier;
        return $this->view('禁用供应商');
    }

    //导出供应商详情表格
    public function PrintSupplier($request)
    {
        $supplierService = new SupplierService();
        $supplierId = $request->get('supplier_id');
        $printData = $supplierService->getSupplierPrintData($supplierId);
        $this->data['printData'] = $printData;
        return $this->view('打印供应商详情');
    }

    //批量申请审批供应商
    public function BatchApplyInReviewSupplier($request)
    {
        $supplierIds = $request->get('supplier_ids');
        $this->data['supplierIds'] = $supplierIds;
        $supplierIds = explode(',', $supplierIds);
        $model = new SupplierChannelModel();
        $suppliers = $model->whereIn('supplier_id', $supplierIds)->get()->toArray();
        $transformer = new SupplierTransformer();
        $suppliers = $transformer->transformList($suppliers);
        $this->data['suppliers'] = $suppliers;
        return $this->view('批量分配渠道开发员');
    }

    //查询供应商
    public function QuerySupplier($request)
    {
        return $this->view('查询供应商');
    }

    //交接供应商
    public function TransferSupplier($request)
    {
        $supplierId = $request->input('supplier_id');
        $supplier = SupplierChannelModel::where('supplier_id', $supplierId)->first();
        if (empty($supplier)) {
            return '当前选择的供应商不存在';
        }
        $this->data['supplier'] = $supplier;

        $channelUids = SupplierContactModel::where('supplier_id', $supplierId)->pluck('can_check_uids')
            ->toArray();
        $channelUids = array_unique($channelUids);
        $supplierUserCodes = (new IntracodeModel())->getSampleEncodeByCodeIds($channelUids);
        $this->data['supplierUserCodes'] = $supplierUserCodes;

        $this->data['userCodes'] = (new IntracodeModel())->getSampleEncode();
        return $this->view('供应商交接');
    }

}