<?php


namespace App\Services\shop;

use App\Models\goods\mysql\GoodsSkuSubShop;
use App\Models\shop\mysql\Shop;
use App\Models\shop\mysql\SubShop;
use Api\PhpUtils\Validate\Validate;
use Api\PhpServices\Idgen\Idgen;

// use Validate\ShopValidate;
use App\Exception\custom\ShopException;
use Api\PhpServices\Sensitive\Sensitive;


class ShopService
{

    /**
     * 添加门店
     *
     */
    public static function addShop($params)
    {
        $lifeAccountId = !empty($params['life_account_id']) ? $params['life_account_id'] : '';
        $phone = !empty($params['phone']) ? $params['phone'] : '';
       
        $name = !empty($params['shop_name']) ? $params['shop_name'] : '';
        $longitude = !empty($params['longitude']) ? $params['longitude'] : '';
        $latitude = !empty($params['latitude']) ? $params['latitude'] : '';
        $address = !empty($params['address']) ? $params['address'] : '';

        if (empty($lifeAccountId)) {
            throw new ShopException(['cus'=>0]);
        }

        if (empty($phone)) {
            throw new ShopException(['cus' => 1]);
        }

        if (empty($name)) {
            throw new ShopException(['cus' => 3]);
        }

        if (self::utf8Strlen($name) > 20) {
            throw new ShopException(['cus' => 8]);
        }


        $detectParams = [
            'businessId' => 1,
            'text' => !empty($name) ? $name : '',
            'scene' => 1,
        ];
        $sensitive = (new Sensitive)->detect($detectParams);
        if (!empty($sensitive['data'])) {
            throw new ShopException(['cus' => 4]);
        }

        //判断店铺重复
        if (!self::isName($name)) {
            throw new ShopException(['cus' => 6]);
        }

        //判断手机号重复
        if (!self::isPhone($phone)) {
            throw new ShopException(['cus' => 7]);
        }

        $shopInfo = Shop::getRecord(['life_account_id' => $lifeAccountId]);
        $shopId = !empty($shopInfo['shop_id']) ? $shopInfo['shop_id'] : '';

        $res = self::getIdgenId(substr($lifeAccountId, -2), 'goods', $count = 1);
        $subShopId = !empty($res[0]) ? $res[0] : '';
        $colums = [
            'sub_shop_id' => $subShopId,
            'life_account_id' => $lifeAccountId,
            'shop_id' => $shopId,
            'shop_name' => $name,
            'longitude' => $longitude,
            'latitude' => $latitude,
            'address' => $address,
            'phone' => $phone,
            'create_time' => date("Y-m-d H:i:s"),
        ];
        $subShop = SubShop::insertRecord($colums);
        return $subShop;
    }

    public static function getShopList($params)
    {
        $lifeAccountId = !empty($params['life_account_id']) ? $params['life_account_id'] : '';
        $phone = !empty($params['phone']) ? $params['phone'] : '';
        $shopId = !empty($params['shop_id']) ? $params['shop_id'] : '';
        $shop_name = !empty($params['shop_name']) ? $params['shop_name'] : '';
        $longitude = !empty($params['longitude']) ? $params['longitude'] : '';
        $latitude = !empty($params['latitude']) ? $params['latitude'] : '';
        $address = !empty($params['address']) ? $params['address'] : '';
        $subShopId = !empty($params['sub_shop_id']) ? $params['sub_shop_id'] : '';
        $appid = !empty($params['appid']) ? $params['appid'] : '';

        if (!empty($appid)) {
            if (empty($lifeAccountId)) {
                 throw new ShopException(['cus' => 0]);
            }
        }

        if (!empty($subShopId)) {
            $where['sub_shop_id'] =  $subShopId;
        }

        if (!empty($shopId)) {
            $where['shop_id'] =  $shopId;
        }

        if (!empty($lifeAccountId)) {
            $where['life_account_id'] =  $lifeAccountId;
        }
 
        $where['ORDER'] = ["create_time" => "DESC"];
        $subShopList = SubShop::getRecords($where);
        return $subShopList;
    }


    /**
     * op后台查询查询
     *
     */
    public static function opShopList($params)
    {
        $params['page'] = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['page_size']) ? $params['page_size'] : 20;
        $subShopId = !empty($params['sub_shop_id']) ? $params['sub_shop_id'] : '';
        $lifeAccountId = !empty($params['life_account_id']) ? $params['life_account_id'] : '';
 
        $page = ($params['page'] - 1) * $limit;
        $where['ORDER'] = ["create_time" => "DESC"];
        $where['LIMIT'] = [$page, $limit];

        if (!empty($subShopId)) {
            $where['sub_shop_id'] =  $subShopId;
        }

        if (!empty($lifeAccountId)) {
            $where['life_account_id'] =  $lifeAccountId;
        }

        $list = SubShop::getRecords($where);
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = SubShop::getCount($where);
        $data = ['result' => $list, 'count' => $count];
        return $data;
    }

    /**
     *
     *
     */
    public static function updateShop($params, $where)
    {
        $name = !empty($params['shop_name']) ? $params['shop_name'] : '';
        $longitude = !empty($params['longitude']) ? $params['longitude'] : '';
        $latitude = !empty($params['latitude']) ? $params['latitude'] : '';
        $address = !empty($params['address']) ? $params['address'] : '';
        $phone = !empty($params['phone']) ? $params['phone'] : '';
        $subShopId = !empty($params['sub_shop_id']) ? $params['sub_shop_id'] : '';
        $lifeAccountId = !empty($params['life_account_id']) ? $params['life_account_id'] : '';
        // if (empty($subShopId)) {
        //     throw new ShopException(['cus' => 9]);
        // }
        $colums = [
            'update_time' => date("Y-m-d H:i:s")
        ];
        if (!empty($name)) {
            $detectParams = [
                'businessId' => 1,
                'text' => !empty($name) ? $name : '',
                'scene' => 1,
            ];
            $sensitive = (new Sensitive)->detect($detectParams);
            if (!empty($sensitive['data'])) {
                throw new ShopException(['cus' => 4]);
            }
            $colums['shop_name'] = $name;
            $subShopInfo = SubShop::getRecord(['shop_name' => $name]);
            //更新
            if (!empty($where['sub_shop_id'])) {
                if (!empty($subShopInfo) && $subShopInfo['sub_shop_id'] != $where['sub_shop_id']) {
                    throw new ShopException(['cus' => 6]);
                }
            }else{
                if (!empty($subShopInfo)) {
                    throw new ShopException(['cus' => 6]);
                }
            }
        }
        
 
        if (!empty($longitude)) {
            $colums['longitude'] = $longitude;
        }

        if (!empty($latitude)) {
            $colums['latitude'] = $latitude;
        }

        if (!empty($address)) {
            $colums['address'] = $address;
        }

        if (!empty($phone)) {
            $colums['phone'] = $phone;
        }

        if (!empty($where['sub_shop_id'])) {
            $subShop = SubShop::updateRecord($colums, $where);
        }else{
            $shopInfo = Shop::getRecord(['life_account_id' => $lifeAccountId]);
            $shopId = !empty($shopInfo['shop_id']) ? $shopInfo['shop_id'] : '';
            $res = self::getIdgenId(substr($lifeAccountId, -2), 'goods', $count = 1);
            $subShopId = !empty($res[0]) ? $res[0] : '';
            $colums = [
                'sub_shop_id' => $subShopId,
                'life_account_id' => $lifeAccountId,
                'shop_id' => $shopId,
                'shop_name' => $name,
                'longitude' => $longitude,
                'latitude' => $latitude,
                'address' => $address,
                'phone' => $phone,
                'create_time' => date("Y-m-d H:i:s"),
            ];
            $subShop = SubShop::insertRecord($colums);
        }
        
        if (empty($subShop)) {
            throw new ShopException(['cus' => 10]);
        }
        return $subShop;
    }


    public static function getShopInfo($params)
    {
        $subShopInfo = SubShop::getRecord($params);
        return $subShopInfo;
    }


    /**
     * 门店名称是否重复
     *
     */
    public static function isName($name = '')
    {
        if (empty($name)) {
            return false;
        }
        $colums = [
            'shop_name' => $name
        ];
        $subShop = SubShop::getRecord($colums);
        if (!empty($subShop)) {
            return false;
        }
        return true;
    }

    /**
     * 门店手机号是否重复
     *
     */
    public static function isPhone($phone = '')
    {
        if (empty($phone)) {
            return false;
        }
        $colums = [
            'phone' => $phone
        ];
        $subShop = SubShop::getRecord($colums);
        if (!empty($subShop)) {
            return false;
        }
        return true;
    }

    /**
     *判断长度
     *
     */
    public static function utf8Strlen($string = null)
    {
        // 将字符串分解为单元
        preg_match_all("/./us", $string, $match);
        // // 返回单元个数
        return count($match[0]);
    }

    /**
     * 通过发号器拿 id （非雪花）
     * number，获取店铺shop_id用生活号id后两位，商品相关的这里是shop_id的后两位
     * @param $number
     * @param $type
     * @param int $count
     * @return array|mixed
     */
    public static function getIdgenId($number, $type, $count = 1)
    {
        $res = Idgen::get(appConfig('idgen.partner'), appConfig('idgen.key'), [], [[
            "type" => $type,
            'number' => (int)$number,
            "count" => $count]]);
        return $res['id_datetime'][$type] ?? [];
    }

    public static function getSnowIdgenId($type, $count = 1)
    {
        $res = Idgen::get(appConfig('idgen.partner'), appConfig('idgen.key'), [[
            "type" => $type,
            "count" => $count]], []);
        return $res['id_snow'][$type] ?? [];
    }

    /**
     * 获取指定 shop_id 下的门店
     * @param $shopId
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    public static function getSubShopList($shopId)
    {
        return SubShop::select("*", ["shop_id" => $shopId]);
    }

    /**
     * 如果 shop_id 为空则补上，在商品创建时候使用
     * @param $subShopIds
     * @param $shopId
     */
    public static function dealShopId($subShopIds, $shopId)
    {
        $subShopList = SubShop::select("*", ["sub_shop_id" => $subShopIds]);
        if (!empty($subShopList)) {
            foreach ($subShopList as $subShop) {
                if (empty($subShop["shop_id"])) {
                    SubShop::updateRecord(["shop_id"=>$shopId], ["sub_shop_id"=>$subShop["sub_shop_id"]]);
                }
            }
        }
    }

    /**
     * 获取商品关联的门店信息
     * @param $goodsSkuId
     * @return \Api\PhpUtils\Mysql\MysqlBase|array
     */
    public static function getRelationShop($goodsSkuId)
    {
        $subShopIds = GoodsSkuSubShop::select("sub_shop_id", ["goods_sku_id"=>$goodsSkuId]);
        $subShopList = [];
        if (!empty($subShopIds)) {
            $subShopIdList = [];
            foreach ($subShopIds as $subShopId) {
                $subShopIdList[] = $subShopId;
            }
            $subShopList = SubShop::select("*", ["sub_shop_id" => $subShopIdList]);
        }
        return $subShopList;
    }
}