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

namespace home\widgets\portlet;

use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\base\InvalidConfigException;
use home\modules\contract\models\Contract;
use home\modules\customer\models\District;
use home\modules\customer\models\Customer;
use common\models\PermissionScope;

/**
 * 我的合同组件
 * 
 * 调用方法如下：
 *
 * ```php
 * <?= ContractPortlet::widget([
 *     'title' => '测试组件',
 *     'x' => 0,
 *     'y' => 0,
 * ]) ?>
 * ```
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class ContractPortlet extends BasePortlet
{
	/**
     * @inheritdoc
     */
    public function getContent()
    {
        $query = Contract::find();
        $query->orderBy(['contract_id' => SORT_DESC]);

        $scopeUser = PermissionScope::getScopeUser('contract/contract/index');  //查找合同的权限范围
        $scopeUser = ($scopeUser === false) ? [Yii::$app->user->id] : $scopeUser;
        if (!Yii::$app->session->get('isSuperAdmin')) {
            $districtUser = District::getMyDistrict("customer/customer/index");  //查找客户的权限范围
            if (!empty($scopeUser)) {
                if (!empty($districtUser)) {
                    $district = Customer::find()->select('customer_no')->where(['in', 'district_id', $districtUser])->asArray()->all();
                    $customerArray = arrayHelper::getColumn($district, 'customer_no');
                    $query->andWhere(['or', ['in', 'owner_id', $scopeUser], ['in', 'customer_no', $customerArray]]);
                }else {
                    $query->andWhere(['in', 'owner_id', $scopeUser]);
                }
            } else if (!empty($districtUser)) {
                $district = Customer::find()->select('customer_no')->where(['in', 'district_id', $districtUser])->asArray()->all();
                $customerArray = arrayHelper::getColumn($district, 'customer_no');
                $query->andWhere( ['in', 'customer_no', $customerArray]);
            }
        }

        $contracts = $query->limit(5)->all();

        return $this->render('contract', [
            'contracts'=> $contracts
        ]);
    }
}
