<?php

namespace JinDouYun\Model\Commission;

use JinDouYun\Dao\Commission\DCommissionGoodsStatistics;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Controller\Common\Logger;
use JinDouYun\Dao\Goods\DGoods;
use JinDouYun\Dao\GoodsManage\DSku;
use JinDouYun\Model\Stock\MInventory;
use JinDouYun\Dao\Commission\DCommissionGoods;
use JinDouYun\Dao\Commission\DCommissionGrade;
use JinDouYun\Model\Price\MPrice;

/**
 * 分销商品
 * Description:
 * Class MCommissionGoods
 */
class MCommissionGoods
{
    /**
     * @var DCommissionGoods
     */
    private $objDCommissionGoods;

    /**
     * @var integer 当前登陆企业id
     */
    private $onlineEnterpriseId;

    /**
     * @var integer 当前登陆用户id
     */
    private $onlineUserId;

    /**
     * @var MInventory
     */
    private $objMInventory;

    /**
     * @var DGoods
     */
    private $objDGoods;

    /**
     * @var DSku
     */
    private $objDSku;

    /**
     * @var DCommissionGrade
     */
    private $objDCommissionGrade;

    /**
     * @var MPrice
     */
    private $objMPrice;

    /**
     * @var DCommissionGoodsStatistics
     */
    private $objDCommissionGoodsStatistics;

    /**
     * MCommissionGoods constructor.
     * @param $onlineEnterpriseId
     * @param $onlineUserId
     * @throws \Exception
     */
    public function __construct($onlineEnterpriseId, $onlineUserId)
    {
        $this->onlineUserId = $onlineUserId;
        $this->onlineEnterpriseId = $onlineEnterpriseId;
        $this->objDCommissionGoods = new DCommissionGoods();
        $this->objDCommissionGoods->setTable('qianniao_commission_goods_' . $this->onlineEnterpriseId);
        $this->objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objDGoods = new DGoods();
        $this->objDGoods->setTable('qianniao_goods_' . $this->onlineEnterpriseId);
        $this->objDSku = new DSku();
        $this->objDSku->setTable('qianniao_sku_' . $this->onlineEnterpriseId);
        $this->objDCommissionGrade = new DCommissionGrade();
        $this->objMPrice = new MPrice($this->onlineUserId, $this->onlineEnterpriseId);
        $this->objDCommissionGoodsStatistics = new DCommissionGoodsStatistics();
        $this->objDCommissionGoodsStatistics->setTable('qianniao_commission_goods_statistics_'.$this->onlineEnterpriseId);
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
    }


    /**
     * Doc: (des="分销商品列表")
     * User: XMing
     * Date: 2020/7/22
     * Time: 2:23 下午
     * @param array $selectParams
     * @return ResultWrapper
     */
    public function getAll(array $selectParams)
    {
        $return = [
            'data'  => [],
            'total' => 0
        ];
        $fields = 'g.id,g.isJoinCommission,g.basicGoodsId,b.title,b.images,s.warehouseId,g.enableStatus';
        $sql = 'SELECT ' . $fields . ' FROM qianniao_goods_' . $this->onlineEnterpriseId . ' as g 
                LEFT JOIN qianniao_goods_basic_' . $this->onlineEnterpriseId . ' as b 
                ON b.id = g.basicGoodsId 
                LEFT JOIN qianniao_shop_1 as s 
                ON s.id = g.shopId 
                WHERE 
                g.deleteStatus = ' . StatusCode::$standard;

        //商品名称
        if (isset($selectParams['keyword']) && !empty($selectParams['keyword'])) {
            $sql .= ' and b.title like "%' . $selectParams['keyword'] . '%"';
        }

        //上架/下架
        if (isset($selectParams['enableStatus']) && !empty($selectParams['enableStatus'])) {
            $sql .= ' and g.enableStatus = ' . $selectParams['enableStatus'];
        }

        //分类筛选
        if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])){
            $sql .= ' and find_in_set('.$selectParams['categoryId'].',b.categoryPath) ';
        }

        //分销状态
        if (isset($selectParams['isJoinCommission']) && !empty($selectParams['isJoinCommission'])) {
            $sql .= ' and g.isJoinCommission = ' . $selectParams['isJoinCommission'];
        }
        $return['total'] = count((array)$this->objDCommissionGoods->query($sql));
        //排序 分页
        $sql .= ' order by g.createTime DESC LIMIT ' . $selectParams['offset'] . ',' . $selectParams['limit'];

        $dbResult = $this->objDCommissionGoods->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCommissionGoods->error(), ErrorCode::$dberror);
        }

        if (empty($dbResult)) {
            return ResultWrapper::success($return);
        }

        $formatData = self::formatList((array)$dbResult);
        if (!$formatData->isSuccess()) {
            return ResultWrapper::fail($formatData->getData(), $formatData->getErrorCode());
        }
        $return['data'] = $formatData->getData();
        return ResultWrapper::success($return);
    }

    /**
     * Doc: (des="格式化分销商品列表数据")
     * User: XMing
     * Date: 2020/7/22
     * Time: 3:14 下午
     * @param array $data
     * @return ResultWrapper
     */
    public function formatList(array $data)
    {
        if (empty($data)) {
            return ResultWrapper::success($data);
        }

        $allGoodsIds = [];
        foreach ($data as $goods) {
            $allGoodsIds[] = $goods['id'];
        }

        //获取分销商品的销量和分销额
        $commissionGoodsStatistics = $this->objDCommissionGoodsStatistics->select(['goodsId' => $allGoodsIds],'goodsId,salesNum,commission');
        if ($commissionGoodsStatistics===false){
            return ResultWrapper::fail($this->objDCommissionGoodsStatistics->error(),ErrorCode::$dberror);
        }
        $commissionGoodsStatisticsMap = [];
        foreach ($commissionGoodsStatistics as $value){
            $commissionGoodsStatisticsMap[$value['goodsId']] = $value;
        }

        foreach ($data as &$item) {
            !is_array($item['images']) && $item['images'] = json_decode($item['images'], true);
            $item['commission'] = isset($commissionGoodsStatisticsMap[$item['id']]) ? $commissionGoodsStatisticsMap[$item['id']]['commission'] : '0.00';//佣金
            $item['inventoryTotal'] = 0;//总库存
            $item['salesCount'] = isset($commissionGoodsStatisticsMap[$item['id']]) ? $commissionGoodsStatisticsMap[$item['id']]['salesNum'] : 0;//总销量
        }

        return ResultWrapper::success($data);
    }

    /**
     * Doc: (des="批量更新商品分销状态")
     * User: XMing
     * Date: 2020/7/22
     * Time: 4:45 下午
     * @param array $params
     * @return ResultWrapper
     */
    public function updateIsJoin(array $params)
    {
        $dbResult = $this->objDGoods->update(['isJoinCommission' => $params['isJoinCommission'], 'updateTime' => time()], ['id' => $params['id']]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoods->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success('操作成功');
    }

    /**
     * Doc: (des="获取分销商品详情")
     * User: XMing
     * Date: 2020/7/22
     * Time: 4:58 下午
     * @param int $id
     * @return ResultWrapper
     * @throws \Exception
     */
    public function getInfo(int $id)
    {
        $fields = 'g.id,g.shopId,b.title,g.isDefine,b.specType,b.images,g.id,g.isJoinCommission,s.warehouseId,g.basicGoodsId,g.retType';
        $sql = 'SELECT ' . $fields . ' FROM qianniao_goods_' . $this->onlineEnterpriseId . ' as g 
                LEFT JOIN qianniao_goods_basic_' . $this->onlineEnterpriseId . ' as b 
                ON b.id = g.basicGoodsId 
                LEFT JOIN qianniao_shop_1 as s 
                ON s.id = g.shopId 
                WHERE g.id = ' . $id;
        $dbResult = $this->objDGoods->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoods->error(), ErrorCode::$dberror);
        }
        if (empty($dbResult)) {
            return ResultWrapper::success([]);
        }
        $dbResult = (array)$dbResult;
        $goodsInfo = array_shift($dbResult);
        $formatData = self::formatDetails($goodsInfo);
        if (!$formatData->isSuccess()) {
            return ResultWrapper::fail($formatData->getData(), $formatData->getErrorCode());
        }
        return ResultWrapper::success($formatData->getData());
    }

    /**
     * Doc: (des="格式化分销商品详情数据")
     * {"grade_1":{"oneRate" : 1,"twoRate":2 ,"threeRate":3}."grade_2":{"oneRate" : 1,"twoRate":2 ,"threeRate":3}}
     * User: XMing
     * Date: 2020/7/22
     * Time: 5:14 下午
     * @param array $data
     * @return ResultWrapper
     * @throws \Exception
     */
    public function formatDetails(array $data)
    {
        if (empty($data)) {
            return ResultWrapper::success([]);
        }

        //获取商品的价格
        $priceSelectParam['material'] = [
            $data['shopId'] => [
                $data['id']
            ]
        ];
        $priceResult = $this->objMPrice->getPrice($priceSelectParam);
        if (!$priceResult->isSuccess()) {
            return ResultWrapper::fail($priceResult->getData(), $priceResult->getErrorCode());
        }
        $priceData = $priceResult->getData();

        //获取商品分销销量
        $CommissionGoodsStatistics = $this->objDCommissionGoodsStatistics->select(['goodsId' => $data['id']],'goodsId,skuId,salesNum');
        if ($CommissionGoodsStatistics  === false){
            return ResultWrapper::fail($this->objDCommissionGoodsStatistics->error(),ErrorCode::$dberror);
        }
        $CommissionGoodsStatisticsMap = [];
        foreach ($CommissionGoodsStatistics as $value){
            $CommissionGoodsStatisticsMap[$value['skuId']] = $value;
        }

        //获取商品的所有sku
        $skuResult = $this->objDSku->select(['goodsId' => $data['basicGoodsId'], 'deleteStatus' => StatusCode::$standard]);
        if ($skuResult === false) {
            return ResultWrapper::fail($this->objDSku->error(), ErrorCode::$dberror);
        }

        $skuIds = [];
        foreach ($skuResult as $item){
            $skuIds[] = $item['id'];
        }

        $inventoryResult = $this->objMInventory->getInventoryByShopIdAndSkuIds($data['shopId'],$skuIds);
        if (!$inventoryResult->isSuccess()){
            return ResultWrapper::fail($inventoryResult->getData(),$inventoryResult->getErrorCode());
        }
        $inventoryData = $inventoryResult->getData();

        $skuMap = [];
        foreach ($skuResult as $item) {
            $skuMap[$item['goodsId']][] = [
                'skuId'         => $item['id'],
                'unitName'      => $item['unitName'],
                'specGroupHash' => $item['specGroupHash'],
                'specData'      => empty($item['specData']) ? [] : json_decode($item['specData'], true),
                'price'         => isset($priceData[$data['shopId']][$data['id']][$item['id']]['salePrice']) ? $priceData[$data['shopId']][$data['id']][$item['id']]['salePrice'] : 0,
                'saleNum'       => isset($CommissionGoodsStatisticsMap[$item['id']]) ? $CommissionGoodsStatisticsMap[$item['id']]['salesNum'] : 0,
                'inventory'     => isset($inventoryData[$item['id']]['num']) ? $inventoryData[$item['id']]['num'] : 0,
            ];
        }

        //查询商品自定义比率
        $commissionData = [];
        if ($data['isDefine'] == StatusCode::$standard) {
            $commissionGoods = $this->objDCommissionGoods->select(['deleteStatus' => StatusCode::$standard, 'goodsId' => $data['id']]);
            if ($commissionGoods === false) {
                return ResultWrapper::fail($this->objDCommissionGoods->error(), ErrorCode::$dberror);
            }
            foreach ($commissionGoods as $item) {
                $commissionData[$item['skuId']] = json_decode($item['commissionRule'], true);
            }
        }

        //获取等级佣金比例
        $gradeResult = $this->objDCommissionGrade->select(['enterpriseId' => $this->onlineEnterpriseId, 'deleteStatus' => StatusCode::$standard, 'enableStatus' => StatusCode::$standard],'*','grade ASC');
        if ($gradeResult === false) {
            return ResultWrapper::fail($this->objDCommissionGrade->error(), ErrorCode::$dberror);
        }

        !is_array($data['images']) && $data['images'] = json_decode($data['images'], true);
        $data['specMultiple'] = isset($skuMap[$data['basicGoodsId']]) ? $skuMap[$data['basicGoodsId']] : [];
        $default_rule = [];
        $commission_rule = [];
        foreach ($gradeResult as $key => $row) {
            $rule = [];
            $default_rule[] = [
                'name'  => $row['name'],
                'grade' => $row['grade'],
                'rule'  => [
                    'oneRate'   => $row['oneRate'],
                    'twoRate'   => $row['twoRate'],
                    'threeRate' => $row['threeRate']
                ]
            ];

            $commission_rule[$key] = [
                'name'  => $row['name'],
                'grade' => $row['grade']
            ];

            foreach ($data['specMultiple'] as $datum) {
                $rule[] = [
                    'skuId'     => $datum['skuId'],
                    'unitName'  => $datum['unitName'],
                    'specData'  => $datum['specData'],
                    'saleNum'   => $datum['saleNum'],
                    'price'     => $datum['price'],
                    'inventory' => $datum['inventory'],
                    'oneRate'   => isset($commissionData[$datum['skuId']][$row['grade']]) ? $commissionData[$datum['skuId']][$row['grade']]['oneRate'] : 0,
                    'twoRate'   => isset($commissionData[$datum['skuId']][$row['grade']]) ? $commissionData[$datum['skuId']][$row['grade']]['twoRate'] : 0,
                    'threeRate' => isset($commissionData[$datum['skuId']][$row['grade']]) ? $commissionData[$datum['skuId']][$row['grade']]['threeRate'] : 0
                ];
            }
            $commission_rule[$key]['rule'] = $rule;
        }

        $data['default_rule'] = $default_rule;//默认规则
        $data['commission_rule'] = $commission_rule;//自定义规则
        return ResultWrapper::success($data);
    }

    /**
     * Doc: (des="自定义分销商品")
     * User: XMing
     * Date: 2020/7/22
     * Time: 6:17 下午
     * @param array $data
     * @return ResultWrapper
     * @example {"id":131,"isDefine":5,"isJoinCommission":5,"commission_rule":[{"skuId":1036,"rule":{"0":{"oneRate":1,"twoRate":2,"threeRate":3},"2":{"oneRate":4,"twoRate":5,"threeRate":6},"3":{"oneRate":7,"twoRate":8,"threeRate":9},"4":{"oneRate":10,"twoRate":11,"threeRate":12}}},{"skuId":1037,"rule":{"0":{"oneRate":1,"twoRate":2,"threeRate":3},"2":{"oneRate":4,"twoRate":5,"threeRate":6},"3":{"oneRate":7,"twoRate":8,"threeRate":9},"4":{"oneRate":10,"twoRate":11,"threeRate":12}}},{"skuId":1038,"rule":{"0":{"oneRate":1,"twoRate":2,"threeRate":3},"2":{"oneRate":4,"twoRate":5,"threeRate":6},"3":{"oneRate":7,"twoRate":8,"threeRate":9},"4":{"oneRate":10,"twoRate":11,"threeRate":12}}}]}
     */
    public function setCommission(array $data)
    {
        $this->objDCommissionGoods->beginTransaction();
        //非单独设置
        $dbResult = $this->objDGoods->update([
            'isJoinCommission' => $data['isJoinCommission'],
            'isDefine'         => $data['isDefine'],
            'retType'          => $data['retType'],
            'updateTime'       => time()
        ], ['id' => $data['id']]);

        if ($dbResult === false) {
            $this->objDGoods->rollBack();
            return ResultWrapper::fail($this->objDGoods->error(), ErrorCode::$dberror);
        }

        if (isset($data['isDefine']) && $data['isDefine'] == StatusCode::$standard) {
            //单独设置了分销数据
            $insert = [];
            //[{"skuId":135,"rule":{"grade_1":{"oneRate" : 1,"twoRate":2 ,"threeRate":3}."grade_2":{"oneRate" : 1,"twoRate":2 ,"threeRate":3}}}]
            foreach ($data['commission_rule'] as $item) {
                $insert[] = [
                    'goodsId'        => $data['id'],
                    'skuId'          => $item['skuId'],
                    'commissionRule' => json_encode($item['rule'])
                ];
            }
            $commissionGoodsResult = $this->objDCommissionGoods->replace($insert, true);
            if ($commissionGoodsResult === false) {
                $this->objDCommissionGoods->rollBack();
                return ResultWrapper::fail($this->objDCommissionGoods->error(), ErrorCode::$dberror);
            }
        }

        $this->objDCommissionGoods->commit();
        return ResultWrapper::success('操作成功');
    }

    /**
     * Doc: (des="格式化分销商品数据")
     * User: XMing
     * Date: 2020/7/28
     * Time: 7:50 下午
     * @param array $params
     * @param int $customerId
     * @throws \Exception
     * @return ResultWrapper
     */
    public function formatGoods(array $params,$customerId = null)
    {
        $allGoodsIds = [];
        $allSkuIds = [];
        foreach ($params as $value){
            $allGoodsIds[] = $value['goodsId'];
            $allSkuIds[] = $value['skuId'];
        }
        $allGoodsIdStr = implode(',',$allGoodsIds);
        $fields = 'g.id,g.basicGoodsId,g.shopId,b.title as goodsName,b.images,b.describe,s.warehouseId,s.name as shopName';
        $sql = 'select '.$fields.' from qianniao_goods_'.$this->onlineEnterpriseId.' as g 
                left join qianniao_goods_basic_'.$this->onlineEnterpriseId.' as b 
                on b.id = g.basicGoodsId 
                left join qianniao_shop_1 as s 
                on g.shopId = s.id 
                where g.id in('.$allGoodsIdStr.')';
        $goods = $this->objDGoods->query($sql);
        if ($goods === false){
            Logger::logs(E_USER_ERROR,'sql',__CLASS__,__LINE__,$this->objDGoods->error());
            return ResultWrapper::fail($this->objDGoods->error(),ErrorCode::$dberror);
        }
        $priceSelectParam  = [];
        $allGoodsMap = [];//商品集合
        if (!empty($customerId)){
            $priceSelectParam['customerId'] = $customerId;
        }
        foreach ($goods as &$value){
            $priceSelectParam['material'][$value['shopId']][] = $value['id'];
            $value['images'] = empty($value['images']) ? [] : json_decode($value['images'],true);
            $allGoodsMap[$value['id']] = $value;
        }
        unset($value);

        //获取所有单位
        $sku = $this->objDSku->select(['id'=>$allSkuIds],'id,unitName,specData,isNew');
        if ($sku === false){
            Logger::logs(E_USER_ERROR,'sql',__CLASS__,__LINE__,$this->objDSku->error());
            return ResultWrapper::fail($this->objDSku->error(),ErrorCode::$dberror);
        }
        $skuMap = [];//sku集合
        foreach ($sku as &$value){
            $value['specGroup'] = empty($value['specData']) ? [] : json_decode($value['specData'],true);
            $skuMap[$value['id']] = $value;
        }
        unset($value);

        //获取商品的价格
        $priceResult = $this->objMPrice->getPrice($priceSelectParam);
        if (!$priceResult->isSuccess()) {
            Logger::logs(E_USER_ERROR,'sql',__CLASS__,__LINE__,$priceResult->getData());
            return ResultWrapper::fail($priceResult->getData(), $priceResult->getErrorCode());
        }
        $priceData = $priceResult->getData();

        //获取库存
        //获取商品的库存
        $inventorySelectParams = [];
        foreach ($goods as $value){
            $inventorySelectParams[$value['shopId']][] = $value['skuId'];
        }

        $inventoryMap = [];
        foreach ($inventorySelectParams as $shopId => $skuIds){
            $inventoryResult = $this->objMInventory->getInventoryByShopIdAndSkuIds($shopId,$skuIds);
            if (!$inventoryResult->isSuccess()){
                return ResultWrapper::fail($inventoryResult->getData(),$inventoryResult->getErrorCode());
            }
            $inventoryMap[$shopId] = $inventoryResult->getData();
        }

        foreach ($params as $key =>  &$param){
            if (!isset($skuMap[$param['skuId']]) || !isset($allGoodsMap[$param['goodsId']])){
                unset($params[$key]);
            }
            $param['basicGoodsId'] = isset($allGoodsMap[$param['goodsId']]) ? $allGoodsMap[$param['goodsId']]['basicGoodsId'] : 0;
            $param['shopId'] = isset($allGoodsMap[$param['goodsId']]) ? $allGoodsMap[$param['goodsId']]['shopId'] : 0;
            $param['salePrice'] = isset($priceData[$param['shopId']][$param['goodsId']][$param['skuId']]) ? $priceData[$param['shopId']][$param['goodsId']][$param['skuId']]['salePrice'] : 0;
            $param['marketPrice'] = isset($priceData[$param['shopId']][$param['goodsId']][$param['skuId']]) ? $priceData[$param['shopId']][$param['goodsId']][$param['skuId']]['marketPrice'] : 0;
            $param['unitName'] = isset($skuMap[$param['skuId']]) ? $skuMap[$param['skuId']]['unitName'] : '';
            $param['specGroup'] = isset($skuMap[$param['skuId']]) ? $skuMap[$param['skuId']]['specGroup'] : [];
            $param['inventory'] = isset($inventoryMap[$param['shopId']][$param['skuId']]['num']) ? $inventoryMap[$param['shopId']][$param['skuId']]['num'] : 0;
            $param['images'] = isset($allGoodsMap[$param['goodsId']]) ? $allGoodsMap[$param['goodsId']]['images'] : [];
            $param['goodsName'] = isset($allGoodsMap[$param['goodsId']]) ? $allGoodsMap[$param['goodsId']]['goodsName'] : '';
        }
        return ResultWrapper::success($params);
    }

    /**
     * Doc: (des="换算库存")
     * User: XMing
     * Date: 2020/7/29
     * Time: 10:00 上午
     * @param array $inventory
     * @return ResultWrapper
     */
    public function conversionInventory(array $inventory)
    {
        //查询出所有基础商品sku数据
        $allGoodsBasicIds = [];
        foreach ($inventory as $key => $value){
            $allGoodsBasicIds[] = $key;
        }
        $allSku = $this->objDSku->select(['goodsId'=>$allGoodsBasicIds,'deleteStatus'=>StatusCode::$standard],'id,goodsId,unitId,isMaster,specGroupHash,conversion,specType,isNew');
        if ($allSku === false){
            return ResultWrapper::fail($this->objDSku->error(),ErrorCode::$dberror);
        }
        $allSkuMap = [];
        $allSkuHashMap = [];
        foreach ($allSku as $value){
            $allSkuMap[$value['goodsId']][$value['id']] = $value;
            $hash = md5($value['goodsId'].$value['isMaster'].$value['specGroupHash']);
            $allSkuHashMap[$value['goodsId']][$hash] = $value;
        }

        foreach ($allSkuMap as $goodsBasicId => $items){
            foreach($items as $skuId => $item){
                if ($item['isMaster'] == StatusCode::$standard){
                    $allSkuMap[$goodsBasicId][$skuId]['inventoryNum'] = isset($inventory[$goodsBasicId][$skuId]['inventoryNum']) ? $inventory[$goodsBasicId][$skuId]['inventoryNum'] : 0;
                    $allSkuMap[$goodsBasicId][$skuId]['costPrice'] = isset($inventory[$goodsBasicId][$skuId]['costPrice']) ? $inventory[$goodsBasicId][$skuId]['costPrice'] : 0;
                    continue;
                }

                //辅助单位
                //获取到辅助单位对应主单位skuId
                $hash = md5($goodsBasicId.StatusCode::$standard.$item['specGroupHash']);
                if (!isset($allSkuHashMap[$goodsBasicId][$hash]['id'])){
                    $allSkuMap[$goodsBasicId][$skuId]['inventoryNum'] = 0;
                    $allSkuMap[$goodsBasicId][$skuId]['costPrice'] = 0;
                    continue;
                }
                $conversion = $item['conversion'];
                $masterSkuId = $allSkuHashMap[$goodsBasicId][$hash]['id'];
                //获取主单位库存
                if (!isset($inventory[$goodsBasicId][$masterSkuId]['inventoryNum'])){
                    $allSkuMap[$goodsBasicId][$skuId]['inventoryNum'] = 0;
                    $allSkuMap[$goodsBasicId][$skuId]['costPrice'] = 0;
                    continue;
                }
                $masterInv = $inventory[$goodsBasicId][$masterSkuId]['inventoryNum'];
                $masterCostPrice = $inventory[$goodsBasicId][$masterSkuId]['costPrice'];
                if ($masterInv == 0){
                    $allSkuMap[$goodsBasicId][$skuId]['inventoryNum'] = 0;
                    $allSkuMap[$goodsBasicId][$skuId]['costPrice'] = 0;
                    continue;
                }
                if ($item['isNew'] == StatusCode::$standard){
                    //新
                    //主换辅 除
                    $inventoryNum = bcdiv($masterInv,$conversion,8);
                }else{
                    //旧
                    //主换辅 乘
                    $inventoryNum = bcmul($masterInv,$conversion,8);
                }
                //$inventoryNum = bcmul($masterInv,$conversion,8);
                $allSkuMap[$goodsBasicId][$skuId]['inventoryNum'] = $inventoryNum;
                $allSkuMap[$goodsBasicId][$skuId]['costPrice'] = $masterCostPrice;
            }
        }
        return ResultWrapper::success($allSkuMap);
    }
}