<?php
/**
 * Created by PhpStorm.
 * User: Gss
 * Date: 2021/5/19 0019
 * Time: 10:51
 */

namespace JinDouYun\Model\Order;

use JinDouYun\Controller\Market\VipCard;
use JinDouYun\Controller\Order\Order;
use JinDouYun\Dao\Order\DOrder;
use JinDouYun\Dao\Order\DOrderGoods;
use JinDouYun\Dao\Order\DOrderIndex;
use JinDouYun\Dao\Order\DOrderPicking;
use JinDouYun\Dao\Order\DOrderReceive;
use JinDouYun\Model\MBaseModel;
use JinDouYun\Model\SysAreaChina\MSysAreaChina;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

class MOrderPicking extends MBaseModel
{
    /**
     * @var int 用户id
     */
    private $onlineUserId;

    /**
     * @var int 企业id
     */
    private $onlineEnterpriseId;

    /**
     * @var int 单表数据量
     */
    private $cutTable = 200000;

    private $loginUserCenterId;

    private $isCashier;

    private $isFront;

    private $objDOrderPicking;

    /**
     * MOrder constructor.
     * @param $onlineUserId
     * @param $onlineEnterpriseId
     * @param null $loginUserCenterId
     * @param bool $isFront
     * @throws \Exception
     */
    public function __construct($onlineUserId, $onlineEnterpriseId, $loginUserCenterId = null, $isFront = false, $isCashier = false)
    {
        $this->isCashier = $isCashier;
        $this->isFront = $isFront;
        $this->onlineUserId = $onlineUserId;
        $this->onlineEnterpriseId = $onlineEnterpriseId;
        $this->loginUserCenterId = $loginUserCenterId;
        parent::__construct($this->onlineEnterpriseId, $loginUserCenterId);

        $this->objDOrderPicking = new DOrderPicking('default');
        self::orderPickSubTable($onlineEnterpriseId, $onlineUserId);
    }

    /**
     * 订单拣货表切表
     */
    public function orderPickSubTable($enterpriseId, $userId)
    {
        $tableName = $this->objDOrderPicking->getTableName('qianniao_order_picking_' . $enterpriseId, $userId, $this->cutTable);
        $this->objDOrderPicking->setTable($tableName);
    }

    /**
     * 获取订单拣货表表名
     */
    public function getOrderPickTable($enterpriseId, $userId){
        return $this->objDOrderPicking->getTableName('qianniao_order_picking_' . $enterpriseId, $userId, $this->cutTable);
    }

    /**
     * 列表
     */
    public function getAllOrderPicking($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $whereSql = '';
        if (isset($selectParams['no']) && !empty($selectParams['no'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' no like "%' . $selectParams['no'] .'%"';
        }
        //时间删选  有timeName字段优先
        if( isset($selectParams['timeName']) && !empty($selectParams['timeName']) ){
            $timeName = $selectParams['timeName'];
            $timestamp = gettimestamp($timeName,time());
            $where = empty($whereSql) ? ' WHERE ' : '  AND ';
            $whereSql .= $where . ' createTime BETWEEN ' . $timestamp['start'] . ' AND '. $timestamp['end'];
        }else{
            if ( (isset($selectParams['startTime']) && !empty($selectParams['startTime']))&&(isset($selectParams['endTime']) && !empty($selectParams['endTime'])) ) {
                $where = empty($whereSql) ? ' WHERE ' : '  AND ';
                $whereSql .= $where . ' createTime BETWEEN ' . $selectParams['startTime'] . ' AND '. $selectParams['endTime'];
            }
        }
        $where = empty($whereSql) ? ' WHERE ' : '  AND ';
        $whereSql .= $where . ' orderStatus != ' . StatusCode::$orderStatus['finish'].' and orderStatus != '.StatusCode::$orderStatus['close'].' and pickingStatus = '.StatusCode::$orderPickStatus['notPicking'] ;

        $objOrder = new DOrder();
        $objDOrderIndex = new DOrderIndex();
        $objDOrderReceive = new DOrderReceive();
        $objMSysAreaChina = new MSysAreaChina();

        $indexSql = 'select * from qianniao_order_index_'.$this->onlineEnterpriseId.$whereSql . ' ORDER BY createTime DESC LIMIT ' . $offset . ' , ' . $limit;
        $indexDbResult = $objDOrderIndex->query($indexSql);
        if ($indexDbResult === false) {
            return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
        }

        $totalSql = 'SELECT COUNT(1) as count FROM qianniao_order_index_'.$this->onlineEnterpriseId.$whereSql;
        $dbTotalResult = $objDOrderIndex->query($totalSql);
        if ($dbTotalResult === false) {
            return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
        }
        if(empty($dbTotalResult)){
            return ResultWrapper::success([]);
        }

        $allOrderData = [];//订单集
        $allOrderReceiveData = [];//订单收货地址集
        $allGroupData = []; // 订单id
        if(!empty($indexDbResult)){
            foreach ($indexDbResult as $indexKey => $indexValue) {
                $tableNum = ceil($indexValue['userCenterId'] / $this->cutTable);
                $allGroupData[$tableNum][] = $indexValue['id'];
            }
            //
            foreach ($allGroupData as $k => $orderId) {
                $objOrder->setTable('qianniao_order_' . $this->onlineEnterpriseId . '_' . $k);
                $tmpOrderId = implode(',',$orderId);

                $orderSql = 'select o.*, p.sort,p.outNum,p.notOutNum,p.orderNum,p.notPickingNum,p.pickingNum,p.otherNum,p.mangeId,p.mangeName from '.$objOrder->get_Table().' as o left join '.$this->objDOrderPicking->get_Table().' as p on o.id=p.orderId where o.id in ('.$tmpOrderId.') ORDER BY o.createTime desc';
                $dbResult = $objOrder->query($orderSql);
                //                $dbResult = $objOrder->select(['id' => $orderId], '*', 'createTime desc');//查询订单
                if ($dbResult === false) {
                    return ResultWrapper::fail($objOrder->error(), ErrorCode::$dberror);
                }
                $objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $k);
                $orderReceiveResult = $objDOrderReceive->select(['orderId' => $orderId], '*', 'createTime desc');//订单收货
                if ($orderReceiveResult === false) {
                    return ResultWrapper::fail($objDOrderReceive->error(), ErrorCode::$dberror);
                }

                $allOrderData = array_merge($dbResult, $allOrderData);
                $allOrderReceiveData = array_merge($orderReceiveResult, $allOrderReceiveData);
            }
        }
        //根据订单处理地址信息
        foreach ($allOrderReceiveData as $receiveKey => $receiveValue){
            // 渲染地址
            if (isset($receiveValue['provinceCode']) && isset($receiveValue['cityCode']) && isset($receiveValue['districtCode'])) {
                $areaName = $objMSysAreaChina->getNameByCode([
                    $receiveValue['provinceCode'],
                    $receiveValue['cityCode'],
                    $receiveValue['districtCode']
                ]);
                $allOrderReceiveData[$receiveKey]['area']['provinceName'] = isset($areaName[$receiveValue['provinceCode']]) ? $areaName[$receiveValue['provinceCode']] : '';
                $allOrderReceiveData[$receiveKey]['area']['cityName'] = isset($areaName[$receiveValue['cityCode']]) ? $areaName[$receiveValue['cityCode']] : '';
                $allOrderReceiveData[$receiveKey]['area']['districtName'] = isset($areaName[$receiveValue['districtCode']]) ? $areaName[$receiveValue['districtCode']] : '';
            }

            $allOrderReceiveData[$receiveValue['orderId']] = $allOrderReceiveData[$receiveKey];
            unset($allOrderReceiveData[$receiveKey]);
        }

        foreach ($allOrderData as $buildKey=>$buildValue){
            //物流信息展示
            if( !empty($buildValue['logisticsData']) ){
                $allOrderData[$buildKey]['logisticsData'] = json_decode($buildValue['logisticsData'],true);
            }
            //备注
            if( !empty($buildValue['extends']) ){
                $allOrderData[$buildKey]['extends'] = json_decode($buildValue['extends'],true);
            }
            //渲染编号
            if( !empty($buildValue['no']) ){
                $allOrderData[$buildKey]['no'] = StatusCode::$noPrefix[1].'-'.$buildValue['no'];
            }
            //配送方式
            if (isset($buildValue['deliveryType'])) {
                $allOrderData[$buildKey]['deliveryMsg'] = isset(StatusCode::$deliveryType[$buildValue['deliveryType']]) ? StatusCode::$deliveryType[$buildValue['deliveryType']] : '';
            }
            //根据订单id来组装地址
            $allOrderData[$buildKey]['orderReceiveData'] = $allOrderReceiveData[$buildValue['id']];
        }


        $return = [
            'data'  => $allOrderData,
            'total' => $dbTotalResult[0]['count'],
        ];

        return ResultWrapper::success($return);
    }

    /**
     * 订单拣货详情
     */
    public function getOrderPickingInfo($pickingId)
    {
        $objOrder = new DOrder();
        $objDOrderIndex = new DOrderIndex();
        $objDOrderReceive = new DOrderReceive();
        $objMSysAreaChina = new MSysAreaChina();
        $objDOrderGoods = new DOrderGoods();

        $indexDbResult = $objDOrderIndex->query('select * from qianniao_order_index_'.$this->onlineEnterpriseId.' where id = '.$pickingId);
        if ($indexDbResult === false) {
            return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
        }

        //订单表名
        $tableNum = ceil($indexDbResult[0]['userCenterId'] / $this->cutTable);

        //获取订单状态不是已完成，已关闭的
        $orderDate = $objOrder->query('select * from qianniao_order_'.$this->onlineEnterpriseId.'_'.$tableNum.' where id = '.$pickingId);
        if ($orderDate === false) {
            return ResultWrapper::fail($objOrder->error(), ErrorCode::$dberror);
        }
        $orderDate = array_shift($orderDate);
        //配送方式
        if (isset($orderDate['deliveryType'])) {
            $orderDate['deliveryMsg'] = isset(StatusCode::$deliveryType[$orderDate['deliveryType']]) ? StatusCode::$deliveryType[$orderDate['deliveryType']] : '';
        }
        //渲染编号
        if( !empty($orderDate['no']) ){
            $orderDate['no'] = StatusCode::$noPrefix[1].'-'.$orderDate['no'];
        }

        $objDOrderReceive->setTable('qianniao_order_receive_' . $this->onlineEnterpriseId . '_' . $tableNum);
        $orderReceiveData = $objDOrderReceive->get(['orderId' => $pickingId], '*', 'createTime desc');
        if ($orderReceiveData === false) {
            return ResultWrapper::fail($objDOrderReceive->error(), ErrorCode::$dberror);
        }

        //根据订单处理地址信息
        if (isset($orderReceiveData['provinceCode']) && isset($orderReceiveData['cityCode']) && isset($orderReceiveData['districtCode'])) {
            $areaName = $objMSysAreaChina->getNameByCode([
                $orderReceiveData['provinceCode'],
                $orderReceiveData['cityCode'],
                $orderReceiveData['districtCode']
            ]);
            $orderReceiveData['area']['provinceName'] = isset($areaName[$orderReceiveData['provinceCode']]) ? $areaName[$orderReceiveData['provinceCode']] : '';
            $orderReceiveData['area']['cityName'] = isset($areaName[$orderReceiveData['cityCode']]) ? $areaName[$orderReceiveData['cityCode']] : '';
            $orderReceiveData['area']['districtName'] = isset($areaName[$orderReceiveData['districtCode']]) ? $areaName[$orderReceiveData['districtCode']] : '';
        }
        $orderDate['orderReceive'] = $orderReceiveData;

        //获取订单商品信息
        $goodsDbResult = $objDOrderGoods->query('select * from qianniao_order_goods_'.$this->onlineEnterpriseId.'_'.$tableNum.' where orderId='.$pickingId .' and deleteStatus='.StatusCode::$standard);
        if ($goodsDbResult === false) {
            return ResultWrapper::fail($objDOrderGoods->error(), ErrorCode::$dberror);
        }
        $orderDate['goodsDate'] = $goodsDbResult;
        return ResultWrapper::success($orderDate);
    }

    /**
     * 待拣货明细
     */
    public function getAllPickingGoodsDetail($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $whereSql = '';
        if (isset($selectParams['no']) && !empty($selectParams['no'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' o.no like "%' . $selectParams['no'] .'%"';
        }
        if (isset($selectParams['goodsName']) && !empty($selectParams['goodsName'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' g.goodsName like "%'.$selectParams['goodsName'].'%"';
        }
        if (isset($selectParams['operatorId']) && !empty($selectParams['operatorId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' o.operatorId =' . $selectParams['operatorId'];
        }
        if ( (isset($selectParams['start']) && !empty($selectParams['start']))&&(isset($selectParams['end']) && !empty($selectParams['end'])) ) {
            $where = empty($whereSql) ? ' WHERE ' : '  AND ';
            $whereSql .= $where . ' o.createTime BETWEEN ' . $selectParams['start'] . ' AND '. $selectParams['end'];
        }
        $where = empty($whereSql) ? ' WHERE ' : '  AND ';
        $whereSql .= $where . ' o.orderStatus != ' . StatusCode::$orderStatus['finish'].' and o.orderStatus != '.StatusCode::$orderStatus['close'].' and o.pickingStatus = '.StatusCode::$orderPickStatus['notPicking'] ;

        $objMOrder = new MOrder($this->onlineUserId,$this->onlineEnterpriseId);
        $orderTable = $objMOrder->getOrderTable($this->onlineEnterpriseId,$this->onlineUserId);
        $tableNum = substr($orderTable,-1);
        $objDOrderIndex = new DOrderIndex();

        $orderSql = 'select o.`no`,o.customerId,o.customerName,o.operatorId,o.operatorName,o.createTime,g.* from '.$orderTable.' as o left join qianniao_order_goods_64_'.$tableNum.' as g on o.id=g.orderId '.$whereSql.' ORDER BY o.createTime desc LIMIT ' . $offset . ' , ' . $limit;

        $indexDbResult = $objDOrderIndex->query($orderSql);
        if ($indexDbResult === false) {
            return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
        }

        // 商品规格信息
        foreach ($indexDbResult as $key => $value){
            // 订单类型
            $indexDbResult[$key]['orderType'] = '销售订单';
            if( isset($value['specGroup']) ){
                if ($value['specGroup'] == 'null'){
                    $indexDbResult[$key]['specGroup'] = json_encode([],true);
                }
                if (!empty($value['specGroup']) && $value['specGroup'] != 'null' && $value['specGroup'] != '[]'){
                    $indexDbResult[$key]['specGroup'] = json_encode($value['specGroup'],true);
                }
            }
        }

        $totalSql = 'select COUNT(1) AS count from '.$orderTable.' as o left join qianniao_order_goods_64_'.$tableNum.' as g on o.id=g.orderId '.$whereSql;
        $dbTotalResult = $objDOrderIndex->query($totalSql);
        if ($dbTotalResult === false) {
            return ResultWrapper::fail($objDOrderIndex->error(), ErrorCode::$dberror);
        }

        if(empty($dbTotalResult)){
            return ResultWrapper::success([]);
        }

        $return = [
            'data'  => $indexDbResult,
            'total' => $dbTotalResult[0]['count'],
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 订单拣货表 新增订单时用
     */
    public function addOrderPick($params)
    {
        $orderPickingDate = [
            'orderId' => getArrayItem($params,'orderId',0),
            'sort' => getArrayItem($params,'sort',0),
            'outNum' => getArrayItem($params,'outNum',0),
            'notOutNum' => getArrayItem($params,'notOutNum',0),
            'orderNum' => getArrayItem($params,'orderNum',0),
            'notPickingNum' => getArrayItem($params,'notPickingNum',0),
            'pickingNum' => getArrayItem($params,'pickingNum',0),
            'outTime' => getArrayItem($params,'outTime',0),
            'mangeId' => getArrayItem($params,'mangeId',0),
            'mangeName' => getArrayItem($params,'mangeName',''),
        ];
        foreach ($orderPickingDate as $key => $value) {
            if (empty($value) && $value !== 0) {
                return ResultWrapper::fail('参数错误，拣货单创建失败', ErrorCode::$paramError);
            }
        }
        $orderPickingDate['createTime'] = time();
        $beginTransactionstatus = $this->objDOrderPicking->beginTransaction();
        $dbResult = $this->objDOrderPicking->insert($orderPickingDate);
        if ($dbResult === false) {
            $this->objDOrderPicking->rollBack();
            return ResultWrapper::fail($this->objDOrderPicking->error(), ErrorCode::$dberror);
        }
        if( $beginTransactionstatus ){
            $this->objDOrderPicking->commit();
        }
        return ResultWrapper::success($dbResult);
    }

}