<?php


namespace App\Services\marketing;

use App\Models\marketing\mysql\Marketing;
use App\Models\marketing\mysql\MarketingGoods;
use Api\PhpUtils\Validate\Validate;
use Api\PhpServices\Idgen\Idgen;
use App\Exception\custom\MarketingException;
use Api\PhpServices\Sensitive\Sensitive;

class MarketingService
{
    /**
     * 查询
     *
     */
    public static function marketingList($params)
    {
        $params['page'] = !empty($params['page']) ? $params['page'] : 1;
        $limit = !empty($params['page_size']) ? $params['page_size'] : 20;
        $page = ($params['page'] - 1) * $limit;

        if (!empty($params['marketing_name'])) {
            $where['marketing_name'] = $params['marketing_name'];
        }

        if (!empty($params['marketing_id'])) {
            $where['marketing_id'] = $params['marketing_id'];
        }

        if (!empty($params['online_status'])) {
            $where['online_status'] = $params['online_status'];
        }

        $where['ORDER'] = ["create_time" => "DESC"];
        $where['LIMIT'] = [$page, $limit];
        $list = Marketing::getRecords($where);
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = Marketing::getCount($where);
        $data = ['result' => $list,'count' => $count];
        return $data;
    }


    public static function addMarketing($params){

        $marketingName = !empty($params['marketing_name']) ? $params['marketing_name'] : '';
        $firstCommissionRate = !empty($params['first_commission_rate']) ? $params['first_commission_rate'] : '';
        $secondCommissionRate = !empty($params['second_commission_rate']) ? $params['second_commission_rate'] : '';
        $createUserEmail = !empty($params['op_cur_user']) ? $params['op_cur_user'] : '';
        $startTime = !empty($params['start_time']) ? $params['start_time'] : '';
        $endTime = !empty($params['end_time']) ? $params['end_time'] : '';
        $type = !empty($params['type']) ? $params['type'] : 1;
        $goodsSkuId = !empty($params['goods_sku_id']) ? explode(",", $params['goods_sku_id']) : [];


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

        // if (empty($firstCommissionRate)) {
        //     throw new MarketingException(['cus'=>3]);
        // }

        // if (empty($secondCommissionRate)) {
        //     throw new MarketingException(['cus'=>4]);
        // }
 
 
        if (self::utf8Strlen($marketingName) > 40) {
            throw new MarketingException(['cus'=>1]);
        }


        $detectParams = [
            'businessId' => 1,
            'text' => !empty($marketingName) ? $marketingName : '',
            'scene' => 1,
        ];
        $sensitive =  (new Sensitive)->detect($detectParams);
        if (!empty($sensitive['data'])) {
            throw new MarketingException(['cus'=>2]);
        }
 
        // //判断重复
        // if (!self::isName($name)) {
        //     throw new ShopException(['cus'=>6]);
        // }
        //$res = self::getIdgenId(1, 'goods', $count = 1);
        //$stores_id = !empty($res[0]) ? $res[0] : '';

        Marketing::beginTransaction();
        $colums = [
            //'marketing_id' => $marketing_id,
            'marketing_name' => $marketingName,
            'first_commission_rate' => $firstCommissionRate,
            'second_commission_rate' => $secondCommissionRate,
            'create_user_email' => $createUserEmail,
            'good_count' => 0,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'online_status' => 1,
            'type' => $type,
            'update_user_email' => $createUserEmail,
            'update_time' => date("Y-m-d H:i:s"),
            'create_time' => date("Y-m-d H:i:s"),
        ];
        $marketingId = Marketing::insertRecord($colums);
        if (empty($marketingId)) {
            Marketing::rollback();  
            throw new MarketingException(['cus' => 5]);
        }
        $colums = [];
        $goodCount = !empty($goodsSkuId) ? count($goodsSkuId) : 0;

        foreach ($goodsSkuId as $key => $value) {
            $colums[$key]['marketing_id'] = $marketingId;
            $colums[$key]['goods_spu_id'] = $value;
            $colums[$key]['goods_sku_id'] = '';
            $colums[$key]['update_time'] = date("Y-m-d H:i:s");
            $colums[$key]['create_time'] = date("Y-m-d H:i:s");
        }

        $info = MarketingGoods::insertRecord($colums);
        if (empty($info)) {
            Marketing::rollback();  
            throw new MarketingException(['cus' => 5]);
        }

        $srt = Marketing::updateRecord(['good_count' => $goodCount], ['marketing_id' => $marketingId]);
        if (!empty($srt)) {
            Marketing::commit();
            return $srt;
        }else{
            Marketing::rollback();  
            throw new MarketingException(['cus' => 5]);
        }
    }

    /**
     * 更新数据
     *
     */
    public static function updateMarketing($params,$where)
    {
        $where['marketing_id'] = !empty($where['marketing_id']) ? $where['marketing_id'] : '';
        $info = Marketing::updateRecord($params, $where);
        return $info;
    }


    public static function marketingInfo($params)
    {
        $where['marketing_id'] = !empty($params['marketing_id']) ? $params['marketing_id'] : '';
        $info = Marketing::getRecord($where);
        return $info;
    }

   


   /**
    *判断长度
    *
    */
    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] ?? [];
    }
}