<?php
/**
 * Created by PhpStorm.
 * User: kang
 * Date: 2021/5/26
 * Time: 9:55
 */
namespace JinDouYun\Model\Delivery;

use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Dao\Delivery\DDistributionCentre;
use JinDouYun\Dao\Delivery\DDeliveryTask;
use JinDouYun\Dao\Delivery\DDeliveryTaskIndex;
use JinDouYun\Dao\Delivery\DDeliveryDetails;

use JinDouYun\Model\MBaseModel;

class MDistributionCentre extends MBaseModel
{
    private $objDDistributionCentre;
    private $objDDeliveryTask;
    private $objDDeliveryTaskIndex;
    private $objDDeliveryDetails;
    private $userCenterId;
    private $enterpriseId;
    
    public function __construct($enterpriseId, $userCenterId)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        
        $this->objDDistributionCentre = new DDistributionCentre('stock'); // 待司机配送主单据表
        $this->objDDistributionCentre->setTable('qinniao_delivery_centre_' . $enterpriseId . '_' . date('Y'));
    
        $this->objDDeliveryTaskIndex = new DDeliveryTaskIndex('stock'); // 配送任务索引表
        $this->objDDeliveryTaskIndex->setTable('qianniao_delivery_task_index_1' . $enterpriseId);
        
        $this->objDDeliveryTask = new DDeliveryTask('stock'); // 配送任务表
        $this->objDDeliveryTask->setTable('qianniao_delivery_task_' . $enterpriseId . '_' . date('Y'));
        
        $this->objDDeliveryDetails = new DDeliveryDetails('stock'); // 配送任务明细
        $this->objDDeliveryDetails->setTable('qianniao_delivery_details_' . $enterpriseId . '_' . date('Y'));
    }
    
    /**
     * 添加待司机配送
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addDistribution($params)
    {
        $distributionId = $this->objDDistributionCentre->insert($params);
        if($distributionId === false){
            return ResultWrapper::fail($this->objDDistributionCentre->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($distributionId);
    }

    
    /**
     * 删除待司机配送
     * @param array $params  要删除待司机配送单
     * @return ResultWrapper
     */
    public function delDistribution($distributionId)
    {
        $updateData = [
            'updateTime'   => time(),
            'deleteStatus' => StatusCode::$delete,
        ];
        $dbResult = $this->objDDistributionCentre->update($updateData, $distributionId);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDDistributionCentre->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($dbResult);
        }
    }
    
    /**
     * 获取所有的待司机配送
     */
    public function getAllDistribution($selectParams)
    {
        
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        
        $returnData = [
            'data'  => [],
            'total' => 0,
        ];
      
        $dbResult = $this->objDDistributionCentre->select($selectParams,'*','',$limit,$offset);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDDistributionCentre->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::success($returnData);
        }
        $dbTotalResult = $this->objDDistributionCentre->count($selectParams);
        if ($dbTotalResult === false) {
            return ResultWrapper::fail($this->objDDistributionCentre->error(), ErrorCode::$dberror);
        }
        $return = [
            'data'  => $dbResult,
            'total' => $dbTotalResult
        ];
        return ResultWrapper::success($return);
    }
    
    
    /**
     * 添加配送任务
     * @param $params
     * @return ResultWrapper
     */
    public function addTask($params)
    {
    
        $deliveryTaskData = $params['deliveryTaskData'];
        unset($params['deliveryTaskData']);
    
        // 生成编号
        $dbResult =  $this->objDDeliveryTaskIndex->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'TaskNo', 'createTime desc');
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDDeliveryTaskIndex->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            $params['TaskNo'] = createSerialNumberByDate('');
        }else{
            $params['TaskNo'] = createSerialNumberByDate($dbResult['TaskNo']);
        }
        
        //开启事务
        $beginTransactionStatus = $this->objDDeliveryTaskIndex->beginTransaction();
        // 组装index数据
        $indexDate = [
            'deliveryStatus'  => getArrayItem($params,'deliveryStatus',1), //配送状态（1：待配送 2：已配送3：配送中）
            'TaskNo'          => getArrayItem($params,'TaskNo',''), //配送任务单号
            'driverId'        => getArrayItem($params,'driverId',''), //配送司机id
            'carId'           => getArrayItem($params,'carId',''), //配送车辆id
            'deliveryBoyId'   => getArrayItem($params,'deliveryBoyId',''), //送货员id
            'deleteStatus'    => StatusCode::$standard,
            'enterpriseId'    => $this->enterpriseId,
            'createTime'      => time(),//创建时间
            'deliveryStartTime'=> time(), // 开始配送时间
        ];
        //索引表插入数据
        $deliveryTaskIndexId = $this->objDDeliveryTaskIndex->insert($indexDate);
        if ($deliveryTaskIndexId === false) {
            $this->objDDeliveryTaskIndex->rollBack();
            return ResultWrapper::fail($this->objDDeliveryTaskIndex->error(), ErrorCode::$dberror);
        }
        $params['id'] = $deliveryTaskIndexId;
        // 主单据插入数据
        $deliveryTaskId = $this->objDDeliveryTask->insert($params);
        if ($deliveryTaskId === false) {
            $this->objDDeliveryTaskIndex->rollBack();
            return ResultWrapper::fail($this->objDDeliveryTask->error(), ErrorCode::$dberror);
        }
        
        foreach ($deliveryTaskData as $key => $value){
            // 主单据表的id赋值给”linkeId“
            $deliveryTaskData[$key]['linkeId'] = $deliveryTaskId;
            // 配送任务单号
            $deliveryTaskData[$key]['TaskNo'] = getArrayItem($params,'TaskNo','');
        }
        $deliveryDetailsId = $this->objDDeliveryDetails->insert($deliveryTaskData,true);
        if ($deliveryDetailsId === false) {
            $this->objDDeliveryTaskIndex->rollBack();
            return ResultWrapper::fail($this->objDDeliveryDetails->error(), ErrorCode::$dberror);
        }
        if($beginTransactionStatus){
            $this->objDDeliveryTaskIndex->commit();
        }
        return ResultWrapper::success($deliveryTaskId);
        
    }
    
    /**
     * 配送任务完成配送
     * @param array $params  配送任务
     * @return ResultWrapper
     */
    public function taskComplete($taskCompleteId)
    {
        $updateData = [
            'deliveryStatus' => 2, // (1:待配送，2已配送)
            'deliveryEndTime'=> time(), //配送完成时间
        ];
        $dbResult = $this->objDDeliveryTask->update($updateData, $taskCompleteId);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDDeliveryTask->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($dbResult);
        }
    }
}