<?php
/**
 * Created by PhpStorm.
 * User: Gss
 * Date: 2021/3/6 0006
 * Time: 15:01
 */

namespace JinDouYun\Model\Finance;

use JinDouYun\Controller\Market\VipCard;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Dao\Finance\DReceiptRequisition;
use JinDouYun\Dao\Finance\DReceiptRequisitionAccount;

class MReceiptRequisition
{
    private $objDReceiptRequisition;
    private $objDReceiptRequisitionAccount;
    private $enterpriseId;
    private $userCenterId;

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

        $this->objDReceiptRequisition = new DReceiptRequisition('finance');
        $this->objDReceiptRequisitionAccount = new DReceiptRequisitionAccount('finance');

        $this->objDReceiptRequisition->setTable('qianniao_receipt_requisition_' . $enterpriseId);
        $this->objDReceiptRequisitionAccount->setTable('qianniao_receipt_requisition_account_' . $enterpriseId);
    }

    /**
     * 新增收款单
     */
    public function addReceiptRequisition($params)
    {
        $receiptRequisitionAccountDate = $params['receiptRequisitionAccountDate'];
        unset($params['receiptRequisitionAccountDate']);
        $dbResult =  $this->objDReceiptRequisition->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'no', 'createTime desc');
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDReceiptRequisition->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            $params['no'] = createSerialNumberByDate('');
        }else{
            $params['no'] = createSerialNumberByDate($dbResult['no']);
        }
        //开启事务
        $beginTransactionStatus = $this->objDReceiptRequisition->beginTransaction();
        $receiptRequisitionId = $this->objDReceiptRequisition->insert($params);

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

        foreach ($receiptRequisitionAccountDate as $key => $value){
            $receiptRequisitionAccountDate[$key]['receiptRequisitionId'] = $receiptRequisitionId;
            $receiptRequisitionAccountDate[$key]['createTime'] = time();
        }

        $receiptRequisitionAccountId = $this->objDReceiptRequisitionAccount->insert($receiptRequisitionAccountDate,true);
        if ($receiptRequisitionAccountId === false) {
            $this->objDReceiptRequisition->rollBack();
            return ResultWrapper::fail($this->objDReceiptRequisitionAccount->error(), ErrorCode::$dberror);
        }
        if($beginTransactionStatus){
            $this->objDReceiptRequisition->commit();
        }
        return ResultWrapper::success($receiptRequisitionId);
    }

    /**
     * 获取指定的收款单
     */
    public function getReceiptRequisitionInfo($receiptRequisitionId)
    {
        $dbResult = $this->objDReceiptRequisition->get($receiptRequisitionId);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDReceiptRequisition->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::success([]);
        }
        //渲染前缀
        $dbResult['no'] = StatusCode::$noPrefix[17] . '-' . $dbResult['no'];


        $dbResultAccount = $this->objDReceiptRequisitionAccount->select(['receiptRequisitionId'=>$receiptRequisitionId,'deleteStatus'=>StatusCode::$standard]);
        if($dbResultAccount === false){
            return ResultWrapper::fail($this->objDReceiptRequisitionAccount->error(), ErrorCode::$dberror);
        }
        if(!empty($dbResultAccount)){
            $dbResult['receiptRequisitionAccountDate'] = $dbResultAccount;
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 编辑指定的收款单
     */
    public function editReceiptRequisition($params)
    {
        $updateReceiptRequisitionId = $params['id'];
        unset($params['id']);

        unset($params['createTime']);
        $receiptRequisitionAccountDate = $params['receiptRequisitionAccountDate'];
        unset($params['receiptRequisitionAccountDate']);
        //累计金额
        $params['totalCollectionAmount'] = 0;
        $params['totalPreferentialAmount'] = 0;
        $params['totalActualAmount'] = 0;
        foreach ($receiptRequisitionAccountDate as $account) {
            $account['preferentialAmount'] = !empty($account['preferentialAmount']) ? $account['preferentialAmount'] : 0;
            $params['totalCollectionAmount'] += $account['actualAmount'];
            $params['totalPreferentialAmount'] += $account['preferentialAmount'];
            $params['totalActualAmount'] += ($account['actualAmount'] - $account['preferentialAmount']);
        }
        //开启事务
        $beginTransactionStatus = $this->objDReceiptRequisition->beginTransaction();
        $receiptRequisitionId = $this->objDReceiptRequisition->update($params, $updateReceiptRequisitionId);
        if($receiptRequisitionId === false){
            $this->objDReceiptRequisition->rollBack();
            return ResultWrapper::fail($this->objDReceiptRequisition->error(), ErrorCode::$dberror);
        }
        foreach ($receiptRequisitionAccountDate as $key => $value){
            $id = getArrayItem($value, 'id', 0);
            if($id){
                $dbResult = $this->objDReceiptRequisitionAccount->update($value,['receiptRequisitionId'=>$id]);
                if ($dbResult === false) {
                    $this->objDReceiptRequisition->rollBack();
                    return ResultWrapper::fail($this->objDReceiptRequisitionAccount->error(), ErrorCode::$dberror);
                }
            }else{
                $value['receiptRequisitionId'] = $updateReceiptRequisitionId;
                $dbResult = $this->objDReceiptRequisitionAccount->insert($value);
                if ($dbResult === false) {
                    $this->objDReceiptRequisition->rollBack();
                    return ResultWrapper::fail($this->objDReceiptRequisitionAccount->error(), ErrorCode::$dberror);
                }
            }
        }

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

    /**
     * 删除指定的收款单
     */
    public function delReceiptRequisition($receiptRequisitionId)
    {
        if (empty($receiptRequisitionId)) {
            return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
        }
        $beginTransactionStatus = $this->objDReceiptRequisition->beginTransaction();
        $dbResult = $this->objDReceiptRequisition->update( ['deleteStatus'=>StatusCode::$delete], $receiptRequisitionId);
        if($dbResult === false){
            $this->objDReceiptRequisition->rollBack();
            return ResultWrapper::fail($this->objDReceiptRequisition->error(), ErrorCode::$dberror);
        }
        unset($dbResult);
        $dbResult = $this->objDReceiptRequisitionAccount->update( ['deleteStatus'=>StatusCode::$delete], ['receiptRequisitionId'=>$receiptRequisitionId]);
        if($dbResult === false){
            $this->objDReceiptRequisition->rollBack();
            return ResultWrapper::fail($this->objDReceiptRequisitionAccount->error(), ErrorCode::$dberror);
        }

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

    /**
     * 获取所有的收款单
     */
    public function getAllReceiptRequisition($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $selectParams['deleteStatus'] = StatusCode::$standard;

        $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['auditStatus']) && !empty($selectParams['auditStatus'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' auditStatus = ' . $selectParams['auditStatus'];
        }
        if (isset($selectParams['custormerId']) && !empty($selectParams['custormerId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' customerId = ' . $selectParams['custormerId'];
        }
        $where = empty($whereSql) ? ' WHERE ' : ' AND ';
        $whereSql .= $where . 'deleteStatus = ' . StatusCode::$standard;
        $sql = 'SELECT * FROM ' .$this->objDReceiptRequisition->get_Table().$whereSql . ' ORDER BY createTime DESC LIMIT ' . $offset . ' , ' . $limit;
        $dbResult = $this->objDReceiptRequisition->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDReceiptRequisition->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::success($returnData);
        }
        //渲染前缀
        foreach ($dbResult as $key => $value){
            $dbResult[$key]['no'] = StatusCode::$noPrefix[17] . '-' . $value['no'];
        }

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

        if ($dbTotalResult === false) {
            return ResultWrapper::fail($this->objDReceiptRequisition->error(), ErrorCode::$dberror);
        }
        if(empty($dbTotalResult)){
            return ResultWrapper::success([]);
        }
        $return = [
            'data'  => $dbResult,
            'total' => $dbTotalResult[0]['count']
        ];
        return ResultWrapper::success($return);
    }
    /**
     * 审核申请收款单
     */
    public function updateReceiptRequisitionStatus($params)
    {
        $ReceiptRequisitionData = $this->objDReceiptRequisition->get($params['id']);
        if ($ReceiptRequisitionData === false) {
            return ResultWrapper::fail($this->objDReceiptRequisition->error(), ErrorCode::$dberror);
        }
        if( empty($ReceiptRequisitionData) ){
            return ResultWrapper::fail('要审核的单据不存在', ErrorCode::$contentNotExists);
        }
        if( $ReceiptRequisitionData['auditStatus'] == StatusCode::$auditStatus['auditPass'] ){
            return ResultWrapper::fail('该单据已经审核过了', ErrorCode::$notAllowAccess);
        }
        //查询accountList信息
        $ReceiptRequisitionAccountList = $this->objDReceiptRequisitionAccount->select(['receiptRequisitionId'=>$params['id']]);
        //组装accountList
        $ReceiptRequisitionData['accountList']= [];
        foreach ($ReceiptRequisitionAccountList as $key => $value){
            $accountList = [
                'accountId' => $value['accountId'],
                'accountNumber'=>'',
                'accountName'=> $value['accountName'],
                'money'=> $value['collectionAmount'],
                'discountMoney'=>$value['preferentialAmount'],
                'finalMoney' => $value['actualAmount'],
                'payWay'=> '',
                'remark'=>$value['remark']
            ];
            array_push($ReceiptRequisitionData['accountList'],$accountList);
        }

        $beginTransactionStatus = $this->objDReceiptRequisition->beginTransaction();
//        判断是否自动生成收款单  autotype
        if($params['autoType'] == StatusCode::$delete){//只审核单据，不生成收款单
            $dbResult = $this->objDReceiptRequisition->update(['auditStatus' => StatusCode::$auditStatus['auditPass']], $params['id']);
        }

        if($params['autoType'] == StatusCode::$standard){//自动生成
            //请求add收款单，生成新的收款单
            //生成收款单
            $objMReceived = new MReceived($this->enterpriseId, $this->userCenterId);
            //创建收款单
            $received = [
                'currentAccountName' => $ReceiptRequisitionData['operatorName'],
                'financeType'        => '销售收款',
                'financeTypeId'      => 2,
                'shopId'             => $ReceiptRequisitionData['shopId'],
                'shopName'           => $ReceiptRequisitionData['shopName'],
                'receiptTime'        => time(),
                'operatorId'         => $this->userCenterId,
                'accountList'        => $ReceiptRequisitionData['accountList'],
                'customerId'         => $ReceiptRequisitionData['customerId'],
                'customerName'       => $ReceiptRequisitionData['customerName'],
                'sourceNo'           => $ReceiptRequisitionData['no'],
                'sourceNoMoney'      => $ReceiptRequisitionData['totalActualAmount'],
                'createTime'         => time(),
                'auditStatus'        => StatusCode::$auditStatus['auditing'],
                'updateTime'         => time(),
                'receiptOffsetData' => []
            ];
            $receivedResult = $objMReceived->addReceived($received, true);
            if (!$receivedResult->isSuccess()) {
                $this->objDReceiptRequisition->rollBack();
                return ResultWrapper::fail($receivedResult->getData(), $receivedResult->getErrorCode());
            }
            $dbResult = $this->objDReceiptRequisition->update(['auditStatus' => StatusCode::$auditStatus['auditPass']], $params['id']);
            //走更新接口
            $updateReceived = $objMReceived->updateReceivedStatus(['id'=>$receivedResult->getData(),'createTime'=>time()]);
            if (!$updateReceived->isSuccess()) {
                $this->objDReceiptRequisition->rollBack();
                return ResultWrapper::fail($updateReceived->getData(), $updateReceived->getErrorCode());
            }
        }
        if ($dbResult === false) {
            $this->objDReceiptRequisition->rollBack();
            return ResultWrapper::fail($this->objDReceiptRequisition->error(), ErrorCode::$dberror);
        }

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