<?php
/**
 * Created by PhpStorm.
 * User: Gss
 * Date: 2021/3/26 0026
 * Time: 10:52
 */

namespace JinDouYun\Model\Customer;


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

use Jindouyun\Cache\CustomerCache;

use JinDouYun\Model\Finance\MAccount;
use JinDouYun\Model\Finance\MAccountDetail;

use JinDouYun\Dao\Customer\DMemberBalanceDetail;
use JinDouYun\Dao\Customer\DCustomer;
use JinDouYun\Dao\Order\DOrderIndex;


class MMemberBalanceDetail
{
    private $enterpriseId;
    private $userCenterId;
    private $objDMemberBalanceDetail;
    private $objDCustomer;
    private $objDOrderIndex;
    private $cutTable = 1;//客户按照企业id分表

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

        $this->objDMemberBalanceDetail = new DMemberBalanceDetail('default');
        $this->objDCustomer = new DCustomer('default');
        $tableName = $this->objDCustomer->getTableName($this->objDCustomer->get_Table(), $this->enterpriseId, $this->cutTable);
        $this->objDCustomer->setTable($tableName);
        $this->objDMemberBalanceDetail->setTable('qianniao_member_balance_detail_' . $enterpriseId);
        $this->objDOrderIndex = new DOrderIndex();
        $this->objDOrderIndex->setTable('qianniao_order_index_' . $enterpriseId);
    }

    /**
     * 新增会员明细
     * $isbackstage后台页面充值
     */
    public function addMemberBalanceDetail($params,$isbackstage=false)
    {
        $financeType = getArrayItem($params, 'financeType', '');
        unset($params['financeType']);

        //查询当前会员的余额
        $customerData = $this->objDCustomer->get($params['customerId']);
        if ($customerData === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }

        if( empty($customerData) ){
            return ResultWrapper::fail('充值的客户不存在', ErrorCode::$contentNotExists);
        }

        $memberBalance = $customerData['memberBalance'];
        if ( bccomp($memberBalance, 0.00,2) < 0 ){
            return ResultWrapper::fail('客户余额不足!', ErrorCode::$notAllowAccess);
        }

        //计算变动后金额
        if($params['type'] == 5){
            $params['afterMoney'] = bcadd($memberBalance,$params['money'],2);
        }else{
            $params['afterMoney'] = bcsub($memberBalance,$params['money'],2);
            if ( bccomp($params['afterMoney'], 0.00, 2) < 0 ){
                return ResultWrapper::fail('余额不足，请切换其它支付方式', ErrorCode::$notAllowAccess);
            }
        }
        $params['beforeMoney'] = $memberBalance;
        $params['userCenterId'] = $customerData['userCenterId'];
        $beginTransactionStatus = $this->objDMemberBalanceDetail->beginTransaction();
        $memberBalanceDetailDate = $this->objDMemberBalanceDetail->insert($params);

        if ($memberBalanceDetailDate === false) {
            $this->objDMemberBalanceDetail->rollBack();
            return ResultWrapper::fail($this->objDMemberBalanceDetail->error(), ErrorCode::$dberror);
        }
        // 更新客户表会员余额
        $dbResult = $this->objDCustomer->update(['memberBalance'=>$params['afterMoney']],['id'=>$params['customerId']]);
        if ($dbResult === false) {
            $this->objDMemberBalanceDetail->rollBack();
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }

        $objCustomerCache = new CustomerCache();
        $objCustomerCache->delCustomerData($this->enterpriseId, $params['customerId']);
        $objCustomerCache->delCustomerUserData($this->enterpriseId, $customerData['userCenterId']);

        // 获取余额账户信息
        $objMAccount = new MAccount($this->enterpriseId, $this->userCenterId);
        $accountResult = $objMAccount->getDefaultAccount(StatusCode::$payType['balance']);
        if (!$accountResult->isSuccess()) {
            $this->objDMemberBalanceDetail->rollBack();
            return ResultWrapper::fail($accountResult->getData(), $accountResult->getErrorCode());
        }
        $accountInfo = $accountResult->getData();
        if (empty($accountInfo)){
            if($beginTransactionStatus){
                $this->objDMemberBalanceDetail->commit();
            }
            return ResultWrapper::success($memberBalanceDetailDate);
        }

        // 添加财务账户明细
        $accountDetail = [
            'accountId'          => $accountInfo['id'],
            'accountCode'        => $accountInfo['accountCode'],
            'accountName'        => $accountInfo['name'],
            'accountNumber'      => $accountInfo['accountNumber'],
            'sourceNo'           => $memberBalanceDetailDate,
            'sourceId'           => $memberBalanceDetailDate,
            'financeType'        => $financeType,
            'beginBalance'       => $accountInfo['money'],
            'shopId'             => 0,
            'shopName'           => '平台',
            'income'             => $params['type'] == StatusCode::$delete ? $params['money'] : 0, // 扣减 = 账户收入
            'expend'             => $params['type'] == StatusCode::$standard ? $params['money'] : 0,  // 充值 = 账户支出
            'endBalance'         => $accountInfo['money'] + (($params['type'] == StatusCode::$standard) ? -1* $params['money'] : $params['money']),
            'contactUnit'        => '客户名称:' . $customerData['name'],
            'supplierId'         => 0,
            'customerId'         => $customerData['id'],
            'operatorId'         => $this->userCenterId,
            'receiveOrPayPerson' => $customerData['name'],
            'remark'             => '会员余额充值',
            'createTime'         => time(),
            'updateTime'         => time(),
        ];
        $objMAccountDetail = new MAccountDetail($this->enterpriseId, $this->userCenterId);
        $result = $objMAccountDetail->addAccountDetail($accountDetail);
        if (!$result->isSuccess()) {
            $this->objDMemberBalanceDetail->rollBack();
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }

        $result = $objMAccount->updateMoney($accountInfo['id'], (($params['type'] == StatusCode::$standard) ? -1* $params['money'] : $params['money']));
        if (!$result->isSuccess()) {
            $this->objDMemberBalanceDetail->rollBack();
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }
        unset($result);

        //为了体现会员充值的钱，新增可选账户，充值到那个账户下
        if($isbackstage){
            $financeAccountResult = $objMAccount->getAccountInfo($params['accountId']);
            if (!$financeAccountResult->isSuccess()) {
                $this->objDMemberBalanceDetail->rollBack(); 
                return ResultWrapper::fail($financeAccountResult->getData(), $financeAccountResult->getErrorCode());
            }
            $financeAccountInfo = $financeAccountResult->getData();
            if (empty($financeAccountInfo)){
                if($beginTransactionStatus){
                    $this->objDMemberBalanceDetail->commit();
                }
                return ResultWrapper::success($memberBalanceDetailDate);
            }
            // 添加财务账户明细
            $financeAccountDetail = [
                'accountId'          => $financeAccountInfo['id'],
                'accountCode'        => $financeAccountInfo['accountCode'],
                'accountName'        => $financeAccountInfo['name'],
                'accountNumber'      => $financeAccountInfo['accountNumber'],
                'sourceNo'           => $memberBalanceDetailDate,
                'sourceId'           => $memberBalanceDetailDate,
                'financeType'        => $financeType,
                'beginBalance'       => $financeAccountInfo['money'],
                'shopId'             => 0,
                'shopName'           => '平台',
                'income'             => $params['type'] == StatusCode::$standard ? $params['money'] : 0, // 扣减 = 账户收入
                'expend'             => $params['type'] == StatusCode::$delete ? $params['money'] : 0,  // 充值 = 账户支出
                'endBalance'         => $financeAccountInfo['money'] + (($params['type'] == StatusCode::$delete) ? -1* $params['money'] : $params['money']),
                'contactUnit'        => '客户名称:' . $customerData['name'],
                'supplierId'         => 0,
                'customerId'         => $customerData['id'],
                'operatorId'         => $this->userCenterId,
                'receiveOrPayPerson' => $customerData['name'],
                'remark'             => '会员余额充值',
                'createTime'         => time(),
                'updateTime'         => time(),
            ];
            $result = $objMAccountDetail->addAccountDetail($financeAccountDetail);
            if (!$result->isSuccess()) {
                $this->objDMemberBalanceDetail->rollBack();
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }

            $result = $objMAccount->updateMoney($financeAccountInfo['id'], (($params['type'] == StatusCode::$delete) ? -1* $params['money'] : $params['money']));
            if (!$result->isSuccess()) {
                $this->objDMemberBalanceDetail->rollBack();
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }
        }

        if($beginTransactionStatus){
            $this->objDMemberBalanceDetail->commit();
        }

        return ResultWrapper::success($memberBalanceDetailDate);
    }

    /**
     * 获取所有的明细
     */
    public function getAllMemberBalanceDetail($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $whereSql = '';
        if (isset($selectParams['userCenterId']) && !empty($selectParams['userCenterId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' userCenterId = ' . $selectParams['userCenterId'];
        }
        if (isset($selectParams['customerId']) && !empty($selectParams['customerId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' customerId = ' . $selectParams['customerId'];
        }
        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'];
        }
        $returnData = [
            'data'  => [],
            'total' => 0,
        ];
        $sql = 'SELECT * FROM ' .$this->objDMemberBalanceDetail->get_Table().$whereSql . ' ORDER BY createTime DESC LIMIT ' . $offset . ' , ' . $limit;
        $dbResult = $this->objDMemberBalanceDetail->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDMemberBalanceDetail->error(), ErrorCode::$dberror);
        }
        foreach ($dbResult as $key => $value){
            if( !empty($value['orderIds']) ){
                $orderIds = explode(',',$value['orderIds']);
                $orderResult = $this->objDOrderIndex->select(['id'=>$orderIds]);
                if ($orderResult === false) {
                    return ResultWrapper::fail($this->objDOrderIndex->error(), ErrorCode::$dberror);
                }
                if(!empty($orderResult)){
                    foreach ($orderResult as $k => $v){
                        $orderResult[$k]['no'] = StatusCode::$noPrefix[1].'-'.$v['no'];
                    }
                    $dbResult[$key]['orderIdDate'] = $orderResult;
                }

            }
        }

        $totalSql = 'SELECT COUNT(1) as count FROM ' .$this->objDMemberBalanceDetail->get_Table().$whereSql;
        $dbTotalResult = $this->objDMemberBalanceDetail->query($totalSql);

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


    public function create($customerId, $userCenterId, $type, $before, $money, $after, $purpose = '', $remark = '')
    {
        $data = [
            'customerId' =>$customerId,
            'userCenterId' => $userCenterId,
            'type' => $type,
            'beforeMoney' => $before,
            'money' => $money,
            'afterMoney' => $after,
            'remark' => $remark,
            'purpose' => $purpose,
        ];
        $this->objDCustomer->update(['memberBalance' => $after], ['id' => $customerId]);
        $this->objDMemberBalanceDetail->insert($data);
    }

}
