<?php
/**
 * 采购订单商品明细数据模型
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2019/11/11
 * Time: 17:57
 */

namespace JinDouYun\Model\Purchase;

use JinDouYun\Dao\Purchase\DPurchaseGoods;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

class MPurchaseGoods
{
    private $objDPurchaseGoods;

    private $onlineUserId;

    private $onlineEnterpriseId;

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

        $this->objDPurchaseGoods = new DPurchaseGoods('stock');
        $this->objDPurchaseGoods->setTable($this->objDPurchaseGoods->get_Table() . '_' . $this->onlineEnterpriseId);
    }

    /**
     * 添加采购商品信息
     * @param $params
     * @return ResultWrapper
     */
    public function addPurchaseGoods($params)
    {
        $dbResult = $this->objDPurchaseGoods->insert($params, true);

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

        return ResultWrapper::success($dbResult);
    }

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

        $insert = [];
        foreach ($params as &$details) {
            if (isset($details['id']) && !empty($details['id'])) {
                $dbResult = $this->objDPurchaseGoods->update($details, ['id' => $details['id']]);
                if ($dbResult === false) {
                    $this->objDPurchaseGoods->rollBack();
                    return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
                }
            } else {
                $insert[] = [
                    'basicGoodsId'   => $details['basicGoodsId'],
                    'goodsCode'      => $details['goodsCode'],
                    'goodsName'      => $details['goodsName'],
                    'skuId'          => $details['skuId'],
                    'buyerNum'       => $details['buyerNum'],
                    'buyerUnitPrice' => $details['buyerUnitPrice'],
                    'subtotalPrice'  => $details['subtotalPrice'],
                    'couponAmount'   => $details['couponAmount'],
                    'otherAmount'    => $details['otherAmount'],
                    'purchaseId'     => $actionIds['purchaseId'],
                ];
            }
        }
        if (!empty($insert)) {
            $dbResult = $this->objDPurchaseGoods->insert($insert, true);
            if ($dbResult === false) {
                $this->objDPurchaseGoods->rollBack();
                return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
            }
        }

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

    /**
     * 通过采购单id获取采购单下的商品
     * @param $ids
     * @return ResultWrapper
     */
    public function getGoodsByPurchaseIds($ids)
    {
        $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $ids,'deleteStatus'=>StatusCode::$standard]);

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

        return ResultWrapper::success(self::formatJson($dbResult));
    }

    /**
     * 获取采购单信息
     */
    public function getPurchaseGoodsData($where = [])
    {
        $where['deleteStatus'] = StatusCode::$standard;
        $dbResult = $this->objDPurchaseGoods->select($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
        }
        $formatData = [];
        foreach($dbResult as $value){
            $formatData[$value['skuId']] = $value;
        }
        return ResultWrapper::success($formatData);
    }

    /**
     * @param $data
     * @return mixed
     */
    public function formatJson($data)
    {
        if (isset($data['id'])) {
            $data['unit'] = empty($data['unit']) ? '' : json_decode($data['unit'], true);
            return $data;
        }

        foreach ($data as &$v) {
            $v['unit'] = empty($v['unit']) ? '' : json_decode($v['unit'], true);
        }
        return $data;
    }
}