<?php

/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\modules\statement\controllers;

use Yii;
use yii\data\ActiveDataProvider;
use common\components\Tool;
use common\models\Common;
use home\modules\statement\models\StatementAccount;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\models\PermissionScope;
use home\models\Attachment;
use yii\helpers\Url;
use home\modules\customer\models\Customer;
use home\modules\statement\models\StatementLink;
use home\modules\statement\models\StatementLinkContract;
use yii\web\ForbiddenHttpException;
use qcbase\models\Auth;

/**
 * 对账单管理
 * 
 * @author HuLimin http://blog.u-bo.com
 * @since 0.1
 */
class StatementAccountController extends \home\controllers\Controller
{

    public function actions()
    {
        $actions = parent::actions();
        $actions['create']['layout'] = '//modal';
        $actions['view']['layout'] = '//modal';
        $actions['update']['layout'] = '//modal';
        unset($actions['index']);
        return $actions;
    }

    /**
     * 进账单管理列表页
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        $total = [];
        $query = StatementAccount::find()
                ->orderBy(['payment_time' => SORT_DESC]);
        $beginTime = trim($request->get('begin_time'));
        $endTime = trim($request->get('end_time'));
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');

        if(!empty($keywords) && !empty($field)){
            $query->andwhere(['like', $field, $keywords]);
        }
        if(!empty($beginTime)){
            $beginTime = strtotime($beginTime);
            $query->andWhere('payment_time >= :beginTime', [':beginTime' => $beginTime]);
        }
        if(!empty($endTime)){
            $endTime = strtotime($endTime);
            $query->andWhere('payment_time <= :endTime', [':endTime' => $endTime]);
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);
        $creditqQuery = clone $query;
        $creditqDebit = clone $query;
        $total = [
            'total_credit' => $creditqQuery->sum('account_credit'),
            'total_debit' => $creditqDebit->sum('account_debit')
        ];
        return $this->render('index', [
                    'model' => new StatementAccount(),
                    'models' => $provider->getModels(),
                    'pages' => $provider->pagination,
                    'get' => $request->get(),
                    'total' => $total
        ]);
    }

    /**
     * 进账单关联客户
     */
    public function actionStatementLink()
    {
        $linkInfo = [];
        $linkCustomerInfo = [];
        $request = Yii::$app->request;
        $statement_id = (int) $request->get('id');
        $type = trim($request->get('type'));

        empty($type) && $type = 'link';
        $model = StatementAccount::find()
                ->where(['statement_id' => $statement_id])
                ->with(['user', 'statementLink'])
                ->one();

        if(!$model){
            return $this->flash('查看的数据对象不存在', 'error');
        }

        return $this->render('statement-' . $type, [
                    'model' => $model
        ]);
    }

    /**
     * 搜索客户
     */
    public function actionAjaxGetCustomer()
    {
        $cusromerInfo = [];
        $info = '';
        $linkInfo = [];

        $request = Yii::$app->request;
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $keywords = trim($request->get('keywords'));
        $statementId = $request->get('statement_id');
        $customerNo = (int) $request->get('customer_no');
        $categoryId = trim($request->get('customer_category_id')); //客户分类
        $districtId = $request->get('customer_district_id'); //客户区域
        if(empty($keywords) && empty($customerId) && empty($categoryId) && empty($districtId)){
            return;
        }
        $query = Customer::find()->where(['status' => 1]);
        $query->orderBy(['attention' => SORT_DESC, 'customer_id' => SORT_DESC]);

        if(!empty($keywords)){
            $query->where(['like', 'name', $keywords]);
        }
//        if(!empty($customerNo)){
//            $query->orWhere(['customer_no' => $customerNo]);
//        }
        if(!empty($categoryId)){
            $query->andWhere(['in', 'category_id', explode(',', $categoryId)]);
        }
        if(!empty($districtId)){
            $query->andWhere(['in', 'district_id', explode(',', $districtId)]);
        }
//   echo $query->createCommand()->sql;
        $cusromerList = $query->all();

        $linkInfo = StatementLink::getLinkInfo($statementId, 'customer', '', 'link_id', true);
        if(!empty($cusromerList)){
            foreach ($cusromerList as $key => $customer) {
                $dealUrl = '';
                $categoryName = empty($customer['category']['name']) ? '' : $customer['category']['name'];
                $districtName = empty($customer['district']['name']) ? '' : $customer['district']['name'];
                $leaderName = empty($customer['leader']['realname']) ? '' : $customer['leader']['realname'];
                if(in_array($customer['customer_no'], $linkInfo)){
                    $dealUrl = "<a href='javascript:void(0);' data-customer_no='{$customer['customer_no']}' class='delete_link' style='color:red'>解除</a>";
                } else {
                    $dealUrl = "<a href='javascript:void(0);' data-customer_no='{$customer['customer_no']}' class='add_link'>关联</a>";
                }
                $info .= "<tr><td>{$customer['name']}</td><td>{$categoryName}</td><td>{$districtName}</td><td>{$leaderName}</td><td>{$dealUrl}</td></tr>";
            }
        }
        return $info;
    }

    /**
     * 创建关联客户
     */
    public function actionCreateLink()
    {
        if(!Auth::checkAccess('statement/statement-account/statement-link')){
            throw new ForbiddenHttpException('权限不足！');
        }
        $request = Yii::$app->request;
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $statementId = (int) $request->get('statement_id');
        $customerId = $request->get('customer_no');

        if(empty($statementId) && empty($customerId)){
            return ['status' => 0, 'info' => '操作失败！'];
        }
        if($model = call_user_func([new StatementLink(), 'findOne'], $statementId)){
            return ['status' => 0, 'info' => '请先解除已关联客户！'];
        } else {
            $model = new StatementLink();
        }

        $model->statement_id = $statementId;
        $model->link_type = 'customer';
        $model->link_id = $customerId;
        $result = $model->save();

        if($result == false){
            $firstError = reset($model->getFirstErrors());
            return ['status' => 0, 'info' => $firstError];
        } else {
            return ['status' => 1, 'info' => '关联成功！'];
        }
    }

    /**
     * 解除客户关联
     */
    public function actionDeleteLink()
    {
        if(!Auth::checkAccess('statement/statement-account/index')){
            throw new ForbiddenHttpException('权限不足！');
        }
        $request = Yii::$app->request;
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $statementId = $request->get('statement_id');
        $customerId = $request->get('customer_no');

        if(empty($statementId) && empty($customerId)){
            return ['status' => 0, 'info' => '操作失败！'];
        }
        $model = StatementLink::find()
                ->where(['statement_id' => $statementId, 'link_type' => 'customer', 'link_id' => $customerId])
                ->one();
        if(empty($model)){
            return ['status' => 0, 'info' => '操作对象不存在！'];
        }

        $result = $model->delete();
        if($result == false){
            $firstError = reset($model->getFirstErrors());
            return ['status' => 0, 'info' => $firstError];
        } else {
            return ['status' => 1, 'info' => '解除成功！'];
        }
    }

    /**
     * 创建关联合同
     */
    public function actionCreateLinkContract()
    {
        $request = Yii::$app->request;
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $contractArr = [];
        $contractInfo = [];

        $statementId = (int) $request->get('statement_id');
        $contractMoney = $request->get('contract_money');
        if(empty($statementId) || empty($contractMoney)){
            return ['status' => 0, 'info' => $contractMoney . $statementId . '操作失败！'];
        }
        $statementInfo = StatementAccount::findOne($statementId);
        if(is_array($contractMoney)){
            foreach ($contractMoney as $key => $vo) {
                $contractInfo = explode('@', $vo);
                StatementLinkContract::createLink(['statement_id' => $statementId, 'contract_no' => $contractInfo[0], 'money' => $contractInfo[1]]);
                unset($contractInfo);
            }
        }
        return ['status' => 1, 'info' => '关联成功！'];
    }

}
