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

namespace home\modules\contract\controllers;

use Yii;
use home\controllers\Controller;
use home\modules\contract\models\Contract;
use common\models\PermissionScope;
use yii\helpers\ArrayHelper;
use common\models\Common;
use home\modules\customer\models\District;
use yii\data\ActiveDataProvider;
use home\modules\customer\models\Customer;
use common\models\User;
use common\models\ExcelExport;
use home\modules\receivable\models\Receivable;
use home\modules\receivable\models\Billing;
use qcbase\models\Auth;

/**
 * 合同控制器
 * 
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class ContractController extends Controller
{

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

        //逻辑删除
        $actions['delete'] = [
            'class' => 'home\actions\TrashDelete',
            'to' => ['index'],
            'trashModel' => 'home\modules\contract\models\ContractTrash',
            'scopeAccessFields' => ['user_id', 'owner_id']
        ];
        return $actions;
    }
    
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 合同列表首页
     * 获取列表数据 iframe
     */
    public function actionIndexIframe()
    {
        if(!Auth::checkAccess('contract/contract/index')){
            throw new ForbiddenHttpException('权限不足！');
        }
        
        $model = new Contract();
        $query = Contract::find();
        $query->orderBy(['contract_id' => SORT_DESC]);

        $request = Yii::$app->request;
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $status_id = $request->get('status_id');
        $collate_status = $request->get('collate_status');
        $bill_collate_status = $request->get('bill_collate_status');
        $money_collate_status = $request->get('money_collate_status');
        $child_ids = $request->get('child_ids');  //客户区域
        $districtArray = explode(',', $child_ids);

        $beginTime = trim($request->get('begin_time'));
        $endTime = trim($request->get('end_time'));

        if (!empty($keywords) && !empty($field)) {
            switch ($field) {
                case 'realname':
                    $userIds = User::find()->where(['like', $field, $keywords])->select('user_id')->asArray()->all();
                    $userIdsArray = arrayHelper::getColumn($userIds, 'user_id');
                    $query->where(['in', 'owner_id', $userIdsArray]);
                    break;
                case 'customer':
                    $customerNo = Customer::find()->where(['like', 'name', $keywords])->select('customer_no')->asArray()->column();
                    $query->where(['in', 'customer_no', $customerNo]);
                    break;
                default :
                    $query->where(['like', $field, $keywords]);
            }
        }
        if (!empty($status_id)) {
            $query->andWhere(['status_id' => (int) $status_id]);
        }

        if ($collate_status !== '' && $collate_status !== NULL) {
            $query->andWhere(['collate_status' => $collate_status]);
        }
        //开票核对
        if ($bill_collate_status !== '' && $bill_collate_status !== NULL) {
            $query->andWhere(['bill_collate_status' => $bill_collate_status]);
        }
        //回款核对
        if ($money_collate_status !== '' && $money_collate_status !== NULL) {
            $query->andWhere(['money_collate_status' => $money_collate_status]);
        }
        if (!empty($child_ids)) {
            $district = Customer::find()->select('customer_no')->where(['in', 'district_id', $districtArray])->asArray()->all();
            $customerArray = arrayHelper::getColumn($district, 'customer_no');
            $query->andWhere(['in', 'customer_no', $customerArray]);
        }
        //签约时间
        if (!empty($beginTime)) {
            $beginTime = strtotime($beginTime);
            $query->andWhere('signing_time >= :beginTime', [':beginTime' => $beginTime]);
        }
        if (!empty($endTime)) {
            $endTime = strtotime($endTime);
            $query->andWhere('signing_time <= :endTime', [':endTime' => $endTime + 24 * 60 * 60]);
        }

        //权限判断，除了超级管理员以外的都只能看到自己负责区域的客户所关联的合同
        if (!Yii::$app->session->get('isSuperAdmin')) {
            $scopeUser = PermissionScope::getScopeUser("contract/contract/index");  //查找合同的权限范围
            $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]);
            }
        }
//        echo $query->createCommand()->sql;

        \Yii::$app->session->set('contract_query', clone $query);
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 15,
            ],
        ]);

        $total = Contract::SumMoney(clone $query);
        $total['money'] = $query->sum('money');
        $this->layout = '//modal';
        return $this->render('index-iframe',
                [
                'get' => $request->get(),
                'model' => new Contract(),
                'models' => $provider->models,
                'pages' => $provider->pagination,
                'total' => $total
        ]);
    }

    /**
     * 编辑合同
     */
    public function actionView()
    {
        $this->layout = '//modal';
        $model = new Contract();
        $id = (int) Yii::$app->request->get('id');
        $model = call_user_func([$model, 'findOne'], $id);
        $action = ['/contract/contract/update'];
        if (empty($id) || !$model) {
            Yii::$app->getSession()->setFlash('error', '编辑的对象不存在');
            $action = [''];
            return $this->redirect(['index']);
        }
        if (!Yii::$app->session->get('isSuperAdmin')) {
            $session = Yii::$app->getSession();
            $permission = Common::getActionPermission($this->action);
            $result = PermissionScope::getScopeUser($permission);  //查找合同的权限范围
            if ($result === false) {
                $session->setFlash('error', '没有权限查看ID为' . $id . '的对象');
                $action = [''];
                //return $this->redirect(['index']);
            } else if ($result !== []) {
                $contractResult = Contract::find()->Where(['in', 'owner_id', $result])->select('customer_no')->asArray()->all();
                $contractArray = arrayHelper::getColumn($contractResult, 'customer_no');
                if (empty($contractArray) || !in_array($model['customer_no'], $contractArray)) {
                    $session->setFlash('error', '没有权限查看ID为' . $id . '的对象');
                    $action = [''];
                    //return $this->redirect(['index']);
                }
            }
        }
        return $this->render('create', [
                'model' => $model,
                'action' => $action
        ]);
    }

    /**
     * 添加合同，选择项目时，自动调取客户名称的回掉操作
     *
     * 获取客户的基本信息
     * @return array  返回一个状态，当不为空时，在附带其他值
     */
    public function actionGetCustomerMessage()
    {
                
    }

    /**
     * 查看合同详情
     */
    public function actionDetail()
    {
        $model = new Contract();
        $id = (int) Yii::$app->request->get('id');
        $model = call_user_func([$model, 'findOne'], $id);
        //权限判断，除了超级管理员以外的都只能看到自己负责区域的客户所关联的合同
        if (!Yii::$app->session->get('isSuperAdmin')) {
            $session = Yii::$app->getSession();
            $permission = Common::getActionPermission($this->action);
            $scopeUser = PermissionScope::getScopeUser($permission);  //查找合同的权限范围
            $result = District::getMyDistrict("customer/customer/index");  //查找客户的权限范围
            if ($scopeUser === [] || $result===[] ) {
                return $this->render('detail', [
                    'model' => $model,
                ]);
            }

            if (count($scopeUser) > 0 && count($result) > 0) {
                $district = Customer::find()->select('customer_no')->where(['in', 'district_id', $result])->asArray()->all();
                $customerArray = arrayHelper::getColumn($district, 'customer_no');
                $endResult = Contract::find()->andWhere(['or', ['in', 'owner_id', $scopeUser], ['in', 'customer_no', $customerArray]])->select('customer_no')->asArray()->all();
                $contractArray = arrayHelper::getColumn($endResult, 'customer_no');
            } else if (count($scopeUser) > 0 && ($result === false)) {
                $endResult = Contract::find()->andWhere(['in', 'owner_id', $scopeUser])->select('customer_no')->asArray()->all();
                $contractArray = arrayHelper::getColumn($endResult, 'customer_no');
            } else if (count($result) > 0 && ($scopeUser === false)) {
                $district = Customer::find()->select('customer_no')->where(['in', 'district_id', $result])->asArray()->all();
                $customerArray = arrayHelper::getColumn($district, 'customer_no');
                $endResult = Contract::find()->andWhere( ['in', 'customer_no', $customerArray])->select('customer_no')->asArray()->all();
                $contractArray = arrayHelper::getColumn($endResult, 'customer_no');
            } else if (($scopeUser === false) && ($result === false)) {
                $session->setFlash('error', '没有权限查看ID为' . $id . '的对象');
                return $this->redirect(['index']);
            }
            if (empty($contractArray) || !in_array($model['customer_no'], $contractArray)) {
                $session->setFlash('error', '没有权限查看ID为' . $id . '的对象');
                return $this->redirect(['index']);
            }
        }
        return $this->render('detail', [
                'model' => $model,
        ]);
    }

    /**
     * ajax更改项目数据核对状态
     */
    public function actionSetCheck()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        $check = (int) $request->get('check');
        $statusName = $request->get('status_name');

        if (empty($id)) {
            $data = ['status' => 0, 'info' => '数据错误'];
            return $data;
        }

        $contract = Contract::find()
            ->where(['contract_id' => $id])
            ->one();
        if (!$contract) {
            $data = ['status' => 0, 'info' => '合同数据错误'];
            return $data;
        } elseif (!Yii::$app->session->get('isSuperAdmin') && !Contract::readAccess('contract/contract/set-check')) {
            //如果不是负责人或没有修改权限则不能修改
            $data = ['status' => 0, 'info' => '当前无权操作此项目'];
            return $data;
        }

        return Contract::setCollate($id, $check, $statusName);
    }

    /**
     * 点击查看合同的金额
     */
    public function actionAmount()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        if (empty($id)) {
            $data = ['status' => 0, 'info' => '数据错误'];
            return $data;
        }
        $contract = Contract::find()
            ->where(['contract_id' => $id])
            ->select('money')
            ->one();
        if (!$contract) {
            $data = ['status' => 0, 'info' => '合同金额数据错误'];
            return $data;
        } elseif (!Yii::$app->session->get('isSuperAdmin') && !Contract::readAccess('contract/contract/amount')) {
            $data = ['status' => 0, 'info' => '当前操作没有权限'];
            return $data;
        }
        $money = number_format($contract['money'], 2, '.', ',');
        $data = ['status' => 1, 'info' => $money];
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $data;
    }

    /**
     * 维保期开始结束日期
     */
    public function actionGetMaintPeriod()
    {
        $request = \Yii::$app->request;
        $maint_period = $request->post('maint_period');
        $acceptance_time = strtotime($request->post('acceptance_time'));
        $dataInfo = [
            'begin_time' => date("Y-m-d", $acceptance_time),
            'end_time' => date("Y-m-d", strtotime('+' . $maint_period . ' month', $acceptance_time)),
        ];
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $dataInfo;
    }

    /**
     * 合同导出
     */
    public function actionExport()
    {
        set_time_limit(0);
        $export = new ExcelExport();
        $userList = \Yii::$app->cache->get("user_list");
        $export->fileTitle = '合同列表';

//        合同编号 合同名称 真实客户 签约客户 所有人 签订日期 金额(元) 已回款 已开票 状态 跟进日期
        $export->cellArray = [
            'A' => ['width' => '20', 'title' => '合同编号', 'row' => 2, 'attribute' => 'contract_no'],
            'B' => ['width' => '50', 'title' => '合同名称', 'row' => 2, 'attribute' => 'name'],
            'C' => ['width' => '30', 'title' => '真实客户', 'row' => 2, 'attribute' => 'real_customer_name'],
            'D' => ['width' => '30', 'title' => '签约客户', 'row' => 2, 'attribute' => 'customer_name'],
            'E' => ['width' => '15', 'title' => '所有人', 'row' => 2, 'attribute' => 'owner'],
            'F' => ['width' => '15', 'title' => '签订日期', 'row' => 2, 'attribute' => 'signing_time'],
            'G' => ['width' => '15', 'title' => '金额(元)', 'row' => 2, 'attribute' => 'money'],
            'H' => ['width' => '15', 'title' => '已回款', 'row' => 2, 'attribute' => 'receivable_money'],
            'I' => ['width' => '15', 'title' => '已开票', 'row' => 2, 'attribute' => 'billing_money'],
            'J' => ['width' => '10', 'title' => '状态', 'row' => 2, 'attribute' => 'status_name'],
            'K' => ['width' => '10', 'title' => '跟进日期', 'row' => 2, 'attribute' => 'judge_follow']
        ];

        $export->styleAlignment = [
            'A' => [
                'horizontal' => 'left',
                'vertical' => 'center'
            ],
            'B' => [
                'horizontal' => 'left',
                'vertical' => 'center'
            ],
            'G' => [
                'horizontal' => 'right',
                'vertical' => 'center'
            ],
            'H' => [
                'horizontal' => 'right',
                'vertical' => 'center'
            ],
            'I' => [
                'horizontal' => 'right',
                'vertical' => 'center'
            ]
        ];
        $export->mergeCells = ['A1:K1'];
        $export->lastRowName = 'K';
        $query = \Yii::$app->session->get('contract_query');
        $query = $query->asArray()->all();
        if (!empty($query) && is_array($query)) {
            foreach ($query as $key => &$value) {
                $realCustomer = Customer::findOne(['customer_no' => $value['real_customer_no']]);
                $customer = Customer::findOne(['customer_no' => $value['customer_no']]);
                $value['real_customer_name'] = $realCustomer['name'];
                $value['customer_name'] = $customer['name'];
                $value['owner'] = !empty($userList[$value['owner_id']]['realname']) ? $userList[$value['owner_id']]['realname'] : '';
                $value['signing_time'] = date('Y/m/d', $value['signing_time']);
                $value['money'] = number_format($value['money'], 2, '.', ',');
                $receivableMoney = Receivable::find()->where(['contract_no' => $value['contract_no']])->sum('rece_money');
                $value['receivable_money'] = number_format($receivableMoney, 2, '.', ',');
                $billingMoney = Billing::find()->where(['contract_no' => $value['contract_no']])->sum('invoice_money');
                $value['billing_money'] = number_format($billingMoney, 2, '.', ',');
                $value['judge_follow'] = strip_tags(Contract::judgeFollow($value['contract_id']));
            }
        }
        $export->exportData = $query;
        $export->export();
    }
    
    /**
     * 左侧树形分类列表数据
     */
    public function actionGetTreedata()
    {
        $data = District::getCateData('district_id as cat_id,name,parent_id,parent_ids,child_ids,sort,status', ['status' => 1], ['sort' => SORT_ASC, 'district_id' => SORT_DESC]);
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $data;
    }
}
