<?php
/**
 * @package merchant
 * @Author: Qinii
 * @Date: 2020/5/8
 */

namespace app\common\repositories\store\product;

use app\common\enum\CommonEnum;
use app\common\model\store\order\StoreOrder;
use app\common\model\store\product\Product;
use app\common\model\store\product\ProductContent;
use app\common\model\user\User;
use app\common\repositories\merchant\MerchantRepository;
use app\common\repositories\shared\SharedProsperityRecommendConfigRepository;
use app\common\repositories\store\coupon\StoreCouponRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\store\order\StoreRefundOrderRepository;
use app\common\repositories\store\StoreSeckillActiveRepository;
use app\common\repositories\store\StoreSeckillTimeRepository;
use app\common\repositories\system\attachment\AttachmentRepository;
use app\common\repositories\user\UserRelationRepository;
use app\common\repositories\user\UserVisitRepository;
use app\common\repositories\wechat\RoutineQrcodeRepository;
use app\common\repositories\wechat\WechatQrcodeRepository;
use app\controller\merchant\gong\Goods;
use app\entity\data\store\StoreProductAttrValueChangeLogEntity;
use app\entity\data\store\StoreProductEntity;
use app\traits\ShouxinyiApiRequest;
use crmeb\exceptions\ApiException;
use crmeb\services\QrcodeService;
use crmeb\services\SwooleTaskService;
use FormBuilder\Factory\Elm;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use app\common\repositories\BaseRepository;
use app\common\dao\store\product\ProductDao as dao;
use app\common\repositories\store\StoreCategoryRepository;
use app\common\repositories\store\shipping\ShippingTemplateRepository;
use app\common\repositories\store\StoreBrandRepository;
use think\facade\Log;
use think\facade\Route;

/**
 * Class ProductRepository
 * @package app\common\repositories\store\product
 * @author xaboy
 * @mixin dao
 */
class ProductRepository extends BaseRepository
{

    protected $dao;
    protected $filed = 'is_status,concession_pri,product_id,mer_id,brand_id,unit_name,rate,reply_count,store_info,cate_id,ficti,image,slider_image,store_name,keyword,sort,is_show,sales,price,refusal,cost,ot_price,stock,is_gift_bag,care_count,status,is_used,create_time,seckill,plate_mer_profit,type,icon_type,pension_is,pension';

    /**
     * ProductRepository constructor.
     * @param dao $dao
     */
    public function __construct(dao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param int $id
     * @param int $merId
     * @return mixed
     */
    public function CatExists(int $id)
    {
        return (app()->make(StoreCategoryRepository::class))->merExists(0, $id);
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/20
     * @param $ids
     * @param int $merId
     * @return bool
     */
    public function merCatExists($ids, int $merId)
    {
        if (!is_array($ids ?? '')) return true;
        foreach ($ids as $id) {
            if (!(app()->make(StoreCategoryRepository::class))->merExists($merId, $id))
                return false;
        }
        return true;
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param int $merId
     * @param int $id
     * @return mixed
     */
    public function merShippingExists(int $merId, int $id)
    {
        $make = app()->make(ShippingTemplateRepository::class);
        return $make->merExists($merId, $id);
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param int $id
     * @return mixed
     */
    public function merBrandExists(int $id)
    {
        $make = app()->make(StoreBrandRepository::class);
        return $make->meExists($id);
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param int $merId
     * @param int $id
     * @return bool
     */
    public function merExists(?int $merId, int $id)
    {
        return $this->dao->merFieldExists($merId, $this->getPk(), $id);
    }

    public function merDeleteExists(int $merId, int $id)
    {
        return $this->dao->getDeleteExists($merId, $id);
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param int $merId
     * @param int $id
     * @return bool
     */
    public function apiExists(?int $merId, int $id)
    {
        return $this->dao->apiFieldExists($merId, $this->getPk(), $id);
    }

    /**
     * @param int $merId
     * @param int $tempId
     * @return bool
     * @author Qinii
     */
    public function merTempExists(int $merId, int $tempId)
    {
        return $this->dao->merFieldExists($merId, 'temp_id', $tempId);
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param array $data
     */
    public function create(array $data)
    {
        return Db::transaction(function () use ($data) {
            if ($data['extension_type'] != 1) {
                $base_commission = Db::name('system_config_value')->where('config_key', 'base_commission')->where('mer_id', $data['mer_id'])->value('value');
                if ($base_commission < 5) {
                    $base_commission = 5;
                }
                foreach ($data['attrValue'] as &$value) {
                    $value['extension_one'] = $base_commission;
                }
            }

            if (is_array($data['icon_type'])) {
                $data['icon_type'] = $data['icon_type'] ? json_encode($data['icon_type'], JSON_UNESCAPED_UNICODE) : null;
            }

            $pension = bcsub($data['attrValue'][0]['price'], bcmul($data['attrValue'][0]['price'], $data['commission'], 2), 2);
            if ($data['pension'] > $pension) {
                return ['code' => 201, 'msg' => '养老金金额和佣金金额总和不能超过商品单价'];
            }
            $param['attr'] = $data['attr'] ?? '';
            $param['attrValue'] = $data['attrValue'] ?? '';
            $param['cate'] = $data['mer_cate_id'] ?? '';
            $content = $data['content'];
            $data['slider_image'] = implode(',', $data['slider_image']);
            $give_coupon_ids = '';
            if (isset($data['give_coupon_ids']) && !empty($data['give_coupon_ids'])) {
                $gcoupon_ids = array_unique($data['give_coupon_ids']);
                $give_coupon_ids = implode(',', $gcoupon_ids);
            }
            $data['give_coupon_ids'] = $give_coupon_ids;
            unset($data['attr']);
            unset($data['attrValue']);
            unset($data['content']);
            unset($data['mer_cate_id']);
            $data['dc_id'] = Db::name('merchant')->where('mer_id', $data['mer_id'])->value('dc_id');
            if ($data['type'] == 7) $data['temp_id'] = 105;
            $result = $this->dao->create($data);
            $product_id = $result['product_id'];
            $settleParams = $this->settleParams($param, $product_id, $data['mer_id']);
            $this->save($product_id, $settleParams, $content);
            return ['code' => 200, 'msg' => $product_id];
        });
    }

    /**
     * TODO 秒杀商品创建
     * @param array $data
     * @author Qinii
     * @day 2020-08-04
     */
    public function createSeckill(array $data)
    {
        $dat = [
            'start_day'      => $data['start_day'],
            'end_day'        => $data['end_day'],
            'start_time'     => (int)$data['start_time'],
            'end_time'       => (int)$data['end_time'],
            'mer_id'         => $data['mer_id'],
            'status'         => 1,
            'once_pay_count' => (int)$data['once_pay_count'],
            'all_pay_count'  => (int)$data['all_pay_count'],
        ];
        unset($data['start_day']);
        unset($data['end_day']);
        unset($data['start_time']);
        unset($data['end_time']);
        unset($data['once_pay_count']);
        unset($data['all_pay_count']);
        Db::transaction(function () use ($data, $dat) {
            $dat['product_id'] = $this->create($data);
            app()->make(StoreSeckillActiveRepository::class)->create($dat);
        });
    }

    /**
     * TODO 基础更新
     * @param int $id
     * @param array $data
     * @return int
     * @author Qinii
     * @day 2020-06-04
     */
    public function baseUpdate(int $id, array $data)
    {
        return $this->dao->update($id, $data);
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param int $id
     * @param array $data
     */
    public function update(int $id, array $data, $merId)
    {
        Db::transaction(function () use ($id, $data, $merId) {
            if ($data['extension_type'] != 1) {
                $base_commission = Db::name('system_config_value')->where('config_key', 'base_commission')->where('mer_id', $merId)->value('value');
                if ($base_commission < 5) {
                    $base_commission = 5;
                }
                foreach ($data['attrValue'] as &$value) {
                    $value['extension_one'] = $base_commission;
                }
            }
            if (is_array($data['icon_type'])) {
                $data['icon_type'] = $data['icon_type'] ? json_encode($data['icon_type'], JSON_UNESCAPED_UNICODE) : null;
            }
            $param['attr'] = $data['attr'] ?? '';
            $param['attrValue'] = $data['attrValue'] ?? '';
            $param['cate'] = $data['mer_cate_id'] ?? '';
            $content = $data['content'];
            $data['slider_image'] = implode(',', $data['slider_image']);
            $give_coupon_ids = '';
            if (isset($data['give_coupon_ids']) && !empty($data['give_coupon_ids'])) {
                $gcoupon_ids = array_unique($data['give_coupon_ids']);
                $give_coupon_ids = implode(',', $gcoupon_ids);
            }
            $data['give_coupon_ids'] = $give_coupon_ids;
            unset($data['attr'], $data['attrValue'], $data['content'], $data['mer_cate_id']);

            (app()->make(ProductAttrRepository::class))->clearAttr($id);
            (app()->make(ProductAttrValueRepository::class))->clearAttr($id);
            (app()->make(ProductContentRepository::class))->clearAttr($id);
            (app()->make(ProductCateRepository::class))->clearAttr($id);

            $data['dc_id'] = Db::name('merchant')->where('mer_id', $merId)->value('dc_id');
            $settleParams = $this->settleParams($param, $id, $merId, $data['type']);
            $this->save($id, $settleParams, $content, $data);
        });
    }

    public function updateSeckill(int $id, array $data, $merId)
    {
        $dat = [
            'start_day'      => $data['start_day'],
            'end_day'        => $data['end_day'],
            'start_time'     => $data['start_time'] . ':00:00',
            'end_time'       => $data['end_time'] . ':00:00',
            'status'         => 1,
            'once_pay_count' => $data['once_pay_count'],
            'all_pay_count'  => $data['all_pay_count'],
        ];
        unset($data['start_day']);
        unset($data['end_day']);
        unset($data['start_time']);
        unset($data['end_time']);
        unset($data['once_pay_count']);
        unset($data['all_pay_count']);
        Db::transaction(function () use ($data, $dat, $id, $merId) {
            $this->update($id, $data, $merId);
            app()->make(StoreSeckillActiveRepository::class)->updateByProduct($id, $dat);
        });
    }

    public function destory($id)
    {
        (app()->make(ProductAttrRepository::class))->clearAttr($id);
        (app()->make(ProductAttrValueRepository::class))->clearAttr($id);
        (app()->make(ProductContentRepository::class))->clearAttr($id);
        (app()->make(ProductCateRepository::class))->clearAttr($id);
        $this->dao->delete($id, true);
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/20
     * @param $id
     * @param $spec_type
     * @param $settleParams
     * @param $content
     * @return int
     */
    public function save($id, $settleParams, $content, $data = [])
    {

        if (isset($settleParams['cate']))
            (app()->make(ProductCateRepository::class)->insert($settleParams['cate']));
        if (isset($settleParams['attr']))
            (app()->make(ProductAttrRepository::class))->insert($settleParams['attr']);
        if (isset($settleParams['attrValue']))
            (app()->make(ProductAttrValueRepository::class))->insert($settleParams['attrValue']);
        $this->dao->createContent($id, ['content' => $content]);
        $data['price'] = $settleParams['data']['price'];
        $data['ot_price'] = $settleParams['data']['ot_price'];
        $data['dc_price'] = $settleParams['data']['dc_price'];
        $data['cost_price'] = $settleParams['data']['cost_price'] ?? 0;
        $data['gong_sku_id'] = $settleParams['data']['gong_sku_id'] ?? 0;
        $data['cost'] = $settleParams['data']['cost'];
        $data['stock'] = $settleParams['data']['stock'];
        $data['concession_pri'] = $settleParams['data']['concession_pri'];
        return $this->dao->update($id, $data);
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/18
     * @param int $id
     * @param array $data
     * @return int
     */
    public function adminUpdate(int $id, array $data)
    {
        Db::transaction(function () use ($id, $data) {
            (app()->make(ProductContentRepository::class))->clearAttr($id);
            $this->dao->createContent($id, ['content' => $data['content']]);
            unset($data['content']);
            return $this->dao->update($id, $data);
        });
    }


    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param array $data
     * @param int|null $id
     * @return array
     */
    public function settleParams(array $data, int $id, $merId, $type = 0)
    {
        $result = $attr_name = [];
        if (isset($data['cate']) && is_array($data['cate'])) {
            foreach ($data['cate'] as $value) {
                $result['cate'][] = [
                    'product_id'  => $id,
                    'mer_cate_id' => $value,
                    'mer_id'      => $merId,
                ];
            }
        }

        if (isset($data['attr']) && is_array($data['attr'])) {
            foreach ($data['attr'] as $value) {
                $result['attr'][] = [
                    'type'        => 0,
                    'product_id'  => $id,
                    "attr_name"   => $value['value'],
                    'attr_values' => implode('-!-', $value['detail']),
                ];
            }
        }
        $extension_status = systemConfig('extension_status');
        $pric = $stock = $ot_price = $cost = $dc_price = $concession_pri = 0;
        if (isset($data['attrValue']) && is_array($data['attrValue'])) {
            foreach ($data['attrValue'] as $value) {
                $value['extension_one'] = $value['extension_one'] ?? 0;
                $value['cost'] = bcsub($value['price'], bcmul($value['price'], $value['extension_one'] / 100, 2), 2);
                $value['gong_mer_profit'] = bcmul($value['price'], $value['extension_one'] / 100, 2);
                $value['gong_market_price'] = bcadd($value['cost'], $value['gong_mer_profit'], 2);
                $value['plate_mer_profit'] = $value['gong_mer_profit'];

                $sku = '';
                if (isset($value['detail']) && is_array($value['detail'])) {
                    $sku = implode(',', $value['detail']);
                }
                $product_data = Db::name('store_product')->where('product_id', $id)->value('spu_id');
                if ($product_data) {
                    if (!in_array($merId, ['319', '320', '321', '322', '323', '324', '325', '326', '327', '328'])) {
                        if ($value['price'] < $value['cost']) {
                            throw new ValidateException('售价不得小于成本价');
                        }
                        if ($type == 5) {
//                            if ($value['dacang_price'] < $value['cost']) {
//                                throw new ValidateException('大仓价格不得小于成本价');
//                            }
                        }
                        if ($value['ot_price'] < $value['cost']) {
                            throw new ValidateException('原价不得小于成本价');
                        }
                    }
                }
                $unique = $this->setUnique($id, $sku, 0);
                $value['dacang_price'] = isset($value['dacang_price']) ? (($value['dacang_price'] < 0) ? 0 : $value['dacang_price']) : 0;
                if ($product_data) {
                    $result['attrValue'][] = [
                        'detail'   => json_encode($value['detail'] ?? ''),
                        "bar_code" => $value["bar_code"] ?? '',
                        "image"    => $value["image"],
                        "cost"     => $value['cost'] ? (($value['cost'] < 0) ? 0 : $value['cost']) : 0,
                        "price"    => $value['price'] ? (($value['price'] < 0) ? 0 : $value['price']) : 0,
                        "volume"   => $value['volume'] ? (($value['volume'] < 0) ? 0 : $value['volume']) : 0,
                        "weight"   => $value['weight'] ? (($value['weight'] < 0) ? 0 : $value['weight']) : 0,
                        "stock"    => $value['stock'] ? (($value['stock'] < 0) ? 0 : $value['stock']) : 0,
                        "sales"    => (isset($value['sales']) && $value['sales'] && $value['sales'] > 0) ? $value['sales'] : 0,

                        "ot_price"      => $value['ot_price'] ? (($value['ot_price'] < 0) ? 0 : $value['ot_price']) : 0,
                        "extension_one" => $extension_status ? ($value['extension_one'] ?? 0) : 0,
                        "extension_two" => $extension_status ? ($value['extension_two'] ?? 0) : 0,
                        "product_id"    => $id,
                        "type"          => 0,
                        "sku"           => $sku,
                        "unique"        => $unique,
                        "dacang_price"  => $value['dacang_price'],
                        "cost_price"    => $value['cost_price'],
                        "gong_sku_id"   => $value['gong_sku_id'],
                        "pension_num"   => 0,
                        "share_num"     => 0,
                        "stock_num"     => 0,
                        "shares_num"    => 0,
                        'gong_mer_profit' => $value['gong_mer_profit'] ?? 0.00,
                        'gong_market_price' => $value['gong_market_price'] ?? 0.00,
                        'plate_mer_profit' => $value['plate_mer_profit'] ?? 0.00,
                    ];
                } else {
                    $result['attrValue'][] = [
                        'detail'        => json_encode($value['detail'] ?? ''),
                        "bar_code"      => $value["bar_code"] ?? '',
                        "image"         => $value["image"],
                        "cost"          => $value['cost'] ? (($value['cost'] < 0) ? 0 : $value['cost']) : 0,
                        "price"         => $value['price'] ? (($value['price'] < 0) ? 0 : $value['price']) : 0,
                        "volume"        => $value['volume'] ? (($value['volume'] < 0) ? 0 : $value['volume']) : 0,
                        "weight"        => $value['weight'] ? (($value['weight'] < 0) ? 0 : $value['weight']) : 0,
                        "stock"         => $value['stock'] ? (($value['stock'] < 0) ? 0 : $value['stock']) : 0,
                        "sales"         => (isset($value['sales']) && $value['sales'] && $value['sales'] > 0) ? $value['sales'] : 0,
                        "ot_price"      => $value['ot_price'] ? (($value['ot_price'] < 0) ? 0 : $value['ot_price']) : 0,
                        "extension_one" => $extension_status ? ($value['extension_one'] ?? 0) : 0,
                        "extension_two" => $extension_status ? ($value['extension_two'] ?? 0) : 0,
                        "product_id"    => $id,
                        "type"          => 0,
                        "sku"           => $sku,
                        "unique"        => $unique,
                        "dacang_price"  => $value['dacang_price'],
                        "pension_num"   => (isset($value['pension_num']) && $value['pension_num'] !== '') ? $value['pension_num'] : 0,
                        "share_num"     => (isset($value['share_num']) && $value['share_num'] !== '') ? $value['share_num'] : 0,
                        "stock_num"     => (isset($value['stock_num']) && $value['stock_num'] !== '') ? $value['stock_num'] : 0,
                        "shares_num"    => (isset($value['shares_num']) && $value['shares_num'] !== '') ? $value['shares_num'] : 0,
                        'gong_mer_profit' => $value['gong_mer_profit'] ?? 0.00,
                        'gong_market_price' => $value['gong_market_price'] ?? 0.00,
                        'plate_mer_profit' => $value['plate_mer_profit'] ?? 0.00,
                    ];
                }
                if (!$pric) $pric = $value['price'];
                if (!$ot_price) $ot_price = $value['ot_price'];
                if (!$dc_price) $dc_price = $value['dacang_price'];
                if (!$cost) $cost = $value['cost'];
                if (!$concession_pri) $concession_pri = $value['plate_mer_profit'] ? (($value['plate_mer_profit'] < 0) ? 0 : $value['plate_mer_profit']) : 0;
                $ot_price = ($ot_price > $value['ot_price']) ? $value['ot_price'] : $ot_price;

                $concession_pri = ($pric > $value['price']) ? $value['plate_mer_profit'] : $concession_pri;
                $pric = ($pric > $value['price']) ? $value['price'] : $pric;

                $dc_price = ($dc_price > $value['dacang_price']) ? $value['dacang_price'] : $dc_price;

                $cost = ($cost > $value['cost']) ? $value['cost'] : $cost;

                $stock = $stock + $value['stock'];
            }
        }
        $result['data'] = ['price' => $pric, 'stock' => $stock, 'ot_price' => $ot_price, 'cost' => $cost, 'dc_price' => $dc_price,'concession_pri'=>$concession_pri];
        return $result;
    }


    /**
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param int $id
     * @param string $sku
     * @param int $type
     * @return string
     */
    public function setUnique(int $id, $sku, int $type)
    {
        $unique = substr(md5($sku . $id), 12, 11) . $type;
        $has = (app()->make(ProductAttrValueRepository::class))->merUniqueExists(null, $unique);
        return $has ? false : $unique;
    }


    /**
     * @Author:Qinii
     * @Date: 2020/5/18
     * @param $id
     * @return array
     */
    public function get($id)
    {
        $with = ['attr', 'attrValue', 'content', 'merCateId.category', 'storeCategory', 'brand', 'temp', 'seckillActive'];
        $data = $this->dao->getWhere(['product_id' => $id], '*', $with)->append(['seckill_status']);
        $where = [['coupon_id', 'in', $data['give_coupon_ids']]];
        $data['coupon'] = app()->make(StoreCouponRepository::class)->selectWhere($where, 'coupon_id,title')->toArray();
        $arr = [];
        if (isset($data['merCateId'])) {
            foreach ($data['merCateId'] as $i) {
                $arr[] = $i['mer_cate_id'];
            }
        }
        $data['mer_cate_id'] = $arr;
        foreach ($data['attr'] as $k => $v) {
            $data['attr'][$k] = [
                'value'  => $v['attr_name'],
                'detail' => $v['attr_values']
            ];
        }
        if ($data['product_type'] == 1)
            $make = app()->make(ProductAttrValueRepository::class);
        foreach ($data['attrValue'] as $key => $item) {
            $sku = explode(',', $item['sku']);
            if ($data['product_type'] == 1)
                $item['old_stock'] = $make->search(['product_id' => $data['old_product_id'], 'sku' => $item['sku']])->value('stock');
            foreach ($sku as $k => $v) {
                $item['value' . $k] = $v;
            }
            $data['attrValue'][$key] = $item;
        }
        foreach ($data['attrValue'] as $k => &$v) {
            $v['dacang_cost_price'] = bcadd(bcmul($v['cost_price'], 0.06, 2), $v['cost_price'], 2);
            $v['no_dacang_cost_price'] = bcadd(bcmul($v['cost_price'], 0.1, 2), $v['cost_price'], 2);
        }
        $content = $data['content']['content'];
        unset($data['content']);
        $data['content'] = $content;
        return $data;
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/18
     * @param $type
     * @param int|null $merId
     * @return array
     */
    public function switchType($type, ?int $merId = 0, $productType = 0, $is_gift_bag = 0)
    {
        $stock = 0;
        if ($merId) $stock = merchantConfig($merId, 'mer_store_stock');
        switch ($type) {
            case 1:
                $where = ['is_show' => 1, 'status' => 1, 'mer_status' => 1];
                break;
            case 2:
                $where = ['is_show' => 0, 'status' => 1];
                if (!$merId && $productType == 0) $where['is_gift_bag'] = 0;
                break;
            case 3:
                $where = ['is_show' => 1, 'stock' => 0, 'status' => 1];
                break;
            case 4:
                $where = ['is_show' => 1, 'stock' => is_int($stock) ? $stock : 0, 'status' => 1];
                break;
            case 5:
                $where = ['soft' => true];
                break;
            case 6:
                $where = ['status' => 0, 'is_gift_bag' => $is_gift_bag];
                break;
            case 7:
                $where = ['status' => -1, 'is_gift_bag' => $is_gift_bag];
                break;
            default:
                $where = ['is_show' => 1, 'status' => 1];
                break;
        }
        if ($productType == 0) {
            $where['product_type'] = $productType;
        }
        if ($productType == 1) {
            $where['product_type'] = $productType;
        }
        if ($productType == 3) {
            $where['is_gift_bag'] = 1;
        }
        return $where;
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/18
     * @param int|null $merId
     * @return array
     */
    public function getFilter(?int $merId, $name = '商品', $productType = 0, $is_gift_bag = 0)
    {

        $result = [];
        $result[] = [
            'type'  => 1,
            'name'  => '出售中' . $name,
            'count' => $this->dao->search($merId, $this->switchType(1, $merId, $productType))->whereNull('spu_id')->count()
        ];
        $result[] = [
            'type'  => 2,
            'name'  => '仓库中' . $name,
            'count' => $this->dao->search($merId, $this->switchType(2, $merId, $productType))->whereNull('spu_id')->count()
        ];
        if ($merId) {
            $result[] = [
                'type'  => 3,
                'name'  => '已售罄' . $name,
                'count' => $this->dao->search($merId, $this->switchType(3, $merId, $productType))->whereNull('spu_id')->count()
            ];
            $result[] = [
                'type'  => 4,
                'name'  => '警戒库存',
                'count' => $this->dao->search($merId, $this->switchType(4, $merId, $productType))->whereNull('spu_id')->count()
            ];
            $result[] = [
                'type'  => 5,
                'name'  => '回收站' . $name,
                'count' => $this->dao->search($merId, $this->switchType(5, $merId, $productType))->whereNull('spu_id')->count()
            ];
        }
        $result[] = [
            'type'  => 6,
            'name'  => '待审核' . $name,
            'count' => $this->dao->search($merId, $this->switchType(6, $merId, $productType, $is_gift_bag))->whereNull('spu_id')->count()
        ];
        $result[] = [
            'type'  => 7,
            'name'  => '审核未通过' . $name,
            'count' => $this->dao->search($merId, $this->switchType(7, $merId, $productType, $is_gift_bag))->whereNull('spu_id')->count()
        ];
        return $result;
    }

    public function getGongFilter(?int $merId, $name = '商品', $productType = 0)
    {
        $make = app()->make(Goods::class);
        $gongProduct439 = $make->getJoinProduct439();
        if ($merId == 496) {
            // 出售中
            $result[] = [
                'type'  => 1,
                'name'  => '出售中' . $name,
                'count' => $this->dao->search($merId, $this->switchType(1, $merId, $productType))->whereIn('spu_id', $gongProduct439)->whereNotNull('spu_id')->count()
            ];
            // 仓库中
            $result[] = [
                'type'  => 2,
                'name'  => '仓库中' . $name,
                'count' => $this->dao->search($merId, $this->switchType(2, $merId, $productType))->whereIn('spu_id', $gongProduct439)->whereNotNull('spu_id')->count()
            ];
            return $result;
        }
        // 出售中
        $result[] = [
            'type'  => 1,
            'name'  => '出售中' . $name,
            'count' => $this->dao->search($merId, $this->switchType(1, $merId, $productType))->whereNotIn('spu_id', $gongProduct439)->whereNotNull('spu_id')->count()
        ];
        // 仓库中
        $result[] = [
            'type'  => 2,
            'name'  => '仓库中' . $name,
            'count' => $this->dao->search($merId, $this->switchType(2, $merId, $productType))->whereNotIn('spu_id', $gongProduct439)->whereNotNull('spu_id')->count()
        ];
        return $result;
    }

    /**
     * TODO 商户商品列表
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param int $merId
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public function getList(?int $merId, array $where, int $page, int $limit)
    {
        $query = $this->dao->search($merId, $where)->whereNull('spu_id')->with(['merCateId.category', 'storeCategory', 'brand']);
        $count = $query->count($this->dao->getPk());
        $list = $query->page($page, $limit)->setOption('field', [])->field($this->filed)->select();
        $list->append(['max_extension', 'min_extension']);
        return compact('count', 'list');
    }

    public function getGongProductList(?int $merId, array $where, int $page, int $limit)
    {

        $make = app()->make(Goods::class);
        $gongProduct439 = $make->getJoinProduct439();

        $query = $this->dao->search($merId, $where)->whereNotNull('spu_id')->with(['attrValue']);

        if ($merId == 496) {
            $count = $query->whereIn('spu_id', $gongProduct439)->count($this->dao->getPk());
            $list = $query->whereIn('spu_id', $gongProduct439)->page($page, $limit)->setOption('field', [])->field($this->filed)->select();
        } else {
            $count = $query->whereNotIn('spu_id', $gongProduct439)->count($this->dao->getPk());
            $list = $query->whereNotIn('spu_id', $gongProduct439)->page($page, $limit)->setOption('field', [])->field($this->filed)->select();
        }

        foreach ($list as $key => $value) {
            foreach ($value['attrValue'] as &$v) {
                $v['min_market_price'] = bcsub($v['gong_market_price'], $v['gong_mer_profit'], 2);
            }
            $list[$key]['spec_type'] = count($value['attrValue']) > 1;
        }
        return compact('count', 'list');
    }

    /**
     * TODO 商户秒杀商品列表
     * @param int|null $merId
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     * @author Qinii
     * @day 2020-08-04
     */
    public function getSeckillList(?int $merId, array $where, int $page, int $limit)
    {
        $make = app()->make(StoreOrderRepository::class);
        $query = $this->dao->search($merId, $where)->with(['merCateId.category', 'storeCategory', 'brand', 'seckillActive']);
        $count = $query->count($this->dao->getPk());
        $list = $query->page($page, $limit)->setOption('field', [])->field($this->filed)->select()
            ->each(function ($item) use ($make) {
                $item['sales'] = $make->seckillOrderCounut($item['product_id']);
                return $item;
            });
        $list->append(['seckill_status']);
        return compact('count', 'list');
    }

    /**
     * TODO 平台商品列表
     * @Author:Qinii
     * @Date: 2020/5/11
     * @param int $merId
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public function getAdminList(?int $merId, array $where, int $page, int $limit)
    {
        $query = $this->dao->search($merId, $where)->with(['merCateId.category', 'storeCategory', 'brand', 'merchant']);
        $count = $query->count($this->dao->getPk());
        $list = $query->page($page, $limit)->select();
        foreach ($list as &$v) {
            $v['is_used'] = (int)$v['is_used'];
        }
        $list->append(['max_extension', 'min_extension']);
        return compact('count', 'list');
    }

    /**
     * TODO 平台秒杀商品列表
     * @param int|null $merId
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     * @author Qinii
     * @day 2020-08-04
     */
    public function getAdminSeckillList(?int $merId, array $where, int $page, int $limit)
    {
        $make = app()->make(StoreOrderRepository::class);
        $query = $this->dao->search($merId, $where)->with(['merCateId.category', 'storeCategory', 'brand', 'merchant', 'seckillActive']);
        $count = $query->count($this->dao->getPk());
        $list = $query->page($page, $limit)->setOption('field', [])->field($this->filed)->select()
            ->each(function ($item) use ($make) {
                $item['sales'] = $make->seckillOrderCounut($item['product_id']);
                return $item;
            });;
        $list->append(['seckill_status']);
        return compact('count', 'list');
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/28
     * @param array $where
     * @param int $page
     * @param int $limit
     * @param $userInfo
     * @return array
     */
    public function getApiSearch($merId, array $where, int $page, int $limit, $userInfo, $type439 = false)
    {
        unset($where['order']);
        if (isset($where['price_on']) && $where['price_on'] != '') $where['price'] = [$where['price_asc'], $where['price_desc']];
        if (isset($where['brand_id']) && $where['brand_id'] != '') $where['brand_id'] = explode(',', $where['brand_id']);
        unset($where['price_on'], $where['price_off']);

        $where = array_merge($where, $this->dao->productShow());

        $cateList = [];
        if(isset($where['cate_id']) && $where['cate_id']!= ''){
            $cate_name = Db::name('store_category')->where('pid', 564)->where('store_category_id', $where['cate_id'])->value('cate_name');
            $url = "https://dc-api.hxxfb.com/douhuomallCategory/getCateAll";
            $result = curlGet($url);
            if (!isset($result['status']) || $result['status'] != 200) {
                $cateList = [$where['cate_id']];
            }else{
                $cateIds = [];
                foreach($result['data'] as $item){
                    if($item['cateName'] == $cate_name){
                        $cateIds = explode(",", $item['cateIds']);
                        break;
                    }
                }
                $cateList = array_merge([$where['cate_id']], $cateIds);
            }
            unset($where['cate_id']);
        }

        //搜索记录
        if ($userInfo && isset($where['keyword']) && !empty($where['keyword'])){
            // log::info("======sousuojilu====");
            app()->make(UserVisitRepository::class)->searchProduct($userInfo['uid'], $where['keyword']);
        }


        $query = $this->dao->search($merId, $where)->with(['merchant']);
        $query->with(['issetCoupon']);

        if ($type439 == true) {
            $make2 = app()->make(Goods::class);
            $gongProduct439 = $make2->getJoinProduct439();

            $query->where(function ($query2) use ($gongProduct439) {
                $query2->whereNotIn('spu_id', $gongProduct439)->whereOr("spu_id is null");
            });
        }

        if(count($cateList) > 0){
            $query->where(function ($query2) use ($cateList) {
                $query2->whereIn('cate_id', $cateList)->whereOr("cate_id is null");
            });
        }

        $count = $query->count($this->dao->getPk());
//        echo DB::getlastsql();die;
        $list = $query->page($page, $limit)->setOption('field', [])->field($this->filed)->select();

        $list->each(function ($item) {
            $item['sales'] = $item['sales'] + $item['ficti'];
            unset($item['ficti']);
            $item['yanglao'] = $this->yanglaojin($item['product_id']);
            $item['icon_type_map'] = [
                1 => 'https://api.hxxfb.com/share/xcx/icon/icon_tjms.png'
            ];
            return $item;
        });

        if ($this->getUserIsPromoter($userInfo)) $list = $list->each(function ($item) {
            return $item['max_extension'] = $item->max_extension;
        });


        return compact('count', 'list');
    }

    /**
     * TODO 秒杀列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     * @author Qinii
     * @day 2020-08-04
     */
    public function getApiSeckill(array $where, int $page, int $limit)
    {
        $field = 'Product.product_id,Product.mer_id,is_new,keyword,brand_id,image,store_name,sort,rate,reply_count,sales,price,cost,ficti,ot_price,stock,extension_type,care_count,unit_name,create_time';

        $make = app()->make(StoreOrderRepository::class);
        $res = app()->make(StoreSeckillTimeRepository::class)->getBginTime($where);
        $count = 0;
        $list = [];

        if ($res) {
            $where = [
                'start_time' => $res['start_time'],
                'end_time'   => $res['end_time'],
                'day'        => date('Y-m-d', time())
            ];
            $query = $this->dao->seckillSearch($where)->with(['seckillActive']);
            $count = $query->count();
            $list = $query->page($page, $limit)->setOption('field', [])->field($field)->select()
                ->each(function ($item) use ($make) {
                    $item['sales'] = $make->seckillOrderCounut($item['product_id']);
                    $item['stop'] = $item->end_time;
                    //unset($item['seckillActive']);
                    unset($item['ficti']);
                    return $item;
                });
        }
        return compact('count', 'list');
    }

    /**
     * TODO 平台礼包列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     * @author Qinii
     * @day 2020-06-01
     */
    public function getBagList(array $where, int $page, int $limit)
    {
        $query = $this->dao->search(null, $where)->with(['merCateId.category', 'storeCategory', 'brand']);
        $count = $query->count($this->dao->getPk());
        $list = $query->page($page, $limit)->setOption('field', [])->field($this->filed)->select();

        return compact('count', 'list');
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/28
     * @param array $where
     * @return mixed
     */
    public function getBrandByCategory(array $where)
    {
        $query = $this->dao->search(null, $where);
        return $query->group('brand_id')->column('brand_id');
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param $id
     * @param $userInfo
     */
    public function detail($id, $userInfo)
    {
        $field = 'product_id,mer_id,image,slider_image,store_name,store_info,unit_name,price,cost,ot_price,stock,sales,ficti,video_link,product_type,type,dc_price,seckill,spu_id';
        $with = [
            'attr', 'attrValue', 'content', 'topReply.orderProduct' => function ($query) {
                $query->field('reply_id,uid,nickname,merchant_reply_content,avatar,order_product_id,product_id,product_score,service_score,postage_score,comment,pics,create_time');
            }, 'merchant.recommend'
        ];
        $is_seckill = Db::name('store_product')->where('product_id', $id)->value('seckill');
        if ($is_seckill == 1) {
            $is_hide = 1;
        } else {
            $is_hide = 0;
        }
        $res = $this->dao->getWhere(['is_show' => 1, 'status' => 1, 'product_id' => $id, 'is_used' => 1, 'is_hide' => $is_hide], $field, $with);
        if (!$res) return null;
        if ($userInfo) {
            $isRelation = app()->make(UserRelationRepository::class)->getUserRelation(['type_id' => $res['product_id'], 'type' => 1], $userInfo['uid']);
            if ($this->getUserIsPromoter($userInfo)) $res->append(['max_extension', 'min_extension']);
        }

        $res['isRelation'] = $isRelation ?? false;
        $res['sku'] = $this->detailAttrValue($res['attrValue'], $userInfo, $res['product_type']);
        $res['sales'] = $res['sales'] + $res['ficti'];
        $res['replayData'] = app()->make(ProductReplyRepository::class)->getReplyRate($res['product_id']);

        // 应前端需求 加上对应价格sku的unique
        $res['unique'] = Db::name('store_product_attr_value')->where('product_id', $id)->where('price', $res['price'])->value('unique');
        if ($res['topReply']) {
            $res['topReply']['sku'] = $res['topReply']['orderProduct']['cart_info']['productAttr']['sku'];
            unset($res['topReply']['orderProduct']);
        }

        unset($res['attrValue']);
        unset($res['ficti']);
        unset($res['attr']);
        unset($res['attr']);

        $res['attr'] = $this->detailAttr($res['attr']);

        $k=$this->pvParm($res['product_id']);


        $res['jfduihuan']=0;
        $res['jdduihuan']=0;

        $res['yanglao']=($k['yanglao']);
        if($res['mer_id'] != 496){
            if($res['mer_id'] != 491){
                $res['jfduihuan']=($k['jfduihuan']??0);
                $res['jdduihuan']=($k['jdduihuan']??0);
            }
        }

        if($res['mer_id'] == 496){

            $s = 0;

            if($res['price']==1180){
                $s = 1000;
            }else if($res['price']==10620){
                $s = 9000;
            }else if($res['price']==11800){
                $s = 10000;
            }else if($res['price'] == 2360){
                $s= 2000;
            }else if($res['price'] == 9440){
                $s = 8000;
            }else if($res['price'] == 5900){
                $s = 5000;
            }

            $res['yanglao'] = bcmul($s, 0.035, 2);
        }


        // 共富商品处理
        if ($res['mer_id'] == 3447) {
            $res['yanglao'] = bcmul($res['price'], CommonEnum::ORDER_EARNING_ALLOCATION['SharedProsperity']['Self']['YangLaoJin']['Ratio']['code'], 2);
            $k['jifen'] = 0;
            $k['gongxian'] = 0;

            // 计算共富区PV
            /** @var SharedProsperityRecommendConfigRepository $sharedProsperityRecommendConfigRepository */
            $sharedProsperityRecommendConfigRepository = app()->make(SharedProsperityRecommendConfigRepository::class);
            $sharedProsperityRecommendConfigEntityByMaxRewardRatio = $sharedProsperityRecommendConfigRepository->getSharedProsperityRecommendConfigEntityByMaxRewardRatio();
            // 利润 减去 顶格的直推奖，剩下的是PV值
            $pvProportion = bcsub('1', bcdiv($sharedProsperityRecommendConfigEntityByMaxRewardRatio->getRewardRatio(), '100', 4), 2);
            // 获取利润
            $productSku = Db::name('store_product_attr_value')->where('product_id', $res['product_id'])->order('price asc')->find();
            // 计算pv
            $pv = bcmul($productSku['plate_mer_profit'], $pvProportion, CommonEnum::DECIMAL_PLACES_OF_THE_AMOUNT);
            $k['pv'] = $pv;

        }

        $res['pv']=($k['pv']);
        $res['jifen']=($k['jifen']);
        $res['gongxian']=($k['gongxian']);

        $res['fzone_paytype']=($k['fzone_paytype']);

        foreach ($res['merchant']['recommend'] as $k => $v) {
//            $is_seckill=Db::name('store_product')->where('product_id',$v['product_id'])->value('seckill');
//            if($is_seckill==1){
//                unset($res['merchant']['recommend'][$k]);
//                continue;
//            }
            if ($res['merchant']['recommend'][$k]['mer_id'] == 276 || $res['merchant']['recommend'][$k]['mer_id'] == 236 || $res['merchant']['recommend'][$k]['mer_id'] == 290) {
                if ($res['merchant']['recommend'][$k]['mer_id'] == '236') {
                    $res['merchant']['recommend'][$k]['yanglao'] = bcmul($res['merchant']['recommend'][$k]['price'], bcmul('10', 0.01, 2), 2);
                } else {
                    $res['merchant']['recommend'][$k]['yanglao'] = bcmul($res['merchant']['recommend'][$k]['price'], bcmul('2', 0.01, 2), 2);
                }
            } else {
                $res['merchant']['recommend'][$k]['yanglao'] = $this->yanglaojin($v['product_id']);
            }
//            $res['merchant']['recommend'][$k]['yanglao'] = $this->yanglaojin($v['product_id']);
        }


        //店铺商品在售数量
        $res['product_count'] = Db::name("store_product")->where(['mer_id' => $res['mer_id'], 'status' => '1', 'is_show' => 1])->count();
        $res['merchant']["business_id"] = Db::name("merchant")->where(['mer_id' => $res['mer_id']])->value("business_id");
        $res['merchant']["sxy_submerchant_id"] = Db::name("merchant")->where(['mer_id' => $res['mer_id']])->value("sxy_submerchant_id");
        $merchant_uid = Db::name("merchant")->where(['mer_id' => $res['merchant']['mer_id']])->value('uid');
        $res['merchant']['im'] = Db::name('merchant_admin')->where(['mer_id' => $res['merchant']['mer_id']])->field('uid,im_uuid,account,im_user_id')->find();
        Db::name("merchant")->where(['mer_id' => $res['mer_id']])->inc('renqizhi', 1)->update();
        return $res;
    }

    public function getopenid($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . env('WECHAT.APPID') . "&secret=" . env('WECHAT.SECRET') . "&code=" . $code . "&grant_type=authorization_code";
        $get = curlGet($url);
        if (!isset($get['openid']) || empty($get['openid'])) {
            return '授权失败';
        }
        return $get['openid'];
    }

    public function pay($price, $openid)
    {


        $productDetails = array(
            'name'     => $product ?? "幸福宝",//商品名称。需传递真实产品名称。
            'quantity' => 1,//商品数量
            'amount'   => strval($price * 100),//商品单价
        );
        $data = [
            'openId'          => $openid,
            'requestId'       => time() . rand(10000, 99999) . "_" . rand(10, 99),
            'orderAmount'     => strval($price * 100),
            'callbackUrl'     => 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg4NzQ4NDgzNQ==&scene=124&uin=&key=&devicetype=Windows+10+x64&version=6302019c&lang=zh_CN&a8scene=7&fontgear=2',
            'paymentModeCode' => 'WECHAT-OFFICIAL_PAY-P2P',
            'productDetails'  => [$productDetails],
            'clientIp'        => $this->getRealIP(),
        ];
        $data['notifyUrl'] = '/api/notify/pay_5upay_h5';
        $insertdata = [
            'data' => json_encode($data),
            'time' => time()
        ];
        Db::name('gzh_h5_pay')->insert($insertdata);
        $res = ShouxinyiApiRequest::onlinePay($data);
        $return = array(
            'redirectUrl' => $res['redirectUrl'] ?? '',//重定向地址
            'status'      => $res['status'],
            'scanCode'    => $res['scanCode'] ?? '',//Base64二维码
            'appParams'   => $res['appParams'] ?? '',//App调用码
            'jsString'    => $res['jsString'] ?? '',//微信小程序及公众号支付调用串
            'wechatId'    => $res['wechatId'] ?? '',//微信原始ID串
            'tradeNo'     => $res['tradeNo'] ?? '',//支付宝生活号调用id
            'token'       => $res['token'] ?? '',    //微包支付调用token
        );

        return $return;
    }

    //客户端IP
    public function getRealIP()
    {
        $forwarded = request()->header("x-forwarded-for");
        if ($forwarded) {
            $ip = explode(',', $forwarded)[0];
        } else {
            $ip = request()->ip();
        }
        return $ip;
    }

    /**
     * TODO 单商品属性
     * @param $data
     * @return array
     * @author Qinii
     * @day 2020-08-05
     */
    public function detailAttr($data)
    {
        $attr = [];
        foreach ($data as $key => $item) {
            $attr[$key] = $item;
            $arr = [];
            foreach ($item['attr_values'] as $i => $value) {
                $arr[] = [
                    'attr'  => $value,
                    'check' => false
                ];
            }
            $attr[$key]['attr_value'] = $arr;
        }
        return $attr;
    }

    /**
     * TODO 单商品sku
     * @param $data
     * @param $userInfo
     * @return array
     * @author Qinii
     * @day 2020-08-05
     */
    public function detailAttrValue($data, $userInfo, $productType = 0)
    {
        $sku = [];
        $make = app()->make(StoreOrderRepository::class);
        foreach ($data as $k => $value) {
            $sku[$value['sku']] = [
                'sku'      => $value['sku'],
                'price'    => set_price_rtrim($value['price']),
                'stock'    => $value['stock'],
                'image'    => $value['image'],
                'bar_code' => $value['bar_code'],
                'weight'   => $value['weight'],
                'volume'   => $value['volume'],
                'ot_price' => set_price_rtrim($value['ot_price']),
                'unique'   => $value['unique'],
                'dacang'   => $value['dacang_price'] ? set_price_rtrim($value['dacang_price']) : 'null'
            ];
            if ($productType) {
                $sku[$value['sku']]['stock'] = $value['stock'] - $make->seckillSkuOrderCounut($value['unique']); //获取sku的销量
            }
            if ($this->getUserIsPromoter($userInfo)) {
                $sku[$value['sku']]['extension_one'] = $value->bc_extension_one;
                $sku[$value['sku']]['extension_two'] = $value->bc_extension_two;
            }

        }
        return $sku;
    }


    /**
     * TODO 秒杀商品详情
     * @param int $id
     * @author Qinii
     * @day 2020-08-05
     */
    public function seckillDetail(int $id)
    {
        $field = 'product_id,mer_id,image,slider_image,store_name,store_info,unit_name,price,cost,ot_price,stock,sales,video_link,old_product_id,product_type';

        $with = [
            'attr', 'attrValue', 'content', 'topReply' => function ($query) {
                $query->field('reply_id,uid,nickname,merchant_reply_content,avatar,order_product_id,product_id,product_score,service_score,postage_score,comment,create_time');
            }, 'merchant.recommend', 'seckillActive'   => function ($query) {
                $query->field('start_day,end_day,start_time,end_time,product_id');
            }
        ];
        $where = $this->seckillShow();
        $where['product_id'] = $id;
        $res = $this->dao->getWhere($where, $field, $with);
        if (!$res) throw new ValidateException('商品不存在');
        $res['isRelation'] = $isRelation ?? false;
        $res['sku'] = $this->detailAttrValue($res['attrValue'], null, $res['product_type']);
        $res['replayData'] = app()->make(ProductReplyRepository::class)->getReplyRate($res['product_id']);
        unset($res['attrValue'], $res['ficti'], $res['attr']);
        $res['attr'] = $this->detailAttr($res['attr']);
        //活动是否结束
        $res->append(['seckill_status']);
        $res['stop'] = strtotime(date('Y-m-d', time()) . $res['seckillActive']['end_time'] . ':00:00');
        unset($res['seckillActive']);
        $res['sales'] = app()->make(StoreOrderRepository::class)->seckillOrderCounut($id);
        $res['quota'] = $this->seckillStock($id);
        $oldPro = $this->dao->productShow();
        $oldPro['product_id'] = $res['old_product_id'];
        $old_status = 0;
        if ($this->dao->getWhere($oldPro)) $old_status = 1;
        $res['old_status'] = $old_status;

        $res['yanglao'] = $this->yanglaojin($res['product_id']);
        foreach ($res['merchant']['recommend'] as $k => $v) {
            $res['merchant']['recommend'][$k]['yanglao'] = $this->yanglaojin($v['product_id']);
        }

        return $res;
    }


    /**
     * TODO 秒杀商品库存检测
     * @param int $productId
     * @return bool|int
     * @author Qinii
     * @day 2020-08-05
     */
    public function seckillStock(int $productId)
    {
        $product = $this->dao->getWhere(['product_id' => $productId], '*', ['attrValue']);
        $count = app()->make(StoreOrderRepository::class)->seckillOrderCounut($productId);
        if ($product['stock'] > $count) {
            $make = app()->make(ProductAttrValueRepository::class);
            foreach ($product['attrValue'] as $item) {
                $attr = [
                    ['sku', '=', $item['sku']],
                    ['product_id', '=', $product['old_product_id']],
                    ['stock', '>', 0],
                ];
                if ($make->getWhereCount($attr)) return true;
            }
        }
        return false;
    }


    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param $userInfo
     * @return bool
     */
    public function getUserIsPromoter($userInfo)
    {
        return (isset($userInfo['is_promoter']) && $userInfo['is_promoter'] && systemConfig('extension_status')) ? true : false;
    }

    /**
     * @Author:Qinii
     * @Date: 2020/5/30
     * @param $userInfo
     * @param int|null $merId
     * @param $page
     * @param $limit
     * @return array
     */
    public function recommend($userInfo, ?int $merId, $page, $limit, $volunteer = null, $sort = '', $type = '')
    {
//        $where = ['order' => 'sales'];
        if ($sort)
            $where['order'] = $sort;

        if (!is_null($userInfo)) {
            $cate_ids = app()->make(UserVisitRepository::class)->getRecommend($userInfo['uid']);
            if ($cate_ids) $where = ['cate_ids' => $cate_ids];
        }
        if ($volunteer) {
            $where['volunteer'] = 1;
        } else {
            $where['volunteer'] = 0;
        }
        $where['price'] = ['>', 0];
        $where = array_merge($where, $this->switchType(1, $merId, 0));
        $make2 = app()->make(Goods::class);
        $gongProduct439 = $make2->getJoinProduct439();


        $query = $this->dao->search($merId, $where)->when($type && $merId == 321, function ($query) use ($type) {
            $query->where("type", $type);
        })->when($merId == 321, function ($q1) use ($gongProduct439) {
            $q1->where(function ($query2) use ($gongProduct439) {
                $query2->whereNotIn('spu_id', $gongProduct439)->whereOr("spu_id is null");
            });

        });


        $count = $query->count($this->dao->getPk());
//        var_dump($where);
//        echo Db::getlastsql();die;
        $list = $query->page($page, $limit)->setOption('field', [])->with(['issetCoupon'])->field('volunteer,product_id,cate_id,mer_id,image,store_name,sort,sales,price,create_time,keyword')->select();
        $arr=[];
        foreach ($list as $v) {
            $k = $this->pvParm($v['product_id']);
//            $v['yanglao'] = $yanglao;
//            $v["yanglao"]
            $v['yanglao']=($k['yanglao']);
            $v['pv']=($k['pv']);
            $v['jifen']=($k['jifen']);
            $v['gongxian']=($k['gongxian']);
            $v['jfduihuan']=($k['jfduihuan']);
            $v['jdduihuan']=($k['jdduihuan']);
//            $v=($v,$k);
//            array_push($v,$k);
            $arr[]=$v;
        }
        $list=$arr;
        return compact('count', 'list');
    }

    /**
     * @param $page
     * @param $limit
     * @param $key
     * @param $cate_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author tang
     */
    public function search_recommend($page, $limit, $key, $cate_id, $uid)
    {
        $topping = Db::name('user')->where('uid', $uid)->value('mer_topping');
        $where = [];
//        if($cate_id!='')
//            $where['cate_id'] = $cate_id;
        $where['sp.volunteer'] = 1;
        $list = [];
        if ($key != '') {
            $list = Db::name('store_product')
                ->alias('sp')
                ->join('merchant m', 'm.mer_id = sp.mer_id')
                ->page($page, $limit)
                ->where($where)
                ->group('sp.mer_id')
                ->whereLike('sp.store_name', "%" . $key . "%")
                ->where('m.mer_state', 1)
                ->where('m.is_del', 0)
                ->where('sp.volunteer', 1)
                ->where('sp.is_show', 1)
                ->where('sp.is_used ', 1)
                ->select();
            if (!$list->isEmpty()) {
                $list = $list->toArray();
            }
            foreach ($list as $k => &$v) {
                if ($v['mer_id'] == $topping) {
                    $a = $v;
                    unset($list[$k]);
                } else {
                    $a = [];
                }
            }
            if (!empty($a))
                array_unshift($list, $a);
            $list = array_merge($list);
        } else {
            $whereCate = [];
            if ($cate_id > 0) {
                $whereCate['m.category_id'] = $cate_id;
            }

            $list = Db::name('store_product')
                ->alias('sp')
                ->join('merchant m', 'm.mer_id = sp.mer_id')
                ->where('m.mer_state', 1)
                ->where('m.is_del', 0)
                ->group('sp.mer_id')
                ->where('sp.volunteer', 1)
                ->where('sp.is_show', 1)
                ->where('sp.is_used ', 1)
                ->where($whereCate)
                ->page($page, $limit)
                ->field('sp.*')
                ->select();
            Log::info($list->isEmpty());
            if (!$list->isEmpty()) {
                $list = $list->toArray();
            }
            Log::info(json_encode($list));
            $a = [];
            foreach ($list as $k => &$v) {

                if ($v['mer_id'] == $topping) {
                    $a = $v;
                    unset($list[$k]);
                }
            }
            if (!empty($a))
                array_unshift($list, $a);
            $list = array_merge($list);
        }
        $count = 0;
        foreach ($list as &$v) {
            $count++;
            $yanglao = $this->yanglaojin($v['product_id']);
            $v['yanglao'] = $yanglao;
        }
        return compact('count', 'list');
    }

    /**
     * 检测是否有效
     * @Author:Qinii
     * @Date: 2020/6/1
     * @param $id
     * @return mixed
     */
    public function getOne($id)
    {
        $data = ($this->dao->getWhere([$this->dao->getPk() => $id]));
        if (!is_null($data) && $data->check()) return $data;
        return false;
    }

    public function switchStatus(array $id, $data)
    {
        $status = $data['status'] ?? 0;
        $is_show = $data['is_show'] ?? 0;
        $make = app()->make(ProductAttrValueRepository::class);

        if (($status == 1 || $is_show == 1) && systemConfig('extension_status')) {
            foreach ($id as $i) {
                if ($this->getWhereCount(['product_id' => $i, 'extension_type' => 1])) {
                    $sku = Db::name("store_product_attr_value")->where(['product_id' => $i])->column("extension_one");
                    foreach ($sku as $k) {
                        if ($k < systemConfig('extension_one_rate'))
                            throw new ValidateException('设置返利请高于系统设置的' . systemConfig('extension_one_rate') . '%比例');
                    }
                }
            }
        }
        $this->dao->updates($id, $data);
        $res = $this->dao->get($id[0]);

        if (isset($data['status'])) {
            SwooleTaskService::merchant('notice', [
                'type' => 'product',
                'data' => [
                    'title'   => '新审核结果',
                    'message' => '您有一条新的商品审核',
                    'id'      => ''
                ]
            ], $res['mer_id']);
        }
    }

    /**
     * TODO 执行检测所有线上商品
     * @author Qinii
     * @day 2020-06-24
     */
    public function checkProductByExtension()
    {
        if (systemConfig('extension_status')) {
            $where = ['status' => 1, 'is_show' => 1, 'product_type' => 0];
            $make = app()->make(ProductAttrValueRepository::class);
            $query = $this->dao->search(null, $where)->where('extension_type', 1);
            $query->chunk(100, function ($prduct) use ($make) {
                foreach ($prduct as $item) {
                    if (!$make->checkExtensionById($item['product_id'])) {
                        $item->status = -2;
                        $item->refusal = '因佣金比例调整，商品佣金低于系统比例';
                        $item->save();
                    }
                }
            });
        }
    }

    public function wxQrCode(Product $product, User $user)
    {
        $name = $product->product_id . '_product_detail_' . $user->uid . '_is_promoter_' . $user['is_promoter'] . '_wap.jpg';
        return app()->make(QrcodeService::class)->getWechatQrcodePath($name, '/pages/goods_details/index?id=' . $product->product_id . '&spread=' . $user['uid']);
    }

    public function routineQrCode(Product $product, User $user)
    {
        //小程序
        $name = $product->product_id . '_' . $user['uid'] . '_' . $user['is_promoter'] . '_product.jpg';
        $data = 'id=' . $product->product_id;
        if ($user['is_promoter'] || systemConfig('store_brokerage_statu') == 2) $data .= '&pid=' . $user['uid'];
        return app()->make(QrcodeService::class)->getRoutineQrcodePath($name, 'pages/goods_details/index', $data);
    }

    /**
     * TODO 礼包是否超过数量限制
     * @param $merId
     * @return bool
     * @author Qinii
     * @day 2020-06-25
     */
    public function checkMerchantBagNumber($merId)
    {
        $where = ['is_gift_bag' => 1];
        $promoter_bag_number = systemConfig('promoter_bag_number');
        $count = $this->dao->search($merId, $where)->count();
        if ($promoter_bag_number > $count) return true;
        return false;
    }

    /**
     * TODO
     * @param int $id
     * @param array $status
     * @author Qinii
     * @day 2020-07-17
     */
    public function changeUsed(int $id, array $status)
    {
        return $this->dao->update($id, $status);
    }

    public function orderProductIncStock($cart)
    {
        Db::transaction(function () use ($cart) {
            $productAttrValueRepository = app()->make(ProductAttrValueRepository::class);
            if (!$productAttrValueRepository->attrExists($cart['product_id'], $cart['cart_info']['productAttr']['unique'])) return;
            $productAttrValueRepository->incStock($cart['product_id'], $cart['cart_info']['productAttr']['unique'], $cart['product_num']);
            if (!$this->exists($cart['product_id'])) return;
            $this->dao->incStock($cart['product_id'], $cart['product_num']);
            if (isset($cart['cart_info']['product']['old_product_id'])) {
                $oldId = $cart['cart_info']['product']['old_product_id'];
                if (!$productAttrValueRepository->skuExists($oldId, $cart['cart_info']['productAttr']['sku'])) return;
                $productAttrValueRepository->incSkuStock($oldId, $cart['cart_info']['productAttr']['sku'], $cart['product_num']);
                if ($this->exists($oldId))
                    $this->incStock($oldId, $cart['product_num']);
            }
        });
    }

    /**
     * TODO 商品验证
     * @param $data
     * @author Qinii
     * @day 2020-08-01
     */
    public function check($data, $merId)
    {


        if ($data['share_is'] == 1 || $data['pension_is'] == 1) {

            $member_settings = merchantConfig($merId, 'member_settings');
            $member_settings = $member_settings ?: [];
            if (empty($member_settings)) {
                $member_settings['tjj'] = 0;
                $member_settings['ylj'] = 0;
                $member_settings['dls'] = 0;
                $member_settings['yy_one'] = 0;
                $member_settings['yy_kg'] = 0;
            }
            $where['mer_id'] = $merId;
            $where['state'] = 1;
            $yeji = Db::name('enterprise_performance_divvy')->where($where)->sum('gdp');
            $daili = Db::name('enterprise_agent_divvy')->where($where)->sum('gdp');


            foreach ($data['attrValue'] as $v) {

                if ($data['share_is'] == 1) {
                    if ($v['share_num'] < 0) {
                        throw new ValidateException('分享奖不能小于0');
                    }
                    $member_settings['tjj'] = $v['share_num'];


                }
                if ($data['pension_is'] == 1) {
                    if ($v['pension_num'] < 0) {
                        throw new ValidateException('养老金不能小于0');
                    }
                    $member_settings['ylj'] = $v['pension_num'];
                }
                // 推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例≤100
                $bili1 = $member_settings['tjj'] + $member_settings['ylj'] + $yeji + $daili;
                if ($bili1 > 100) {
                    throw new ValidateException('推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例≤100');
                    return app('json')->fail('推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例≤100');
                }
                // 运营中心比例+推荐代理商收益≤100-(推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例)
                $bili2 = $member_settings['yy_one'] + $member_settings['dls'];
                if ($member_settings['yy_kg'] != 1) {
                    $bili2 = $member_settings['dls'];
                }
                if ($bili2 <= (100 - $bili1)) {

                } else {
                    throw new ValidateException('运营中心比例+推荐代理商收益≤100-(推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例)');
                    return app('json')->fail('运营中心比例+推荐代理商收益≤100-(推荐奖比例+养老金比例+业绩分红总比例+代理商分红总比例)');
                }
            }
        }


//        if(!$this->merBrandExists($data['brand_id']))
//            throw new ValidateException('品牌不存在');
//        if(!$this->CatExists($data['cate_id']))
//            throw new ValidateException('平台分类不存在');
//        if(isset($data['mer_cate_id']) && !$this->merCatExists($data['mer_cate_id'],$merId))
//            throw new ValidateException('不存在的商户分类');
        if (!$this->merShippingExists($merId, $data['temp_id']) && $data['temp_id'] != 105)
            throw new ValidateException('运费模板不存在');

    }


    /**
     * 通过产品id，价格，商户id，获取pv,贡献值，积分，养老金等
     * @param int $good_id
     * @param int $price
     * @param int $dc
     * @param null $product_attr_unique
     * @return string
     */
    public function pvParm($good_id = 0, $price = 0,$mer_id=0, $dc = 0, $product_attr_unique = null)
    {

        $yanglao = 0;//养老金
        $pv = 0;//pv值
        $gongxian = 0;//贡献值
        $jifen = 0;//积分
        $jfduihuan = "";//积分+现金兑换
        $jdduihuan = "";//京豆+现金兑换
        $total_price = 0;//产品价格
        $srtArry[]="";//返回的数组
        $fzone_paytype = [];
//        $extension_bili = 0;
        //线上商品
        if ($good_id > 0) {
            if ($good_id == 15323) {
                //19800商品固定200养老金
                return 200;
            }
            $product = Db::name('store_product')->where('product_id', $good_id)->find();
            //var_dump($product['mer_id']);
            if ($price) {
                $total_price = $price;
            } else {
                $total_price = $product['price'];
            }

            //plate_mer_profit 产品获得的佣金 数据库添加商品已经算好的佣金

            // $pv=decimal2($product['plate_mer_profit']*0.5);//pv=佣金的50%
            // $dui_jifen=decimal2($product['plate_mer_profit']*0.4);
            // $dui_jingdou=decimal2($product['plate_mer_profit']*0.5);
            // $dui_price=$total_price-$dui_jifen;//用积分兑换，所需要的现金 佣金的*40%
            // $jidou__price=$total_price-$dui_jingdou;//用京豆兑换，所需要的现金 佣金的*50%

            // $jfduihuan="{$dui_price} + {$dui_jifen}";
            // $jdduihuan="{$jidou__price} + {$dui_jingdou}";
            // $srtArry['jfduihuan']=$jfduihuan;
            // $srtArry['jdduihuan']=$jdduihuan;


            // $yanglao='';
            // $pv='';
            // $jifen='';
            // $gongxian='';
            // $jfduihuan='';
            // $jdduihuan='';


            //$v['vr'] = 0;
            $num_yl = 0;

            if($product['price'] == '1180'){
                $num_yl = 1000;
            }else if($product['price'] == '10620'){
                $num_yl = 9000;
            }else if($product['price'] == '11800'){
                $num_yl = 10000;
            }else if($product['price'] == '2360'){
                $num_yl = 2000;
            }else if($product['price'] == '9440'){
                $num_yl = 8000;
            }else if($product['price'] == '5900'){
                $num_yl = 5000;
            }

            if($product['mer_id'] == 496){

                $yanglao = bcmul($num_yl, 0.035, 2);
                $pv = bcmul($num_yl, 0.7, 2);
                //$v['vr']=$v['price'];
                //1:为会员专区,

                $fzone_paytype= [
                    1=>[
                        1=>$product['price'],//VR
                        2=>$product['price']//现金
                    ]
                ];

            }else if($product['mer_id'] == 439){
                //精彩生活和商贸区
                $jf = $product['price'] - bcmul($product['concession_pri'], 0.3, 2) . ' + ' . bcmul($product['concession_pri'],0.3, 2);
                $jd = $product['price'] - bcmul($product['concession_pri'], 0.35, 2) . ' + ' . bcmul($product['concession_pri'],0.35, 2);
                if($product['concession_pri'] !=null || $product['concession_pri'] !=0){
                    $yanglao = bcmul($product['concession_pri'], 0.3, 2);
                    $pv = bcmul($product['concession_pri'], 0.35, 2);
                    $srtArry['jfduihuan'] =$jf;
                    $srtArry['jdduihuan'] = $jd;
                    $jifen = bcmul($product['concession_pri'], 0.35, 2);
                    $gongxian = bcmul($product['concession_pri'], 0.35, 2);

                    $jcvr = $product['price'] - bcmul($product['concession_pri'], 0.3, 2);
                    $jcjf = bcmul($product['concession_pri'], 0.3, 2);
                    $jcprice = $product['price'] - bcmul($product['concession_pri'], 0.3, 2);
                    $jcjf1 = bcmul($product['concession_pri'], 0.3, 2);
                    $jcvr1 = $product['price'] - bcmul($product['concession_pri'], 0.35, 2);
                    $jcjd = bcmul($product['concession_pri'], 0.35, 2);
                    $jcprice1 = $product['price'] - bcmul($product['concession_pri'], 0.35, 2);
                    $jcjd1 = bcmul($product['concession_pri'], 0.35, 2);


                    //支付组合
                    // $fzone_paytype= [

                    //     2=>[
                    //         1=>[$jcvr,$jcjf],//VR+积分
                    //         2=>[$jcprice,$jcjf1],//现金+积分
                    //         3=>[$jcvr1,$jcjd],//VR+京豆
                    //         4=>[$jcprice1,$jcjd1],//现金+金豆
                    //         5=>$product['price'],//VR
                    //         6=>$product['price'],//现金
                    //     ]
                    // ]; 

                    $fzone_paytype= [
                        ['type'=>'b1','price'=>$jcvr,'other'=>$jcjf],
                        ['type'=>'b2','price'=>$jcprice,'other'=>$jcjf1],
                        ['type'=>'b3','price'=>$jcvr1,'other'=>$jcjd],
                        ['type'=>'b4','price'=>$jcprice1,'other'=>$jcjd1],
                        ['type'=>'b5','price'=>$product['price'],'other'=>0],
                        ['type'=>'b6','price'=>$product['price'],'other'=>0],
                    ];

                }
            }else if($product['mer_id'] == 491){
//                $num_yl = $product['price'];
//                $pv= $num_yl * 0.3;
                // 获取商品sku
                $productSku = Db::name('store_product_attr_value')->where('product_id', $good_id)->order('price asc')->find();
                $pv = $productSku['plate_mer_profit']??0.00;
                $yanglao = bcmul($pv, 0.5, 2);
                //$v['vr']=$v['price'];
                //1:为会员专区,

                $fzone_paytype= [
                    1=>[
                        1=>$product['price'],//VR
                        2=>$product['price'],//现金
                        3=>$product['price']//复购金
                    ]
                ];
            } else {
                // 商贸区
                /** @var MerchantRepository $merchant */
                $merchant = app()->make(MerchantRepository::class);
                $merchantInfo = $merchant->get($product['mer_id']);
                // 1企业2个体3个人
                if ($merchantInfo && in_array($merchantInfo['type'],[1,2,3])) {
                    //商贸区
                    $jf = $product['price'] - bcmul($product['concession_pri'],0.3, 2) . ' + ' . bcmul($product['concession_pri'],0.3, 2);
                    $jd = $product['price'] - bcmul($product['concession_pri'],0.35, 2) . ' + ' . bcmul($product['concession_pri'],0.35, 2);
                    if($product['concession_pri'] !=null || $product['concession_pri'] !=0){
                        $yanglao = bcmul($product['concession_pri'], 0.3, 2);
                        $pv = bcmul($product['concession_pri'], 0.35, 2);
                        $srtArry['jfduihuan'] =$jf;
                        $srtArry['jdduihuan'] = $jd;
                        $jifen = bcmul($product['concession_pri'], 0.35, 2);
                        $gongxian = bcmul($product['concession_pri'], 0.35, 2);

                        $jcvr = $product['price'] - bcmul($product['concession_pri'], 0.3, 2);
                        $jcjf = bcmul($product['concession_pri'], 0.3, 2);
                        $jcprice = $product['price'] - bcmul($product['concession_pri'], 0.3, 2);
                        $jcjf1 = bcmul($product['concession_pri'], 0.3, 2);
                        $jcvr1 = $product['price'] - bcmul($product['concession_pri'], 0.35, 2);
                        $jcjd = bcmul($product['concession_pri'], 0.35, 2);
                        $jcprice1 = $product['price'] - bcmul($product['concession_pri'], 0.35, 2);
                        $jcjd1 = bcmul($product['concession_pri'], 0.35, 2);

                        $fzone_paytype= [
//                ['type'=>'b1','price'=>$jcvr,'other'=>$jcjf],
                            ['type'=>'b2','price'=>$jcprice,'other'=>$jcjf1],
//                ['type'=>'b3','price'=>$jcvr1,'other'=>$jcjd],
                            ['type'=>'b4','price'=>$jcprice1,'other'=>$jcjd1],
//                ['type'=>'b5','price'=>$product['price'],'other'=>0],
                            ['type'=>'b6','price'=>$product['price'],'other'=>0],
                        ];

                    }
                }
            }
        }else{//线下商品

            if ($mer_id>0){
                $base_commission= merchantConfig($mer_id, 'base_commission') ?: [
                    'base_commission' => 5
                ];// 如果没有查到商户的设置，系统默认最小5%让利
                $rangli=$total_price*($base_commission/100);//商户让利的金额
                $pv=$rangli;//线下的pv等与让利100%
            }

        }
        $jifen=$pv;
        $gongxian=$pv;
        $yanglao=$yanglao;//养老金=pv的5%
        $srtArry['pv']=$pv;
        $srtArry['jifen']=$jifen;
        $srtArry['gongxian']=$gongxian;
        $srtArry['yanglao']=$yanglao;
        $srtArry['fzone_paytype']=$fzone_paytype;

        // $srtArry['per_balance']=$fzone_paytype;//个人余额
        // $srtArry['per_vr']=$fzone_paytype;//个人VR
        // $srtArry['per_jingdou']=$fzone_paytype;//个人京豆
        // $srtArry['per_score']=$fzone_paytype;//个人积分
        return  $srtArry;


    }


    /*
     *
        @good_id  商品id
        @cabbage
        @date 2020-11-18
    */
    /**
     * 计算商品的养老金
     * @param int $good_id
     * @param int $price
     * @param int $dc
     * @param null $product_attr_unique
     * @return string
     */
    public function yanglaojin($good_id = 0, $price = 0, $dc = 0, $product_attr_unique = null): string
    {

        $yanglao     = 0;
        $total_price = 0;
        $extension_bili = 0;
        if ($good_id > 0) {
            if ($good_id == 15323) {
                //19800商品固定200养老金
                return 200;
            }
            $product = Db::name('store_product')->where('product_id', $good_id)->find();
            if ($price) {
                $total_price = $price;
            } else {
                $total_price = $product['price'];
            }
            $mer_id = $product['mer_id'];
            if ($product['spu_id']) {
                // 大仓商品
                // 佣金设置
                $commission_rate = systemConfig('commission_rate');
                $yanglao         = $total_price * $commission_rate['yanglao_rate'] / 100;

            } else {
                // 平台商品 走商户后台
                // 推荐创客收益设置
//                 $shop_bonus_setting                 = merchantConfig($mer_id, 'shop_bonus_setting') ?: [
//                     'shop_bonus_rate' => 30,
//                     'yanglao_rate'    => 5,
//                 ];
//                 $shop_bonus_setting['yanglao_rate'] = $shop_bonus_setting['yanglao_rate'] ?? 5;
// //                if ($mer_id == 496) {
// //                    $yanglao = $total_price * 5 / 100;
// //                } else {
//                 $yanglao = $total_price * $shop_bonus_setting['yanglao_rate'] / 100;
// //                }
                $yanglao = bcmul($product['concession_pri'], 0.3, 2);

            }
            $yanglao= decimal2($yanglao);
        } else {
            $extension_bili=  (float)systemConfig('extension_tao_rate');
            $logs['extension_tao_rate'] = $extension_bili;
            $extension['price'] = $price;
        }

        //养老金比例
        $yanglaojin_admin=  systemConfig('yanglaojin_admin');
        $logs['yanglaojin_admin'] = $yanglaojin_admin;

        if ($extension_bili>0){
            $yanglao = $extension['price'] * $extension_bili / 100 ;  //除去刷卡费  乘以返利比例

            if($good_id==0){
                // 三方手续费要计算刷卡手续费，前台显示要和实际给到保持一致
                //刷卡手续费
                $souxufees=0;
                $souxufee =floatval(systemConfig('yanglao'));
                $logs['yanglao'] = $souxufee;
                if ($souxufee){
                    $souxufees = bcmul($yanglao, $souxufee * 0.01, 3);
                }
                //返佣比例
                $base_commission= floatval(systemConfig('extension_tao_rate'));
                $logs['extension_tao_rate'] = $base_commission;
                //返佣总额 返利总额=（交易金额-手续费）*返利比例
                // log::info("计算养老金 good_id： {$good_id},yanglao ： $yanglao");
                $yanglao=bcmul($yanglao-$souxufees,$base_commission/100,3);
                // log::info("计算养老金 good_id： {$good_id},yanglao-$souxufees 保留三位$yanglao");
            }
            $yanglao = $yanglao * $yanglaojin_admin /100  ;//养老金比例
            // log::info("计算养老金 good_id： {$good_id},yanglao ： $yanglao");

            $yanglao= decimal2($yanglao);// 取两位小数 后面舍去
        }

        // log::info(json_encode($logs));
        // log::info("计算养老金 good_id： {$good_id},price{$total_price},yanglao:{$yanglao}");

        return set_price_rtrim($yanglao);
    }

    public function editPrice($product_id, $skuArr, $type = 1, $operatorId = 0)
    {
        if (empty($skuArr))
            throw new ApiException('参数错误');
        try {
            // 获取商品的规格信息
            $attrInfo = Db::name('store_product_attr_value')
                ->field('gong_sku_id,gong_mer_profit,price,cost,ot_price,gong_market_price,gong_pension')
                ->where('product_id', $product_id)
                ->select()->toArray();
            $attrInfo = array_column($attrInfo, null, 'gong_sku_id');
            $updateData = [];
            /** @var ProductAttrValueChangeLogRepository $productAttrValueChangeLogRepository */
            $productAttrValueChangeLogRepository = app()->make(ProductAttrValueChangeLogRepository::class);
            // 组装数据
            foreach ($skuArr as $key => $value) {
                if (isset($attrInfo[$value['sku_id']])) {

                    if ($value['edit_price'] > $attrInfo[$value['sku_id']]['gong_market_price']) {
                        // 上调价格计算创客利润
                        $diff = bcsub($value['edit_price'], $attrInfo[$value['sku_id']]['gong_market_price'], 2);
                        // $diff_profit = bcmul($diff, 0.7, 2);
                        $diff_profit = $diff;
                        $plate_mer_profit = bcadd($attrInfo[$value['sku_id']]['gong_mer_profit'], $diff_profit, 2);
                    } else {
                        // 下调价格计算创客利润
                        $diff = bcsub($attrInfo[$value['sku_id']]['gong_market_price'], $value['edit_price'], 2);
                        $plate_mer_profit = bcsub($attrInfo[$value['sku_id']]['gong_mer_profit'], $diff, 2);
                        if ($plate_mer_profit < 0) {
                            throw new ApiException('销售价格填写不正确');
                        }
                    }
                    /** @var StoreProductAttrValueChangeLogEntity $storeProductAttrValueChangeLogEntity */
                    $storeProductAttrValueChangeLogEntity = StoreProductAttrValueChangeLogEntity::newInstance();
                    $storeProductAttrValueChangeLogEntity->setProductId($product_id)
                        ->setSkuId($value['sku_id'])
                        ->setCost($attrInfo[$value['sku_id']]['cost'])
                        ->setOtPrice($attrInfo[$value['sku_id']]['ot_price'])
                        ->setPrice($attrInfo[$value['sku_id']]['price'])
                        ->setPlateMerProfit($attrInfo[$value['sku_id']]['plate_mer_profit'])
                        ->setOperatorId($operatorId)
                        ->setCreateTime(date('Y-m-d H:i:s'));
                    $productAttrValueChangeLogRepository->createByEntity($storeProductAttrValueChangeLogEntity);
                    $updateData[] = [
                        'gong_sku_id'      => $value['sku_id'],
                        'price'            => $value['edit_price'],
                        'plate_mer_profit' => $plate_mer_profit,
                        'concession_pri'   => $plate_mer_profit,
                        'cost'             => $attrInfo[$value['sku_id']]['cost'],
                        'ot_price'         => $attrInfo[$value['sku_id']]['ot_price'],
                        'gong_pension'     => $attrInfo[$value['sku_id']]['gong_pension']
                    ];
                }
            }
            if (empty($updateData))
                throw new ApiException('数据错误');

            $sortPrice = array_column($updateData, 'price');
            array_multisort($sortPrice, SORT_ASC, $updateData);

            Db::startTrans();
            // 修改入库
            foreach ($updateData as $udv) {
                $skuModel = Db::name('store_product_attr_value')->where('product_id', $product_id)->where('gong_sku_id', $udv['gong_sku_id']);
                $skuOld = $skuModel->select()->toArray();
                Log::info("商家修改供应链商品sku前的数据：" . json_encode($skuOld));
                $skuModel->update([
                    'price'            => $udv['price'],
                    'plate_mer_profit' => $udv['plate_mer_profit']
                ]);
            }
            // 同步商品库中的信息
            $productModel = Db::name('store_product')->where('product_id', $product_id);
            $productOld = $productModel->select()->toArray();
            Log::info("商家修改供应链商品基本信息前的数据：" . json_encode($productOld));
            $yanglaojin_scale = (!empty($updateData[0]['gong_pension']) && !empty($updateData[0]['price'])) ? bcdiv($updateData[0]['gong_pension'], $updateData[0]['price'], 2) : 0;
            $productModel->update([
                'price'            => $updateData[0]['price'],
                'cost'             => $updateData[0]['cost'],
                'ot_price'         => $updateData[0]['ot_price'],
                'plate_mer_profit' => $updateData[0]['plate_mer_profit'],
                'concession_pri'   => $updateData[0]['plate_mer_profit'],
                'is_show'          => 0,
                'yanglaojin_scale' => $yanglaojin_scale,
                'type'             => $type
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new ApiException('系统繁忙');
        }
    }

    // 判断创客利润是否大于0
    public function checkGongProfit($ids)
    {
        foreach ($ids as $id) {
            $skuInfo = Db::name('store_product_attr_value')->field('price,gong_market_price,gong_mer_profit')->where('product_id', $id)->select()->toArray();
            foreach ($skuInfo as $value) {
                if ($value['price'] < $value['gong_market_price']) {
                    $diff = bcsub($value['gong_market_price'], $value['price'], 2);
                    $plate_mer_profit = bcsub($value['gong_mer_profit'], $diff, 2);
                    if ($plate_mer_profit < 0) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    // 供应链商品删除
    public function changeDelete($ids)
    {
        $data = ['is_show' => 0, 'is_del' =>1];
        $this->dao->update($ids, $data);
    }


    // 供应链商品上下架
    public function changeStatus($ids, $is_show)
    {

        if ($is_show == 1) {
            $data = ['is_show' => $is_show, 'is_status' => 0];
        } else {
            $data = ['is_show' => $is_show, 'is_status' => 1];
        }

        $this->dao->updates($ids, $data);

        foreach ($ids as $id) {
            $res = $this->dao->get($id);

            if (isset($data['status'])) {
                SwooleTaskService::merchant('notice', [
                    'type' => 'product',
                    'data' => [
                        'title'   => '新审核结果',
                        'message' => '您有一条新的商品审核',
                        'id'      => ''
                    ]
                ], $res['mer_id']);
            }
        }
    }

    public function thirdYanglaojin($good_id = 0, $price = 0)
    {
        //返佣比例
        $base_commission= floatval(systemConfig('extension_tao_rate'));

        //刷卡手续费
        $souxufees=0;
        $souxufee =floatval(systemConfig('yanglao'));
        if ($souxufee){
            $souxufees = bcmul($price, $souxufee * 0.01, 3);
        }
        //返佣总额 返利总额=（交易金额-手续费）*返利比例
        return decimal2(bcmul($price-$souxufees,$base_commission/100,3));
    }

    /**
     * @param int $productId
     * @return StoreProductEntity
     */
    public function getStoreProductEntityByProductId(int $productId): StoreProductEntity
    {
        $entityList = $this->getStoreProductEntityListByProductIdList([$productId]);
        $entity = array_shift($entityList);
        if ($entity instanceof StoreProductEntity) {
            return $entity;
        } else {
            /** @var StoreProductEntity */
            return StoreProductEntity::newInstance();
        }
    }

    /**
     * @param array $idList
     * @return StoreProductEntity[]
     */
    public function getStoreProductEntityListByProductIdList(array $idList): array
    {
        return $this->dao->getUserSignGongxianEntityListByIdList($idList);
    }
}
