<?php
/**
 * Created by PhpStorm.
 * User: Gss
 * Date: 2021/4/6 0006
 * Time: 14:19
 */

namespace JinDouYun\Model\Merchant;


use JinDouYun\Dao\Merchant\DMerchantSettlement;
use JinDouYun\Dao\Merchant\DMerchantApply;
use JinDouYun\Dao\Merchant\DMerchantDetail;


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

class MMerchantSettlement
{
    private $objDMerchantSettlement;
    private $objDMerchantApply;
    private $objDMerchantDetail;
    private $enterpriseId;
    private $userCenterId;

    public function __construct($enterpriseId, $userCenterId)
    {
        $this->userCenterId = $userCenterId;
        $this->enterpriseId = $enterpriseId;

        $this->objDMerchantSettlement = new DMerchantSettlement('finance');
        $this->objDMerchantApply = new DMerchantApply();
        $this->objDMerchantDetail = new DMerchantDetail();

        $this->objDMerchantSettlement->setTable('qianniao_merchant_settlement_' . $enterpriseId);
        $this->objDMerchantDetail->setTable('qianniao_merchant_detail_' . $enterpriseId);
    }

    /*
     * 新增结算记录
     * */
    public function addMerchantSettlement($params)
    {
        $insert = [];
        foreach ($params as $key =>$value){
            $insert[] = [
                "orderId"=>$value['orderId'],
                "orderNo"=>$value['orderNo'],
                "goodsId"=>$value['goodsId'],
                "goodsName"=>$value['goodsName'],
                "goodsNum"=>$value['goodsNum'],
                "goodsPrice"=>$value['goodsPrice'],
                "goodsMoney"=>$value['goodsMoney'],
                "merchantId"=>$value['merchantId'],
                "merchantName"=>isset($value['merchantName']) ? $value['merchantName'] : '',
                "outStockTime"=>$value['outStockTime']
            ];
        }
        $beginTransactionStatus = $this->objDMerchantSettlement->beginTransaction();
        $merchantSettlementId = $this->objDMerchantSettlement->insert($insert,true);
        if ($merchantSettlementId === false) {
            return ResultWrapper::fail($this->objDMerchantSettlement->error(), ErrorCode::$dberror);
        }

        if($beginTransactionStatus){
            $this->objDMerchantSettlement->commit();
        }
        return ResultWrapper::success($merchantSettlementId);
    }

    /*
     * 结算记录状态
     * */
    public function updateMerchantSettlement($params)
    {
        //根据订单id查询当前结算记录
        $merchantSettlementData = $this->objDMerchantSettlement->select( ['orderId'=>$params['orderId'],'settlementStatus'=>StatusCode::$delete] );
        if ($merchantSettlementData === false) {
            return ResultWrapper::fail($this->objDMerchantSettlement->error(), ErrorCode::$dberror);
        }
        if( empty($merchantSettlementData) ){
            return ResultWrapper::success(false);
        }
        $beginTransactionStatus = $this->objDMerchantSettlement->beginTransaction();
        $merchantData = [];
        $insertDetails = [];
        //循环统计商户的金额
        foreach ($merchantSettlementData as $key => $value){
            if( isset($merchantData[$value['merchantId']][$value['orderId']]) ){
                $merchantData[$value['merchantId']][$value['orderId']]['goodsMoney'] =
                    bcadd($value['goodsMoney'],$merchantData[$value['merchantId']][$value['orderId']]['goodsMoney'],2);
            }else{
                $merchantData[$value['merchantId']][$value['orderId']] = [
                    'orderId' => $value['orderId'],
                    'orderNo' => $value['orderNo'],
                    'merchantId' => $value['merchantId'],
                    'merchantName' => $value['merchantName'],
                    'goodsMoney' => $value['goodsMoney']
                ];
            }
        }
        foreach ($merchantData as $merchantId => $orderData){
            //查询商户余额
            $merchant = $this->objDMerchantApply->get(['id' => $merchantId]);
            if($merchant === false){
                $this->objDMerchantSettlement->rollBack();
                return ResultWrapper::fail($this->objDMerchantApply->error(), ErrorCode::$dberror);
            }
            $afterMoney = empty($merchant['balance'])?0:$merchant['balance'];
            foreach($orderData as $orderId => $value){
                $afterMoney = bcadd($afterMoney, $value['goodsMoney'], 2);
                //组装流水数据
                $insertDetails[] = [
                    'merchantId' => $value['merchantId'],
                    'merchantName' => $value['merchantName'],
                    'originId' => $value['orderId'],
                    'originNo' => $value['orderNo'],
                    'money' => $value['goodsMoney'],
                    'afterMoney' => $afterMoney,
                    'type' => StatusCode::$standard,
                    'source' => 2,
                    'remark' => '订单结算',
                    'createTime' => time(),
                    'updateTime' => time()
                ];
            }
            $detailsDbResult = $this->objDMerchantDetail->insert($insertDetails,true);
            if($detailsDbResult === false){
                $this->objDMerchantSettlement->rollBack();
                return ResultWrapper::fail($this->objDMerchantDetail->error(), ErrorCode::$dberror);
            }
            $dbResult = $this->objDMerchantApply->update(['balance' => $afterMoney, 'updateTime' => time()], ['id' => $merchantId]);
            if($dbResult === false){
                $this->objDMerchantSettlement->rollBack();
                return ResultWrapper::fail($this->objDMerchantApply->error(), ErrorCode::$dberror);
            }
        }
        //更新结算状态
        $updateStatus = $this->objDMerchantSettlement->update(['settlementStatus'=>StatusCode::$standard, 'updateTime' => time(), 'finishTime'=>time()],['orderId'=>$params['orderId'],'settlementStatus'=>StatusCode::$delete]);
        if ($updateStatus === false) {
            $this->objDMerchantSettlement->rollBack();
            return ResultWrapper::fail($this->objDMerchantSettlement->error(), ErrorCode::$dberror);
        }
        if($beginTransactionStatus){
            $this->objDMerchantSettlement->commit();
        }
        return ResultWrapper::success($updateStatus);
    }

    /*
     * 获取所有结算记录
     * */
    public function getAllMerchantSettlement($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $returnData = [
            'data'  => [],
            'total' => 0,
        ];
        $whereSql = '';
//        if (isset($selectParams['operatorName']) && !empty($selectParams['operatorName'])) {
//            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
//            $whereSql .= $where . ' operatorName like "%' . $selectParams['operatorName'] . '%"';
//        }
        if (isset($selectParams['merchantId']) && !empty($selectParams['merchantId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' merchantId = ' . $selectParams['merchantId'];
        }
        if (isset($selectParams['goodsName']) && !empty($selectParams['goodsName'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' goodsName LIKE "%' . $selectParams['goodsName'] .'%"';
        }
        if (isset($selectParams['settlementStatus']) && !empty($selectParams['settlementStatus'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' settlementStatus = ' . $selectParams['settlementStatus'];
        }
        if ( (isset($selectParams['start']) && !empty($selectParams['start']))&&(isset($selectParams['end']) && !empty($selectParams['end'])) ) {
            $where = empty($whereSql) ? ' WHERE ' : '  AND ';
            $whereSql .= $where . ' createTime BETWEEN ' . $selectParams['start'] . ' AND '. $selectParams['end'];
        }

        $sql = 'SELECT * FROM ' .$this->objDMerchantSettlement->get_Table().$whereSql . ' ORDER BY createTime DESC LIMIT ' . $offset . ' , ' . $limit;
        $dbResult = $this->objDMerchantSettlement->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDMerchantSettlement->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::success($returnData);
        }
        $totalSql = 'SELECT COUNT(1) as count FROM ' .$this->objDMerchantSettlement->get_Table().$whereSql;
        $dbTotalResult = $this->objDMerchantSettlement->query($totalSql);

        if ($dbTotalResult === false) {
            return ResultWrapper::fail($this->objDMerchantSettlement->error(), ErrorCode::$dberror);
        }
        if(empty($dbTotalResult)){
            return ResultWrapper::success([]);
        }
        $return = [
            'data'  => $dbResult,
            'total' => $dbTotalResult[0]['count']
        ];
        return ResultWrapper::success($return);
    }
}