<?php
/**
 * 付款单管理模块
 * Created by PhpStorm.
 * User: tpl
 * Date: 2019/10/30
 * Time: 13:54
 */

namespace JinDouYun\Controller\Finance;

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

use JinDouYun\Controller\BaseController;
use JinDouYun\Model\Finance\MPaid;
use JinDouYun\Cache\FinanceCache;

class Paid extends BaseController
{
    private $objMPaid;
    private $objFinanceCache;

    public function __construct($isCheckAcl = true, $isMustLogin = true)
    {
        parent::__construct($isCheckAcl, $isMustLogin);
        $this->objFinanceCache = new FinanceCache();
        $this->objMPaid = new MPaid($this->onlineEnterpriseId, $this->onlineUserId);
    }

    /**
     * 添加和编辑付款单管理公共字段处理方法
     *
     * @return array
     */
    public function commonFieldFilter()
    {

        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $paidData = [
            'supplierId'         => isset($params['supplierId']) ? $params['supplierId'] : '',
            'supplierName'       => isset($params['supplierName']) ? $params['supplierName'] : '',
            'currentAccountName' => isset($params['currentAccountName']) ? $params['currentAccountName'] : '',
            'financeType'        => isset($params['financeType']) ? $params['financeType'] : '',
            'financeTypeId'      => isset($params['financeTypeId']) ? $params['financeTypeId'] : '',
            'shopId'             => isset($params['shopId']) ? $params['shopId'] : '',
            'shopName'           => isset($params['shopName']) ? $params['shopName'] : '',
            'receiptTime'        => isset($params['receiptTime']) ? $params['receiptTime'] : '',
            'operatorId'         => $this->onlineUserId,
            'paidType'           => getArrayItem($params,'receivedType',4),// 付款类型(预收,应收)
            'accountList'        => isset($params['accountList']) ? $params['accountList'] : ''
        ];

        $paidData['tempSave'] = true;
        if (isset($params['tempSave']) && $params['tempSave'] == true) {
            $paidData['sourceNo'] = isset($params['sourceNo']) ? $params['sourceNo'] : '';
            $paidData['sourceNoMoney'] = isset($params['sourceNoMoney']) ? $params['sourceNoMoney'] : 0;
            return $paidData;
        }
        //非暂存,则验证
        unset($paidData['tempSave']);
        foreach ($paidData as $key => $value) {
            if (empty($value) && $value !== 0) {
                $this->sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }

        foreach ($paidData['accountList'] as $account) {
            if(!empty($account)) {
                foreach ($account as $k =>$v) {
                    if(in_array($k, ['accountId','money']) && empty($v)) {
                        $this->sendOutput('请输入账户'.$k, ErrorCode::$paramError);
                    }
                }
            }
        }

        $paidData['receiptOffsetData'] = getArrayItem($params, 'receiptOffsetData', []);
        // 没有 receiptOffsetData 数据说明是预收单据
        if(empty($paidData['receiptOffsetData'])){
            $paidData['paidType'] = StatusCode::$standard;
        }
        // receiptOffsetData 有数据  做判断
        if (!empty($receivedData['receiptOffsetData'])){
            foreach ($receivedData['receiptOffsetData'] as $val) {
                if(!empty($val)) {
                    foreach ($val as $k =>$v) {
                        if(in_array($k, ['payReceiptId','offsetMoney','paidId','payCreateTime']) && empty($v)) {
                            $this->sendOutput('请输入'.$k, ErrorCode::$paramError);
                        }
                    }
                }
            }
        }
        $paidData['sourceNo'] = isset($params['sourceNo']) ? $params['sourceNo'] : '';
        $paidData['sourceNoMoney'] = isset($params['sourceNoMoney']) ? $params['sourceNoMoney'] : 0;
        $paidData['auditStatus'] = StatusCode::$auditStatus['auditing'];
        $paidData['createTime'] = time();
        $paidData['updateTime'] = time();

        return $paidData;
    }

    /**
     * 添加付款单
     */
    public function addPaid()
    {
        $paidData = $this->commonFieldFilter();

        if (isset($paidData['tempSave'])) {
            $this->objFinanceCache->savePaidReceipt($this->onlineEnterpriseId, $this->onlineUserId, $paidData);
            parent::sendOutput('暂存成功');
        } else {
            $result = $this->objMPaid->addPaid($paidData);
            if ($result->isSuccess()) {
                //删除暂存数据
                $this->objFinanceCache->delPaidReceipt($this->onlineEnterpriseId, $this->onlineUserId);
                parent::sendOutput($result->getData());
            } else {
                parent::sendOutput($result->getData(), $result->getErrorCode());
            }
        }

    }


    /**
     * 修改付款单
     */
    public function editPaid()
    {
        $paidId  = $this->request->param('request_id');
        if(empty($paidId)){
            $this->sendOutput('参数错误', ErrorCode::$paramError);
        }
        $paidData = $this->commonFieldFilter();
        $paidData['id'] = $paidId;
        $result = $this->objMPaid->editPaid($paidData);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 获取暂存信息
     */
    public function getTempPaidData()
    {
        $result = $this->objFinanceCache->getPaidReceipt($this->onlineEnterpriseId, $this->onlineUserId);
        $this->sendOutput($result);
    }

    /**
     * 获取指定付款单信息
     */
    public function getPaidInfo()
    {
        $params = $this->request->getRawJson();
        if (empty($params['id']) || empty($params['createTime'])) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $result = $this->objMPaid->getPaidInfo($params);

        if ($result->isSuccess()) {
            $this->sendOutput($result->getData());
        } else {
            $this->sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 付款单审核
     */
    public function updatePaidStatus()
    {
        $params = $this->request->getRawJson();
        if (empty($params['id']) && empty($params['createTime'])) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $result = $this->objMPaid->updatePaidStatus($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }


    /**
     * 后台所有付款单列表
     */
    public function getAllPaid()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];
        $selectParams['no'] = getArrayItem($params,'no','');
        $selectParams['supplierId'] = getArrayItem($params, 'supplierId', '');
        $selectParams['start'] = getArrayItem($params, 'start', '');
        $selectParams['end'] = getArrayItem($params, 'end', '');
        $selectParams['auditStatus'] = getArrayItem($params, 'auditStatus', '');
        $selectParams['financeTypeId'] = getArrayItem($params, 'financeTypeId', '');
        $export = isset($params['export']) ? $params['export'] : 0;
        $result = $this->objMPaid->getAllPaid($selectParams,$export);

        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize'  => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 搜索
     */
    public function search()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $selectParams = [
            'keyword'     => isset($params['keyword']) ? $params['keyword'] : '',
            'customerId'  => isset($params['customerId']) ? $params['customerId'] : '',
            'start'       => isset($params['start']) ? $params['start'] : '',
            'end'         => isset($params['end']) ? $params['end'] : '',
            'auditStatus' => isset($params['auditStatus']) ? $params['auditStatus'] : '',
            'financeTypeId' => isset($params['financeTypeId']) ? $params['financeTypeId'] : '',
        ];

        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];
        $result = $this->objMPaid->search($selectParams);

        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize'  => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }


    /**
     * 付款查询核销记录
     */
    public function getAllPaidOffset()
    {
        $params = $this->request->getRawJson();
        if(empty($params['paidId'])){
            parent::sendOutput('paidId参数为空', ErrorCode::$paramError);
        }

        $result = $this->objMPaid->getAllPaidOffset($params);

        if ($result->isSuccess()) {
            parent::sendOutput($result->getData(), 0, ['pageTotal'=>count($result->getData())]);
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }


}