<?php


namespace JinDouYun\Model\Order;


use JinDouYun\Dao\Order\DSupplierOrderDetails;
use JinDouYun\Dao\Order\DSupplierOrderIndex;
use JinDouYun\Model\Customer\MCustomer;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

/**
 * @copyright   Copyright (c) https://www.qianniaovip.com All rights reserved
 * Description:
 * Class MSupplierOrderDetails
 * @package JinDouYun\Model\Order
 */
class MSupplierOrderDetails
{
    private $enterpriseId;

    private $userCenterId;

    private $objDSupplierOrderDetails;

    public static $cutTable = 50000;

    public $objDSupplierOrderIndex;

    /**
     * MSupplierOrderDetails constructor.
     * @param $enterpriseId
     * @param $userCenterId
     * @throws \Exception
     */
    public function __construct($enterpriseId, $userCenterId)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        $this->objDSupplierOrderDetails = new DSupplierOrderDetails();
        $this->objDSupplierOrderIndex = new DSupplierOrderIndex();
        $this->objDSupplierOrderIndex->setTable('qianniao_supplier_order_index_'.$this->enterpriseId);
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2020/12/22
     * Time: 5:22 下午
     * @param array $selectParams
     */
    private function buildSqlBySelectParams(array $selectParams): array
    {
        $fields = ' o.id as orderId,s.*';
        $countFields = ' COUNT(o.id) as total ';
        $whereSql = '';

        if (isset($selectParams['supplierId']) && !empty($selectParams['supplierId'])){
            $whereSql .= ' AND s.supplierId = '.$selectParams['supplierId'];
        }

        if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])){
            $whereSql .= ' AND o.auditStatus = '.$selectParams['auditStatus'];
        }

        if (isset($selectParams['startTime']) && !empty($selectParams['startTime'])){
            $whereSql .= ' AND o.createTime BETWEEN '.$selectParams['startTime'].' AND '.$selectParams['endTime'];
        }

        $countSql = 'SElECT '.$countFields.' FROM qianniao_order_index_'.$this->enterpriseId.' AS o 
                    LEFT JOIN qianniao_supplier_order_index_'.$this->enterpriseId.' as s 
                    ON s.no = o.no WHERE o.deleteStatus = '.StatusCode::$standard.$whereSql;

        $whereSql .= ' GROUP BY s.no ';
        $whereSql .= ' ORDER BY o.createTime DESC ';

        if (isset($selectParams['limit']) && !empty($selectParams['limit'])){
            $whereSql .= ' LIMIT '.$selectParams['offset'].','.$selectParams['limit'];
        }

        $sql = 'SElECT '.$fields.' FROM qianniao_order_index_'.$this->enterpriseId.' AS o 
                    LEFT JOIN qianniao_supplier_order_index_'.$this->enterpriseId.' as s 
                    ON s.no = o.no WHERE o.deleteStatus = '.StatusCode::$standard.$whereSql;
        return [
            'sql' => $sql,
            'countSql' => $countSql
        ];
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2020/12/22
     * Time: 5:21 下午
     * @param array $selectParams
     * @return ResultWrapper
     */
    public function getAll(array $selectParams): ResultWrapper
    {
        $buildSql = self::buildSqlBySelectParams($selectParams);
        $indexLists = $this->objDSupplierOrderIndex->query($buildSql['sql']);
        if ($indexLists === false){
            return ResultWrapper::fail($this->objDSupplierOrderIndex->error(),ErrorCode::$dberror);
        }

        $count = $this->objDSupplierOrderIndex->query($buildSql['countSql']);

        $customerIds = [];
        foreach ($indexLists as $list){
            $customerIds[] = $list['customerId'];
        }
        $objMCustomer = new MCustomer($this->enterpriseId,$this->userCenterId);
        $reservoirMapResult = $objMCustomer->getReservoirByCustomerIds($customerIds);
        if (!$reservoirMapResult->isSuccess()){
            return ResultWrapper::fail($reservoirMapResult->getData(),$reservoirMapResult->getErrorCode());
        }
        $reservoirMap = $reservoirMapResult->getData();

        foreach ($indexLists as &$list){
            $list['reservoir'] = !empty($list['reservoir']) ? json_decode($list['reservoir'],true) : [];
            if (empty($list['reservoir'])){
                $list['reservoir'] = getArrayItem($reservoirMap,$list['customerId'],[]);
            }
        }
        $ret = [
            'data' => $indexLists,
            'total' => isset($count[0]['total']) ? $count[0]['total'] : 0,
        ];
        return ResultWrapper::success($ret);
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2020/12/22
     * Time: 6:16 下午
     * @param int $id
     * @return ResultWrapper
     * @throws \Exception
     */
    public function get(int $id): ResultWrapper
    {
        $index = $this->objDSupplierOrderIndex->get($id);
        if ($index === false){
            return ResultWrapper::fail($this->objDSupplierOrderIndex->error(),ErrorCode::$dberror);
        }
        if (empty($index)){
            return ResultWrapper::fail('未获取到指定订单',ErrorCode::$paramError);
        }
        $fix = ceil($index['orderId'] / self::$cutTable);
        $this->objDSupplierOrderDetails->setTable('qianniao_supplier_order_details_'.$this->enterpriseId.'_'.$fix);
        $details = $this->objDSupplierOrderDetails->select(['no' => $index['no']]);
        if ($details === false){
            return ResultWrapper::fail($this->objDSupplierOrderDetails->error(),ErrorCode::$dberror);
        }

        $customerIds = [];
        foreach ($details as $list){
            if (!in_array($list['customerId'],$customerIds)){
                $customerIds[] = $list['customerId'];
            }
        }
        $objMCustomer = new MCustomer($this->enterpriseId,$this->userCenterId);
        $reservoirMapResult = $objMCustomer->getReservoirByCustomerIds($customerIds);
        if (!$reservoirMapResult->isSuccess()){
            return ResultWrapper::fail($reservoirMapResult->getData(),$reservoirMapResult->getErrorCode());
        }
        $reservoirMap = $reservoirMapResult->getData();

        $index['reservoir'] = !empty($index['reservoir']) ? json_decode($index['reservoir'],true) : [];

        foreach ($details as &$val){
            $val['specGroup'] = !empty($val['specGroup']) ? json_decode($val['specGroup'],true) : [];
            unset($val['reservoir']);
            if (empty($index['reservoir'])){
                $index['reservoir'] = getArrayItem($reservoirMap,$val['customerId'],[]);
            }
        }
        $index['details'] = $details;
        return ResultWrapper::success($index);
    }

    /**
     * Doc: (des="修改-采购单生成状态")
     * User: XMing
     * Date: 2020/12/24
     * Time: 9:23 上午
     * @param $ids
     * @return ResultWrapper
     */
    public function updatePurchaseStatus($ids): ResultWrapper
    {
        $result = $this->objDSupplierOrderIndex->update(['purchaseStatus' => StatusCode::$standard,'updateTime' => time()],['id' => $ids]);
        if ($result === false){
            return ResultWrapper::fail($this->objDSupplierOrderIndex->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success(true);
    }

    /**
     * Doc: (des="获取供应商订单数量")
     * User: XMing
     * Date: 2020/12/26
     * Time: 4:46 下午
     * @param $supplierId
     * @return ResultWrapper
     */
    public function getTotalBySupplierId($supplierId): ResultWrapper
    {
        $selectParams = [
            'supplierId' => $supplierId,
            'auditStatus' => StatusCode::$auditStatus['auditPass'],
        ];
        $buildSql = self::buildSqlBySelectParams($selectParams);
        $count = $this->objDSupplierOrderIndex->query($buildSql['countSql']);
        if ($count === false){
            return ResultWrapper::fail($this->objDSupplierOrderIndex->error(),ErrorCode::$dberror);
        }
        $total = isset($count[0]['total']) ? $count[0]['total'] : 0;
        return ResultWrapper::success($total);
    }
}