<?php

namespace App\Services\goods;

use App\Exception\custom\GoodsException;
use App\Models\goods\mysql\Ota;
use Api\PhpServices\Printer\PrinterFactory;
use Validate\OtaValidate;

class OtaService
{
    const COLUMNS = ['ota_id','ota_name','printer_sn','printer_key','label_printer_sn','label_printer_key', 'longitude', 'latitude', 'location', 'address', 'status'];
    /**
     * 获取供应商列表（op 后台）
     * @param string $otaName
     * @param string $contacts
     * @param string $phone
     * @param int $offset
     * @param int $limit
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    public static function list($otaName='',$printerSN='',$printerKey='', $labelPrinterSN='',$labelPrinterKey='', $isNormal = false,$offset=0,$limit=20)
    {
        $otaName && $where['ota_name'] = $otaName;
        $printerSN && $where["printer_sn"] = $printerSN;
        $printerKey && $where['printer_key'] = $printerKey;
        $labelPrinterSN && $where["label_printer_sn"] = $labelPrinterSN;
        $labelPrinterKey && $where['label_printer_key'] = $labelPrinterKey;

        $isNormal &&$where['status'] = Ota::STATUS_NORMAL;
        $where['ORDER'] = ['ota_id' => 'DESC'];
        $where['LIMIT'] = [$offset, $limit];

        $res['list'] = Ota::select(self::COLUMNS, $where);
        unset($where['ORDER'],$where['LIMIT']);
        $res['total'] = Ota::count('*', $where);

        return $res;
    }

    /**
     * 获取某个ota详情
     * @param $OtaId
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    public static function detail($OtaId)
    {
        return Ota::get(self::COLUMNS,['ota_id'=>$OtaId]);
    }


    /**
     * 根据id批量获取供应商信息
     * @param $otaIds
     * @return \Api\PhpUtils\Mysql\MysqlBase|array
     */
    public static function getOtaListByIds($otaIds)
    {
        if(empty($otaIds)) {
            return [];
        }

        return Ota::select(self::COLUMNS,['ota_id'=>$otaIds]);
    }

    /**
     * 添加供应商
     * @param $params
     * @return \Api\PhpUtils\Mysql\MysqlBase
     * @throws GoodsException
     */
    public static function add($params)
    {
        //检查供应商是否已存在
        if (self::list($params['ota_name'])['total'] > 0) {
            throw new GoodsException(['cus' => GoodsException::OTA_ALREADY_EXIST]);
        }

        //检查打印机是否已存在 -- 打印机已被（商家名称）绑定
        if(isset($params['printer_sn']) && $params['printer_sn']) {
            if ((new OtaValidate())->is_label_printer_sn($params['printer_sn'])) {
                throw new GoodsException(['cus' => GoodsException::PRINTER_SN_ERROR]);
            }
            $printer = self::list('',$params['printer_sn']);
            if ($printer['total'] > 0) {
                throw new GoodsException(
                    ['cus' => GoodsException::PRINTER_ALREADY_EXIST,'data'=>[$printer['list'][0]['ota_name']]]
                );
            }
        }
        //检查标签打印机是否已存在 -- 打印机已被（商家名称）绑定
        if(isset($params['label_printer_sn']) && $params['label_printer_sn']) {

            if (!(new OtaValidate())->is_label_printer_sn($params['label_printer_sn'])) {
                throw new GoodsException(['cus' => GoodsException::PRINTER_SN_ERROR]);
            }
            $printer = self::list('','', '', $params['label_printer_sn']);
            if ($printer['total'] > 0) {
                throw new GoodsException(
                    ['cus' => GoodsException::LABEL_PRINTER_ALREADY_EXIST,'data'=>[$printer['list'][0]['ota_name']]]
                );
            }
        }

        try {

            if(isset($params['printer_sn']) && $params['printer_sn']) {
                $FeiPrinter = PrinterFactory::getPrinter('Fei');
                $FeiPrinter->addPrinter([
                    'printer_sn' => $params['printer_sn'],
                    'printer_key' => $params['printer_key'],
                    'ota_name' => $params['ota_name'],
                ]);
            }
            if(isset($params['label_printer_sn']) && $params['label_printer_sn']) {
                $FeiPrinter = PrinterFactory::getPrinter('Fei');
                $FeiPrinter->addPrinter([
                    'printer_sn' => $params['label_printer_sn'],
                    'printer_key' => $params['label_printer_key'],
                    'ota_name' => $params['ota_name'],
                ]);
            }
        } catch (\Exception $e) {
            throw new GoodsException(
                ['cus' => GoodsException::PRINTER_BIND_ERROR,'data'=>[$e->getMessage()]]
            );
        }


        $data['ota_name'] = $params['ota_name'];
        $data['printer_sn'] = $params['printer_sn'] ?? '';
        $data['printer_key'] = $params['printer_key'] ?? '';
        $data['label_printer_sn'] = $params['label_printer_sn'] ?? '';
        $data['label_printer_key'] = $params['label_printer_key'] ?? '';
        $data['longitude'] = $params['longitude'] ?? 0;
        $data['latitude'] = $params['latitude'] ?? 0;
        $data['location'] = $params['location'] ?? '';
        $data['address'] = $params['address'] ?? '';


        return Ota::insert($data);
    }

    /**
     * 删除供应商
     * @param $otaId
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    public static function deleteOne($otaId)
    {
        return self::update(['ota_id'=>$otaId,'status'=>Ota::STATUS_DELETE]);
    }

    /**
     * 取消删除供应商
     * @param $otaId
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    public static function unDeleteOne($otaId)
    {
        return self::update(['ota_id'=>$otaId,'status'=>Ota::STATUS_NORMAL]);
    }

    /**
     * 更新供应商信息
     * @param $params
     * @return \Api\PhpUtils\Mysql\MysqlBase
     * @throws GoodsException
     */
    public static function update($params, $canUnBind = false)
    {

        if(empty($params['ota_id'])) {
            throw new GoodsException(['cus' => GoodsException::EMPTY_OTA_ID]);
        }

        $otaDetail = self::detail($params['ota_id']);
        //检查供应商是否存在
        if (empty($otaDetail)) {
            throw new GoodsException(['cus' => GoodsException::OTA_NOT_EXIST]);
        }


        //检查打印机是否已存在 -- 打印机已被（商家名称）绑定
        if(isset($params['printer_sn']) && $params['printer_sn'] && $otaDetail['printer_sn'] != $params['printer_sn']) {

            if ((new OtaValidate())->is_label_printer_sn($params['printer_sn'])) {
                throw new GoodsException(['cus' => GoodsException::PRINTER_SN_ERROR]);
            }

            $printer = self::list('',$params['printer_sn']);
            if ($printer['total'] > 0) {
                throw new GoodsException(
                    ['cus' => GoodsException::PRINTER_ALREADY_EXIST,'data'=>[$printer['list'][0]['ota_name']]]
                );
            }

            try {
                $FeiPrinter = PrinterFactory::getPrinter('Fei');
                $FeiPrinter->addPrinter([
                    'printer_sn' => $params['printer_sn'],
                    'printer_key' => $params['printer_key'],
                    'ota_name' => $params['ota_name'],
                ]);
            } catch (\Exception $e) {
                throw new GoodsException(['cus' => GoodsException::PRINTER_BIND_ERROR,'data'=>[$e->getMessage()]]);
            }
        }
        //检查标签打印机是否已存在 -- 打印机已被（商家名称）绑定
        if(isset($params['label_printer_sn']) && $params['label_printer_sn'] && $otaDetail['label_printer_sn'] != $params['label_printer_sn']) {

            if (!(new OtaValidate())->is_label_printer_sn($params['label_printer_sn'])) {
                throw new GoodsException(['cus' => GoodsException::PRINTER_SN_ERROR]);
            }
            $printer = self::list('','', '', $params['label_printer_sn']);
            if ($printer['total'] > 0) {
                throw new GoodsException(
                    ['cus' => GoodsException::LABEL_PRINTER_ALREADY_EXIST,'data'=>[$printer['list'][0]['ota_name']]]
                );
            }

            try {
                $FeiPrinter = PrinterFactory::getPrinter('Fei');
                $FeiPrinter->addPrinter([
                    'printer_sn' => $params['label_printer_sn'],
                    'printer_key' => $params['label_printer_key'],
                    'ota_name' => $params['ota_name'],
                ]);
            } catch (\Exception $e) {
                throw new GoodsException(['cus' => GoodsException::PRINTER_BIND_ERROR,'data'=>[$e->getMessage()]]);
            }
        }


        $data = [];
        isset($params['ota_name']) && $data['ota_name'] = $params['ota_name'];
        isset($params['printer_sn']) && $data['printer_sn'] = $params['printer_sn'];
        isset($params['printer_key']) && $data['printer_key'] = $params['printer_key'];
        isset($params['label_printer_sn']) && $data['label_printer_sn'] = $params['label_printer_sn'];
        isset($params['label_printer_key']) && $data['label_printer_key'] = $params['label_printer_key'];
        isset($params['longitude']) && $data['longitude'] = $params['longitude'];
        isset($params['latitude']) && $data['latitude'] = $params['latitude'];
        isset($params['location']) && $data['location'] = $params['location'];
        isset($params['address']) && $data['address'] = $params['address'];
        isset($params['status']) && $data['status'] = $params['status'];

        // 解绑
        if ($canUnBind && !empty($otaDetail['printer_sn']) && empty($params['printer_sn']) && empty($params['printer_key'])) {
            $data['printer_sn'] = $data['printer_key'] = '';
        }

        if ($canUnBind && !empty($otaDetail['label_printer_sn']) && empty($params['label_printer_sn']) && empty($params['label_printer_key'])) {
            $data['label_printer_sn'] = $data['label_printer_key'] = '';
        }

        return Ota::update(
            $data,
            ['ota_id'=>$params['ota_id']]
        );
    }

}