<?php
/**
 * Created by PhpStorm.
 * User: Gss
 * Date: 2021/3/27 0027
 * Time: 16:25
 */

namespace JinDouYun\Model\Customer;

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

use JinDouYun\Dao\Customer\DReflectDetail;
use JinDouYun\Dao\Customer\DCustomer;

use JinDouYun\Model\Customer\MMemberBalanceDetail;
use JinDouYun\Model\Customer\MCustomerDemand;

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

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

        $this->objDReflectDetail = new DReflectDetail('default');
        $this->objDReflectDetail->setTable('qianniao_reflect_detail_' . $enterpriseId);
        $this->objDCustomer = new DCustomer('default');
        $tableName = $this->objDCustomer->getTableName($this->objDCustomer->get_Table(), $this->enterpriseId, $this->cutTable);
        $this->objDCustomer->setTable($tableName);
    }

    /**
     * 申请提现
     */
    public function addReflectDetail($params)
    {
        //查询当前会员的余额
        $dbResult = $this->objDCustomer->get($params['customerId']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }
        $memberBalance = $dbResult['memberBalance'];
        if ( bcsub($memberBalance, $params['money'],2) < 0 ){
            return ResultWrapper::fail('客户余额不足!提现余额不能大于总余额', ErrorCode::$notAllowAccess);
        }
        unset($dbResult);
        $beginTransactionStatus = $this->objDReflectDetail->beginTransaction();
        //记录流水
        $memberBalanceDetailData = [
            'customerId' => $params['customerId'],
            'type'       => StatusCode::$delete,
            'userCenterId' => $this->userCenterId,
            'money'         =>$params['money'],
            'purpose'    => '提现',
            'orderIds'      =>'',
            'remark'     => '',
            'financeType' => '会员余额提现',
        ];
        $objMMemberBalanceDetail = new MMemberBalanceDetail($this->enterpriseId,$this->userCenterId);
        $memberBalanceDbResult = $objMMemberBalanceDetail->addMemberBalanceDetail($memberBalanceDetailData);
        if (!$memberBalanceDbResult->isSuccess()) {
            $this->objDReflectDetail->rollBack();
            return ResultWrapper::fail($memberBalanceDbResult->getData(), $memberBalanceDbResult->getErrorCode());
        }
        $DReflectDetailDate = $this->objDReflectDetail->insert($params);

        if ($DReflectDetailDate === false) {
            $this->objDReflectDetail->rollBack();
            return ResultWrapper::fail($this->objDReflectDetail->error(), ErrorCode::$dberror);
        }
        if($beginTransactionStatus){
            $this->objDReflectDetail->commit();
        }
        return ResultWrapper::success($DReflectDetailDate);
    }

    /**
     * 所有提现记录
     */
    public function getAllReflectDetail($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['reflectStatus']) && !empty($selectParams['reflectStatus'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' reflectStatus = ' . $selectParams['reflectStatus'];
        }
        if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' auditStatus = ' . $selectParams['auditStatus'];
        }
        if (isset($selectParams['reflectType']) && !empty($selectParams['reflectType'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' reflectType = "' . $selectParams['reflectType'].'"';
        }
        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->objDReflectDetail->get_Table().$whereSql . ' ORDER BY createTime DESC LIMIT ' . $offset . ' , ' . $limit;
        $dbResult = $this->objDReflectDetail->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDReflectDetail->error(), ErrorCode::$dberror);
        }
        $reflectInfo = [];
        foreach ($dbResult as $key =>$value){
            $reflectInfoDbResult = json_decode($dbResult[$key]['reflectInfo']);
            foreach ($reflectInfoDbResult as $k => $v){
                $reflectInfo[$k] = $v;
            }
            $dbResult[$key]['reflectInfo'] = $reflectInfo;
        }
        //映射客户名称
        $MCustomerDemand= new MCustomerDemand($this->enterpriseId,$this->userCenterId);
        $customerName = $MCustomerDemand->format($dbResult);
        $totalSql = 'SELECT COUNT(1) as count FROM ' .$this->objDReflectDetail->get_Table().$whereSql;
        $dbTotalResult = $this->objDReflectDetail->query($totalSql);

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

    //审核，打款公共方法
    public function updateReflectDetail($params)
    {
        $dbResult = $this->objDReflectDetail->get($params['id']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDReflectDetail->error(), ErrorCode::$dberror);
        }

        if(empty($dbResult)){
            return ResultWrapper::fail('要审核的单据不存在', ErrorCode::$contentNotExists);
        }
        if(empty($params['auditStatus']) && empty($params['reflectStatus'])){
            return ResultWrapper::fail('没有auditStatus|reflectStatus 不允许审核', ErrorCode::$notAllowAccess);
        }
        $beginTransactionStatus = $this->objDReflectDetail->beginTransaction();
        //判断是需要审核还是打款
        if(!empty($params['auditStatus'])){//审核
            if ($dbResult['auditStatus'] === StatusCode::$auditStatus['auditPass']) {
                return ResultWrapper::fail('单据已审核', ErrorCode::$actionIsDo);
            }
            $updateDReflectDetail = $this->objDReflectDetail->update(['auditStatus'=>StatusCode::$auditStatus['auditPass']],['id'=>$params['id']]);
            if ($updateDReflectDetail === false) {
                $this->objDReflectDetail->rollBack();
                return ResultWrapper::fail($this->objDReflectDetail->error(), ErrorCode::$dberror);
            }
        }
        if(!empty($params['reflectStatus'])){//打款
            if ($dbResult['reflectStatus'] === StatusCode::$standard) {
                return ResultWrapper::fail('单据已打款', ErrorCode::$actionIsDo);
            }
            $updateDReflectDetail = $this->objDReflectDetail->update(['reflectStatus'=>$params['reflectStatus']],['id'=>$params['id']]);
            if ($updateDReflectDetail === false) {
                $this->objDReflectDetail->rollBack();
                return ResultWrapper::fail($this->objDReflectDetail->error(), ErrorCode::$dberror);
            }
        }
        if($beginTransactionStatus){
            $this->objDReflectDetail->commit();
        }
        return ResultWrapper::success($updateDReflectDetail);
    }
}