<?php
/**
 * 资金转账管理模块
 * Created by PhpStorm.
 * User: wxj
 * Date: 2019/10/30
 * Time: 14:02
 */

namespace JinDouYun\Model\Finance;

use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;
use JinDouYun\Model\MBaseModel;
use JinDouYun\Dao\Finance\DAccountTransfer;
use JinDouYun\Model\Finance\MAccount;
use JinDouYun\Model\Finance\MAccountDetail;

class MAccountTransfer extends MBaseModel {

    private $objDAccountTransfer;
    private $objMAccount;
    private $objMAccountDetail;
    private $enterpriseId;
    private $userCenterId;

    public function __construct($enterpriseId, $userCenterId)
    {
        $this->userCenterId = $userCenterId;
        $this->enterpriseId = $enterpriseId;
        parent::__construct($enterpriseId, $userCenterId);
        $this->objDAccountTransfer = new DAccountTransfer('finance');
        $this->objDAccountTransfer->setTable('qianniao_account_transfer_' . $enterpriseId);
        $this->objMAccount = new MAccount($enterpriseId, $userCenterId);
        $this->objMAccountDetail = new MAccountDetail($enterpriseId, $userCenterId);
    }

    /**
     * 添加资金转账
     *
     * @param array $params 资金转账数据
     *
     * @return ResultWrapper
     */
    public function addAccountTransfer($params)
    {
        //判断是否可转出
        $records = json_decode($params['records'],true);
        foreach ($records as $record) {
            $result = self::checkTransferLegal($record['outAccountId'], $record['money']);
            if($result->isSuccess() == false) {
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
                break;
            }
        }

        $params['no'] = createOrderSn(StatusCode::$source['manage'], StatusCode::$orderType['accountTransfer'], $this->userCenterId);
        $AccountTransferId = $this->objDAccountTransfer->insert($params);

        if($AccountTransferId === false){
            return ResultWrapper::fail($this->objDAccountTransfer->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($AccountTransferId);
        }
    }

    /**
     * 获取指定资金转账信息
     * @param $AccountTransferIds
     * @return ResultWrapper
     */
    public function getAccountTransferInfo($AccountTransferIds)
    {
        $dbResult = $this->objDAccountTransfer->get($AccountTransferIds);

        if($dbResult === false){
            return ResultWrapper::fail($this->objDAccountTransfer->error(), ErrorCode::$dberror);
        }else{
            $dbResult = self::format([$dbResult]);
            return ResultWrapper::success(array_shift($dbResult));
        }
    }

    public function format($data) {
        foreach ($data as $key => $value) {
            $data[$key]['records'] = json_decode($data[$key]['records'], true);
        }
        return $data;
    }

    /**
     * 编辑资金转账
     *
     * @param int|array $params 修改资金转账的数据
     *
     * @return ResultWrapper
     */
    public function editAccountTransfer($params)
    {
        if( empty($params['id']) ){
            return ResultWrapper::fail('没有指定要修改的AccountTransferid', ErrorCode::$paramError);
        }

        //判断是否可转出
        $records = json_decode($params['records'],true);
        foreach ($records as $record) {
            $result = self::checkTransferLegal($record['outAccountId'], $record['money']);
            if($result->isSuccess() == false) {
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
                break;
            }
        }

        $updateAccountTransferId = $params['id'];
        unset($params['id']);

        $dbResult = $this->objDAccountTransfer->update($params, $updateAccountTransferId);

        if($dbResult === false){
            return ResultWrapper::fail($this->objDAccountTransfer->error(), ErrorCode::$dberror);
        }else{
            return ResultWrapper::success($dbResult);
        }
    }

    //判断转出账户金额是否大于转出金额
    public function checkTransferLegal($accountId, $transferMoney) {
        if(!$transferMoney) {
            return ResultWrapper::fail('转出金额必须大于0', ErrorCode::$paramError);
        }
        $accountResult = $this->objMAccount->getAccountInfo($accountId);
        if($accountResult->isSuccess() == false) {
            return ResultWrapper::fail($accountResult->getData(), $accountResult->getErrorCode());
        }

        $account = $accountResult->getData();
        if($account['money'] < $transferMoney) {
            return ResultWrapper::fail('账户金额不足', ErrorCode::$paramError);
        }
        return ResultWrapper::success('可正常转出');
    }

    /**
     * 资金转账审核
     * @param array $id
     * @return ResultWrapper
     */
    public function updateAccountTransferStatus($id)
    {
        $transferResult = $this->objDAccountTransfer->get($id);
        if(isset($transferResult['auditStatus']) && $transferResult['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
            return ResultWrapper::fail('单据已通过审核，请勿重复操作', ErrorCode::$actionIsDo);
        }

        $this->objDAccountTransfer->beginTransaction();
        $dbResult = $this->objDAccountTransfer->update( ['auditStatus'=>StatusCode::$auditStatus['auditPass']], $id );
        if($dbResult === false){
            $this->objDAccountTransfer->rollBack();
            return ResultWrapper::fail($this->objDAccountTransfer->error(), ErrorCode::$dberror);
        }

        //循环records，给转出账户减去一定数值，给转入的加数值  添加账户明细
        $records = json_decode($transferResult['records'], true);
        foreach ($records as $record) {
            $result = self::dealAccountDetail($record['inAccountId'], $transferResult, $record);
            if($result->isSuccess() == false) {
                $this->objDAccountTransfer->rollBack();
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }

            $result = $this->objMAccount->updateMoney($record['inAccountId'], $record['money']);
            if($result->isSuccess() == false) {
                $this->objDAccountTransfer->rollBack();
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }

            $result = self::dealAccountDetail($record['outAccountId'], $transferResult, $record, false);
            if($result->isSuccess() == false) {
                $this->objDAccountTransfer->rollBack();
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }
            $result = $this->objMAccount->updateMoney($record['outAccountId'], '-'.$record['money']);
            if($result->isSuccess() == false) {
                $this->objDAccountTransfer->rollBack();
                return ResultWrapper::fail($result->getData(), $result->getErrorCode());
            }
        }

        $this->objDAccountTransfer->commit();
        return ResultWrapper::success($dbResult);

    }

    /**
     * 账户明细
     * @param $accountId
     * @param $transferData
     * @param $record
     * @param $in
     * @return ResultWrapper
     * @throws \Exception
     */
    public function dealAccountDetail($accountId, $transferData, $record, $in =true) {
        //获取账户信息
        $accountResult = $this->objMAccount->getAccountInfo($accountId);
        if($accountResult->isSuccess() == false) {
            return ResultWrapper::fail($accountResult->getData(), $accountResult->getErrorCode());
        }
        $accountInfo = $accountResult->getData();

        //账户明细
        $accountDetail = [
            'accountId'=> $accountInfo['id'],
            'accountCode'=> $accountInfo['accountCode'],
            'accountName'=> $accountInfo['name'],
            'accountNumber'=> $accountInfo['accountNumber'],
            'sourceNo' =>$transferData['no'],
            'sourceId' => $transferData['id'],
            'financeType'=>'资金转账',
            'beginBalance'=>$accountInfo['money'],
            'shopId'=>$transferData['shopId'],
            'shopName'=>$transferData['shopName'],
            'income'=> $in ? $record['money'] : 0,
            'expend'=> $in ? 0 : $record['money'],
            'endBalance'=> $in ? ($accountInfo['money'] + $record['money']) : ($accountInfo['money'] - $record['money']),
            'contactUnit'=>'资金转账',
            'supplierId'=>0,
            'customerId'=>0,
            'operatorId'=>$this->userCenterId,
            'receiveOrPayPerson'=>'',
            'remark'=>$in ? "资金转账：转入".$record['money']."元" : "资金转账：转出".$record['money']."元",
            'createTime'=>time(),
            'updateTime'=>time(),
        ];
        $result = $this->objMAccountDetail->addAccountDetail($accountDetail);
        if ($result->isSuccess() === false) {
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }
        return ResultWrapper::success($result);
    }
    /**
     * 获取所有资金转账数据
     *
     * @param array $selectParams 过滤条件
     *
     * @return ResultWrapper
     */
    public function getAllAccountTransfer($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $where = '';
        if(!empty($selectParams['no'])) {
            $where .= 'no='. $selectParams['no'];
        }

        if(!empty($selectParams['start'])) {
            if(!empty($where)) {
                $where .= ' AND ';
            }
            $where .= 'createTime >= '. $selectParams['start'];
        }

        if(!empty($selectParams['end'])) {
            if(!empty($where)) {
                $where .= ' AND ';
            }
            $where .= 'createTime <= '. $selectParams['end'];
        }

        if(!empty($selectParams['outAccountId'])) {
            if(!empty($where)) {
                $where .= ' AND ';
            }
            $where .= "JSON_CONTAINS(records->'$[*].outAccountId', '".$selectParams['outAccountId']."', '$') = 1";
        }

        if(!empty($selectParams['inAccountId'])) {
            if(!empty($where)) {
                $where .= ' AND ';
            }
            $where .= "JSON_CONTAINS(records->'$[*].inAccountId', '".$selectParams['inAccountId']."', '$') = 1";
        }

        $dbResult = $this->objDAccountTransfer->select($where, '*', 'createTime desc', $limit, $offset);

        if($dbResult === false){
            return ResultWrapper::fail($this->objDAccountTransfer->error(), ErrorCode::$dberror);
        }

        $total = $this->objDAccountTransfer->count($selectParams);

        $return = [
            'data'  => self::format($dbResult),
            'total' => ($total)?intval($total):0,
        ];

        return ResultWrapper::success($return);

    }
    
}