<?php

namespace Api\PhpUtils\Common;


class GoodsSkuId
{
    /**
     * 生成加密后的 sku_id
     * id 非雪花算法生成的sku_id
     * category_1_id 一级分类的id，两位，不足两位在十位补零
     * category_2_id 二级分类的id，两位，不足三位在百位补零
     * spu 商品类型，1虚拟商品，2实体商品
     *
     * @param $id
     * @param $category1Id
     * @param $category2Id
     * @param $spuType
     * @return string
     */
    public static function generateGoodSkuId($id, $category1Id, $category2Id, $spuType)
    {
        if (strlen($category1Id) == 1) {
            $category1Id = "0" . $category1Id;
        }
        if (strlen($category2Id) == 2) {
            $category2Id = "0" . $category2Id;
        }
        $idStr = $id . $category1Id . $category2Id . $spuType;
        //转62进制
        $tmp = BaseConvert::decToOther($idStr);

        $len = strlen($tmp);
        $len = $len < 6 ? 6 : $len;
        if ($len % 2 == 1) {
            $tmp = '0' . $tmp;
            $len += 1;
        }
        $tmp = str_pad(strval($tmp), $len < 6 ? 6 : $len, '0', STR_PAD_LEFT);
        $sum = 0;
        for ($i = 0; $i < $len / 2; $i++) {
            $sum *= 137;
            $sum += ord($tmp[$i]) ^ ord($tmp[$len - $i - 1]);
        }
        $code = '';
        $base = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        for ($i = 2; $i > 0; $i--) {
            $idx = $sum % 62;
            $sum = ($sum - $idx) / 62;
            $code = $base[$idx] . $code;
        }

        return $tmp . $code;
    }

    /**
     * 验证 str 是否是合法的 goods_sku_id
     * @param $str
     * @return bool
     */
    public static function validGoodSkuId($str)
    {
        $strlen = strlen($str);

        $chklen = 2;
        $code = substr($str, -$chklen);
        $str = substr($str, 0, $strlen-$chklen);
        $strlen -= $chklen;

        $base = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

        if ($strlen % 2 == 1)
        {
            $str = '0' . $str;
            $strlen += 1;
        }

        $sum = 0;
        $len = $strlen/2;

        for ($i=0; $i<$len; $i++)
        {
            $sum *= 137;
            $sum += ord($str[$i]) ^ ord($str[$strlen-$i-1]);
        }

        $ret = '';

        for ($i=$chklen; $i>0; $i--)
        {
            $idx = $sum % 62;
            $sum = ($sum-$idx) / 62;
            $ret = $base[$idx] . $ret;
        }

        return $ret === $code;
    }
}