<?php
/**
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2019/12/18
 * Time: 12:13
 */

namespace JinDouYun\Model\Market;

use JinDouYun\Dao\Market\DActivityGoods;
use JinDouYun\Model\Goods\MGoods;
use JinDouYun\Model\GoodsManage\MSku;
use JinDouYun\Model\MBaseModel;
use JinDouYun\Model\Price\MPrice;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

class MActivityGoods extends MBaseModel
{
    /**
     * @var int
     */
    private $onlineUserId;

    /**
     * @var int
     */
    private $onlineEnterpriseId;

    /**
     * @var DActivityGoods
     */
    private $objDActivityGoods;

    /**
     * @var MSku
     */
    private $objMSku;

    /**
     * MActivityGoods constructor.
     * @param $onlineUserId
     * @param $onlineEnterpriseId
     * @throws \Exception
     */
    public function __construct($onlineUserId, $onlineEnterpriseId)
    {
        $this->onlineUserId = $onlineUserId;
        $this->onlineEnterpriseId = $onlineEnterpriseId;
        parent::__construct($this->onlineEnterpriseId, $onlineUserId);

        $this->objMSku = new MSku($this->onlineUserId,$this->onlineEnterpriseId);
        $this->objDActivityGoods = new DActivityGoods('default');
        $this->objDActivityGoods->setTable($this->objDActivityGoods->get_Table() . '_' . $this->onlineEnterpriseId);
    }

    /**
     * @param $params
     * @param bool $multiple
     * @return ResultWrapper
     */
    public function add($params, $multiple = false)
    {
        $dbResult = $this->objDActivityGoods->insert($params, $multiple);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDActivityGoods->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * @param $selectParams
     * @param string $fields
     * @return ResultWrapper
     * @throws \Exception
     */
    public function getActivityGoods($selectParams, $fields = '*', $format = true)
    {
        $dbResult = $this->objDActivityGoods->select($selectParams, $fields);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDActivityGoods->error(), ErrorCode::$dberror);
        }
        if ($format === true) $dbResult = self::format($dbResult);
        return ResultWrapper::success($dbResult);
    }

    /**
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function format($data)
    {
        if (empty($data)) return $data;
        $objMPrice = new MPrice($this->onlineUserId, $this->onlineEnterpriseId);
        $selectParam['material'] = [];
        //$skuData = parent::getSkuNameByIds($this->onlineEnterpriseId, array_column($data, 'skuId'));//旧的sku
        $skuResult = $this->objMSku->getSpecNameBySkuId(array_column($data, 'skuId'));
        $skuData = [];
        if ($skuResult->isSuccess()){
            $skuData = $skuResult->getData();
        }

        $objMGoods = new MGoods($this->onlineEnterpriseId, true, $this->onlineUserId);
        $goodsData = $objMGoods->getNameByGoodsIds(array_column($data, 'basicGoodsId'));
        if ($goodsData->isSuccess()) {
            $goodsData = $goodsData->getData();
        } else {
            $goodsData = [];
        }
        foreach ($data as &$val) {
            $val['goodsName'] = isset($goodsData[$val['basicGoodsId']]['title']) ? $goodsData[$val['basicGoodsId']]['title'] : '';
            $val['unitName'] = isset($skuData[$val['skuId']]) ? $skuData[$val['skuId']]['nameFields'] : '';
            $val['goodsCode'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $val['goodsId'], StatusCode::$code['goodsBasic']['length']);
            $val['images'] = isset($goodsData[$val['basicGoodsId']]['images']) ? $goodsData[$val['basicGoodsId']]['images'] : '';
            $val['describe'] = isset($goodsData[$val['basicGoodsId']]['describe']) ? $goodsData[$val['basicGoodsId']]['describe'] : '';
            $selectParam['material'][$val['shopId']][] = $val['goodsId'];
        }
        $dbResult = $objMPrice->getPrice($selectParam);
        if (!$dbResult->isSuccess()) {
            return $data;
        }
        $priceResult = $dbResult->getData();
        $goodsArr = [];
        foreach ($priceResult as $shopPriceArr) {
            foreach ($shopPriceArr as $goodsId => $goodsSkuArr) {
                $goodsArr[$goodsId] = $goodsSkuArr;
            }
        }
        foreach ($data as &$goods) {
            $goods["salePrice"] = isset($goodsArr[$goods['goodsId']][$goods['skuId']]['salePrice']) ? $goodsArr[$goods['goodsId']][$goods['skuId']]['salePrice'] : '';
        }
        return $data;
    }

    /**
     * @param $params
     * @param $id
     * @param $deleteArray
     * @return ResultWrapper
     */
    public function edit($params, $id, $deleteArray)
    {
        $this->objDActivityGoods->beginTransaction();
        if (!empty($deleteArray)) {
            $dbResult = $this->objDActivityGoods->update(['deleteStatus' => StatusCode::$delete], $deleteArray);
            if ($dbResult === false) {
                $this->objDActivityGoods->rollBack();
                return ResultWrapper::fail($this->objDActivityGoods->error(), ErrorCode::$dberror);
            }
        }

        foreach ($params as &$details) {
            if (isset($details['id']) && !empty($details['id'])) {
                $dbResult = $this->objDActivityGoods->update($details, ['id' => $details['id']]);
                if ($dbResult === false) {
                    $this->objDActivityGoods->rollBack();
                    return ResultWrapper::fail($this->objDActivityGoods->error(), ErrorCode::$dberror);
                }
            } else {
                $insert[] = [
                    'goodsId'      => isset($details['goodsId']) ? $details['goodsId'] : '',
                    'shopId'       => isset($details['shopId']) ? $details['shopId'] : '',
                    'skuId'        => isset($details['skuId']) ? $details['skuId'] : '',
                    'price'        => isset($details['price']) ? $details['price'] : '',
                    'basicGoodsId' => isset($details['basicGoodsId']) ? $details['basicGoodsId'] : '',
                    'activityNum'  => isset($details['activityNum']) ? $details['activityNum'] : 0,
                    'limitNum'     => isset($details['limitNum']) ? $details['limitNum'] : 0,
                    'activityId'   => $id,
                ];
            }
        }


        if (!empty($insert)) {
            $dbResult = $this->objDActivityGoods->insert($insert, true);
            if ($dbResult === false) {
                $this->objDActivityGoods->rollBack();
                return ResultWrapper::fail($this->objDActivityGoods->error(), ErrorCode::$dberror);
            }
        }

        $this->objDActivityGoods->commit();
        return ResultWrapper::success($dbResult);
    }
}