<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Filter\SupplierFilter;
use App\Http\Exporter\SupplierListExporter;
use App\Http\Exporter\SupplierWordExporter;
use App\Http\Services\BlacklistService;
use App\Http\Services\DepartmentService;
use App\Http\Services\LogService;
use App\Http\Services\MessageService;
use App\Http\Services\SupplierAuditService;
use App\Http\Services\SupplierService;
use App\Http\Services\SyncSupplierService;
use App\Http\Transformers\SupplierTransformer;
use App\Http\Validators\SupplierValidator;
use App\Model\SupplierBlacklistModel;
use App\Model\SupplierChannelModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

//通用API,比如获取品牌列表,分类列表等
class SupplierApiController extends Controller
{

    //默认要接收的数据
    private $channelMap = [
        'supplier_id',
        //基础资料
        'supplier_name',
        'register_company_name',
        'supplier_name_en',
        'stockup_type',
        'supplier_group',
        'region',
        'currency',
        'tax_number',
        'supplier_address',
        'main_brands',
        'upload_file',
        'legal_representative',
        'established_time',
        'pay_type',
        'trading_method',

        //收发货地址
        'return_phone',
        'return_address',
        'return_consignee',
        'shipping_address',

        //系数和货期
        'cn_ratio',
        'us_ratio',
        'credit_investigation',
        'us_delivery_time',
        'cn_delivery_time_period',
        'cn_delivery_time',
        'us_delivery_time_period',

        //附加费
        'cn',
        'us',
//        'status',

        //商品上传规则
        'sku_upload_ruler',
    ];

    public function Entrance(Request $request, $id)
    {
        $this->$id($request, $id);
    }

    //添加供应商
    public function AddSupplier($request)
    {
        //先去表单验证
        $validator = new SupplierValidator();
        $validateResult = $validator->checkSave($request);
        if ($validateResult) {
            $this->response(-1, $validateResult);
        }
        $channel = $request->only($this->channelMap);
        $service = new SupplierService();
        $result = $service->saveSupplier($channel, $request->get('contact'));
        if (!$result) {
            $this->response(-1, '操作失败');
        }
        $this->response(0, '操作成功');
    }

    //添加供应商
    public function UpdateSupplier($request)
    {
        //先去表单验证
        $validator = new SupplierValidator();
        $validateResult = $validator->checkSave($request);
        if ($validateResult) {
//            $this->response(-1, $validateResult);
        }
        $channel = $request->only($this->channelMap);
        $service = new SupplierService();
        $result = $service->saveSupplier($channel);
        if (!$result) {
            $this->response(-1, '操作失败');
        }
        $this->response(0, '操作成功');
    }


    //获取供应商信息变更记录
    public function GetSupplierList(Request $request)
    {
        $model = new SupplierChannelModel();
        $query = $model;
        $filter = new SupplierFilter();
        $query = $filter->listFilter($request, $query);
        $limit = $request->get('limit', 10);
        $list = $query->paginate($limit)->toArray();
        $transformer = new SupplierTransformer();
        $list['data'] = $transformer->transformList($list['data']);
        if (env('LOGIN_DOMAIN') == 'user.liexin.net') {
            $list['total'] = $list['total'] > 10 ? 10 : $list['total'];
        }
        $this->response(0, 'ok', $list['data'], $list['total']);
    }

    public function DisableSupplier($request)
    {
        $supplierId = $request->get('supplier_id');
        $model = new SupplierChannelModel();
        $result = $model->where('supplier_id', $supplierId)->update([
            'update_time' => time(),
            'status' => $model::STATUS_DISABLE,
        ]);
        if ($result) {
            //发送队列消息同步到金蝶
            $service = new SyncSupplierService();
            $service->syncSupplierToErp($supplierId);
            $this->response(0, '禁用成功');
        } else {
            $this->response(-1, '禁用失败');
        }

    }

    //修改状态(禁用,启用(审核通过),驳回,草稿,取消黑名单)
    public function ChangeSupplierStatus($request)
    {
        $status = $request->get('status');
        $supplierId = $request->get('supplier_id');
        if (empty($status) || empty($supplierId)) {
            $this->response(-1, '参数缺失');
        }
        $model = new SupplierChannelModel();
        $supplier = $model->where('supplier_id', $supplierId)->first()->toArray();
        $data = [
            'status' => $status,
            'update_time' => time(),
        ];
        //审核通过或者驳回,要更新审核时间
        if (($supplier['status'] == 1 || $supplier['status'] == 3)) {
            if ($status == 2) {
                $data['audit_time'] = time();
                $data['audit_name'] = $request->user->name;
                $data['audit_uid'] = $request->user->userId;
            }
        }
        if ($status == 3) {
            $data['audit_time'] = time();
            $data['audit_name'] = $request->user->name;
            $data['audit_uid'] = $request->user->userId;
        }
        if ($status == 3) {
            $rejectReason = trim($request->get('reject_reason'));
            if (empty($rejectReason)) {
                $this->response(-1, '没有填写驳回原因');
            }
            $data['reject_reason'] = $rejectReason;
        }
        $result = $model->where('supplier_id', $supplierId)->update($data);

        //保存日志
        $logService = new LogService();
        $action = array_get(config('fixed.SupplierStatus'), $status);
        $logService->AddLog($supplierId, 1, $action, $action . '-' . $supplier['supplier_name']);
        if (!$result) {
            $this->response(-1, '修改状态失败');
        }
        //发送短信
        $messageService = new MessageService();
        $messageService->sendSupplierMessage($supplierId, $status);
        //发送队列消息同步到金蝶
        $service = new SyncSupplierService();
        $service->syncSupplierToErp($supplierId);
        $this->response(0, '修改状态成功');
    }

    //导出供应商信息申请表到word
    public function ExportSupplierToWord($request)
    {
        $supplierId = $request->get('supplier_id');
        $exporter = new SupplierWordExporter();
        $exporter->export($supplierId);
    }

    //检查供应商名称是否相似或者重复
    public function CheckSupplierName($request)
    {
        $supplierName = $request->get('supplier_name');
        $supplierId = $request->get('supplier_id');
        $model = new SupplierChannelModel();
        $existedSupplierName = $model->where('supplier_name', $supplierName)->value('supplier_name');
        //如果是编辑操作,则要忽略非当前
        if ($supplierId) {
            if ($supplierName !== $existedSupplierName) {
                $supplierName = $model->where('supplier_name', 'like',
                    "%$supplierName%")->limit(1)->value('supplier_name');
                if (!empty($supplierName)) {
                    $this->response(-2, '存在类似的供应商名称', $supplierName);
                }
            }
        } else {
            if ($existedSupplierName) {
                $this->response(-1, '已经有重复的供应商名称');
            } else {
                $supplierName = $model->where('supplier_name', 'like',
                    "%$supplierName%")->limit(1)->value('supplier_name');
                if (!empty($supplierName)) {
                    $this->response(-2, '存在类似的供应商名称', $supplierName);
                }
            }
        }

        $this->response(0, '供应商名称合理');
    }

    //审核供应商
    public function AuditSupplier($request)
    {
        $status = $request->get('status');
        $rejectReason = $request->get('reject_reason');
        if (empty($status)) {
            $this->response(-1, '必须选择一个审核意见');
        }
        if ($status == 3 && empty($rejectReason)) {
            $this->response(-1, '不同意时必须填写原因');
        }
        $supplierId = $request->get('supplier_id');
        $service = new SupplierAuditService();
        $result = $service->auditSupplier($supplierId, $status, $rejectReason);
        if (!$result) {
            $this->response(-1, '审核失败');
        }
        $this->response(0, '审核成功');

    }

    //分配渠道开发员
    public function AllocatePurchaseUser($request)
    {
        $purchaseUid = $request->get('purchase_uid');
        $supplierId = $request->get('supplier_id');
        if (empty($purchaseUid)) {
            $this->response(-1, '渠道开发员不能为空');
        }
        $service = new SupplierService();
        $result = $service->allocatePurchaseUser($supplierId, $purchaseUid);
        if (!$result) {
            $this->response(-1, '分配渠道开发员失败');
        }
        $this->response(0, '分配渠道开发员成功');

    }

    //导出供应商
    public function Export()
    {
        $params = json_decode(\request()->get('params'), true);
        $exporter = new SupplierListExporter($params);
        $exporter->export();
    }
}