<?php


namespace JinDouYun\Controller\Cron;

use JinDouYun\Dao\Price\DNationalUnifiedPrice;
use JinDouYun\Dao\Price\DPriceRangeSheet;

/**
 * 同步价格数据到最高/低价格表
 * Class PriceCron
 * @package JinDouYun\Controller\Cron
 */
class PriceCron
{
    public function __construct()
    {
        echo date('Y-m-d H:i:s') . ':同步价格数据开始' . PHP_EOL;
    }

    /**
     * @throws \Exception
     */
    public function syncRangePrice()
    {

        $enterpriseIds = [1,3,4,10,11,13,15,16];//dev
        //$enterpriseIds = [1,4,7,8,9,13,14,17,18,19,21,23,24,25,27];//master
        $objDNationalUnifiedPrice = new DNationalUnifiedPrice();
        $objDPriceRangeSheet = new DPriceRangeSheet();
        foreach ($enterpriseIds as $enterpriseId){
            // 按照企业分表
            $tableName = 'qianniao_nationalUnifiedPrice_' . $enterpriseId;
            $objDNationalUnifiedPrice->setTable($tableName);

            $dbResult = $objDNationalUnifiedPrice->select([],'goodsId,shopId,salePrice');
            if ($dbResult === false){
                echo '获取'.$enterpriseId.'企业价格表数据失败'.$objDNationalUnifiedPrice->error().PHP_EOL;
                exit;
            }
            if (empty($dbResult)){
                echo '企业'.$enterpriseId.'价格表数据为空不需要同步'.PHP_EOL;
                continue;
            }

            // 按照企业分表
            $objDPriceRangeSheet->setTable('qianniao_priceRangeSheet_'.$enterpriseId);
            $add = [];
            foreach ($dbResult as $row){
                $salePrice = json_decode($row['salePrice'],true);
                $allSalePrice = array_column($salePrice,'salePrice');
                $sale = [
                    'minSalePrice' => min($allSalePrice),
                    'maxSalePrice' => max($allSalePrice),
                ];
                $add[] = [
                    'goodsCode'  => isset($row['goodsCode']) ? $row['goodsCode'] : '',
                    'goodsName'  => isset($row['goodsName']) ? $row['goodsName'] : '',
                    'goodsId'    => $row['goodsId'],
                    'shopId'     => $row['shopId'],
                    'createTime' => time(),
                    'salePrice'  => json_encode($sale),
                ];
            }
            $result = $objDPriceRangeSheet->replace($add,true);
            if ($result === false){
                echo '企业'.$enterpriseId.'写入最低/高表价格失败'.$objDPriceRangeSheet->error().PHP_EOL;
                exit;
            }

            echo '企业'.$enterpriseId.'写入最低/高价格表成功，共写入'.count($add).'条数据'.PHP_EOL;
        }
    }

    public function __destruct()
    {
        echo date('Y-m-d H:i:s') . ':同步价格数据完成' . PHP_EOL;
    }
}