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

namespace home\modules\customer\controllers;

use yii;
use home\controllers\Controller;
use home\modules\customer\models\Customer;
use home\modules\customer\models\District;
use home\modules\customer\models\CustomerTrash;
use yii\data\ActiveDataProvider;
use home\modules\customer\models\DistrictLink;
use common\models\Common;
use yii\helpers\ArrayHelper;
use common\models\PermissionScope;
use common\models\User;
use qcbase\models\Auth;
use qcbase\models\Department;
use home\modules\sale\models\Opportunity;

/**
 * 客户控制器
 *
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class CustomerController extends Controller
{

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

    public function actionIndex()
    {
        //$departmentList = User::getListByDepartment([], 3);
        return $this->render('index');
    }

    /**
     * 客户列表首页
     */
    public function actionIndexIframe()
    {
        if (!Auth::checkAccess('customer/customer/index')) {
            throw new ForbiddenHttpException('权限不足！');
        }
        $query = Customer::find();
        $query->orderBy(['attention' => SORT_DESC, 'customer_id' => SORT_DESC]);

        $request = Yii::$app->request;
        $category_id = $request->get('category_id');       //客户类别
        $child_ids = $request->get('child_ids');  //客户区域
        $keywords = trim($request->get('keywords'));
        $status = $request->get('status');
        $field = $request->get('search_field');
        if (!empty($keywords) && !empty($field)) {
            if ($field == 'leader_name') {
                $userIds = \common\models\User::find()->where(['like', 'realname', $keywords])->select('user_id')->asArray()->all();
                $userIdsArray = arrayHelper::getColumn($userIds, 'user_id');
                $query->where(['in', 'leader_id', $userIdsArray]);
            } else {
                $query->where(['like', $field, $keywords]);
            }
        }
        if ($status != '') {
            $query->andWhere(['status' => (int) $status]);
        }
        if (!empty($category_id)) {
            $query->andWhere(['in', 'category_id', explode(',', $category_id)]);
        }
        if (!empty($child_ids)) {
            $query->andWhere(['in', 'district_id', explode(',', $child_ids)]);
        }
        $userId = Yii::$app->user->id;
        //权限判断，除了超级管理员以外的都只能看到自己负责区域的客户
        if (!Yii::$app->session->get('isSuperAdmin')) {
            $scopeUser = PermissionScope::getScopeUser("customer/customer/index");
            if (!empty($scopeUser)) {
                $findArr = [];
                foreach ($scopeUser as $u) {
                    $findArr[] = 'FIND_IN_SET(' . (int) $u . ', share_user_ids)';
                }
                $findStr = implode(' or ', $findArr);
                $query->andWhere(' `leader_id` in (' . implode(', ', $scopeUser).') or ' . $findStr );
            }
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 15,
            ],
        ]);
        $this->layout = '//modal';
        //$dept_id = Department::find()->where(['like', 'name', '销售'])->select('dept_id')->one();
        //$departmentList = User::getListByDepartment([], $dept_id->dept_id);
        $onePageData = [];
        foreach ($provider->models as $k => $v) {
            $onePageData[] = $v['customer_id'];
        }
        $stringData = implode(',', $onePageData);
        return $this->render('index-iframe', [
                'get' => $request->get(),
                'model' => new Customer(),
                'models' => $provider->models,
                'pages' => $provider->pagination,
                //'departmentList' => $departmentList,
                'stringData' => $stringData,
        ]);
    }

    /**
     * 编辑客户
     */
    public function actionView()
    {
        $this->layout = '//modal';
        $model = new Customer();
        $id = (int) Yii::$app->request->get('id');
        $model = call_user_func([$model, 'findOne'], $id);
        if (empty($id) || !$model) {
            Yii::$app->getSession()->setFlash('error', '编辑的对象不存在');
            return $this->redirect(['index']);
        }
        if (!Yii::$app->session->get('isSuperAdmin')) {
            $session = Yii::$app->getSession();
            $permission = Common::getActionPermission($this->action);
            $result = PermissionScope::getScopeUser($permission);
//          $result = District::getMyDistrict($permission);
            if ($result === false) {
                $session->setFlash('error', '没有权限查看ID为' . $id . '的对象');
                return $this->redirect(['index']);
            }
        }
        return $this->render('create', [
                'model' => $model,
                'action' => ['/customer/customer/update'],
        ]);
    }

    /**
     *  查看当前客户的详情
     */
    public function actionDetail()
    {
        $model = new Customer();
        $query = Customer::find();
        $id = (int) Yii::$app->request->get('id');
        if (empty($id)) {
            $this->redirect(['index']);
        }
        $queryWhere = "customer_id=" . $id;
        $session = Yii::$app->getSession();
        $permission = Common::getActionPermission($this->action);
        $scopeUser = PermissionScope::getScopeUser($permission);
        if (!Yii::$app->session->get('isSuperAdmin')) {
            if (!empty($scopeUser)) {
                $userId = Yii::$app->user->id;
                $queryWhere .=" and (leader_id in(" . implode(',', $scopeUser) . ") or FIND_IN_SET('" . (int) $userId . "', share_user_ids))";
            }
            if ($scopeUser === false) {
                $session->setFlash('error', '没有权限查看ID为' . $id . '的对象');
                return $this->redirect(['index']);
            }
        }

        $query->where($queryWhere);
        $model = $query->one();
//        $command = $query->createCommand();
//        var_dump($command->sql);
        if (empty($model)) {
            $this->redirect(['index']);
        }
        return $this->render('detail', [
                'model' => $model,
        ]);
    }

    /**
     * 逻辑删除操作
     */
    public function actionDelete()
    {
        $model = new Customer();
        $query = Yii::$app->request;
        $id = (int) $query->get('id');
        $ids = $query->post('delete');
        $session = Yii::$app->getSession();
        if (empty($id) && empty($ids)) {
            $session->setFlash('error', '要删除的对象不存在');
        } else {
            //权限范围过滤
            $permission = Common::getActionPermission($this->action);
            $result = PermissionScope::getScopeUser($permission);
//            $result = District::getMyDistrict($permission);
            if ($result === false) {
                $session->setFlash('error', '没有权限删除ID为' . $id . '的对象');
                $success = false;
                $canDelete = false;
            } else if ($result === []) {
                !empty($id) && $ids[] = $id;
                $success = true;
                $canDelete = true;
                foreach ($ids as $id) {
                    if (!$model = call_user_func([$model, 'findOne'], $id)) {
                        $session->setFlash('error', 'ID为' . $id . '的对象不存在');
                        $success = false;
                        break;
                    }
                    $attributes = $model->attributes;
                    $trashModel = new CustomerTrash(['scenario' => 'trash']);
                    $trashModel->attributes = $attributes;
                    if (!$trashModel->save()) {
                        $success = false;
                        $session->setFlash('error', 'ID为' . $id . '的对象删除到回收站失败');
                        break;
                    }
                    $model->delete();
                }
            } else {
                !empty($id) && $ids[] = $id;
                $success = true;
                $canDelete = true;

                foreach ($ids as $id) {
                    if (!$model = call_user_func([$model, 'findOne'], $id)) {
                        $session->setFlash('error', 'ID为' . $id . '的对象不存在');
                        $success = false;
                        break;
                    }
                    //权限范围判断
                    $canDelete = false;
                    if (in_array($model->leader_id, $result)) {
                        $canDelete = true;
                    } else {
                        $session->setFlash('error', '没有权限删除ID为' . $id . '的对象');
                    }
                    if ($canDelete) {
                        $attributes = $model->attributes;
                        $trashModel = new CustomerTrash(['scenario' => 'trash']);
                        $trashModel->attributes = $attributes;
                        if (!$trashModel->save()) {
                            $success = false;
                            $session->setFlash('error', 'ID为' . $id . '的对象删除到回收站失败');
                            break;
                        }
                        $model->delete();
                    }
                }
            }

            if ($canDelete && $success) {
                $session->setFlash('success', '删除成功');
            }
        }
        return $this->redirect(['index']);
    }

    public function actionUpdateAddress()
    {
        exit();
        $request = \Yii::$app->request;

        //查找省，市，区 串联起来赋值给地址栏
        $address_ids = $request->post('Customer');
        $province_id = $address_ids['province_id'];
        $city_id = $address_ids['city_id'];
        $area_id = $address_ids['area_id'];

        $province = \home\models\Area::findOne($province_id);
        $city = \home\models\Area::findOne($city_id);
        $area = \home\models\Area::findOne($area_id);
        $address = $province['title'] . $city['title'] . $area['title'];

        //当所有的都查为空，给默认值0
        $district_id = 0;
        //查找区ID对应的客户区域ID
        $returnArea = DistrictLink::find()->select('district_id')->where(['area_id' => $area_id])->orderBy(['link_id' => SORT_DESC])->one();
        if (!empty($returnArea)) {
            $district_id = $returnArea['district_id'];
        } else {
            //当区查无内容时，查找市ID对应的客户区域ID
            $returnCity = DistrictLink::find()->select('district_id')->where(['city_id' => $city_id])->orderBy(['link_id' => SORT_DESC])->one();
            if (!empty($returnCity)) {
                $district_id = $returnCity['district_id'];
            } else {
                //当市查无内容时，查找省ID对应的客户区域ID
                $returnProvince = DistrictLink::find()->select('district_id')->where(['province_id' => $province_id])->orderBy(['link_id' => SORT_DESC])->one();
                if (!empty($returnProvince)) {
                    $district_id = $returnProvince['district_id'];
                }
            }
        }

        $data = [
            'province_id' => $province_id,
            'city_id' => $city_id,
            'area_id' => $area_id,
            'address' => $address,
            'district_id' => $district_id
        ];

        $ids = $request->post('delete');
        if (!empty($ids)) {
            $command = Yii::$app->db->createCommand();
            foreach ($ids as $id) {
                $result = $command->update('{{%customer}}', $data, 'customer_id =:customer_id', [':customer_id' => $id])->execute();

                if ($result == 0) {
                    return $this->flash($id . '更新失败！请稍后再试！', 'error');
                }
            }

            return $this->flash('更新成功！', 'success');
        }
        return $this->flash('参数不全，请稍后再试！', 'error');
    }

    public function actionShiftLeader()
    {
        if (!Auth::checkAccess('customer/customer/shift-leader')) {
            throw new ForbiddenHttpException('权限不足！');
        }
        $request = \Yii::$app->request;
        $leader_id = $request->post('leader_id');
        //$type为1：当前页选中的转移    为2：当前页未选中的转移
        $type = $request->post('type');
        $stringData = $request->post('stringData');
        $ids = $request->post('delete');
        if ($type == 2) {
            $stringData = explode(',', $stringData);
            $ids = array_diff($stringData, $ids);
        }
        $this->layout = '//modal';
        if (!empty($ids)) {
            $command = Yii::$app->db->createCommand();
            foreach ($ids as $id) {
                $users = Customer::find()->where(['customer_id' => $id])->select(' customer_no, leader_id, share_user_ids')->one();
                $shareUser = $users->share_user_ids;
                if (!empty($shareUser)) {
                    $shareUserArray = explode(',', $shareUser);
                    $key = in_array($leader_id, $shareUserArray) ? array_search($leader_id, $shareUserArray) : FALSE;
                    if ($key !== FALSE) {
                        unset($shareUserArray[$key]);
                    }
                    $shareUserArray[] = $users->leader_id;
                    $shareUserArray = array_unique($shareUserArray);
                    $shareUser = implode(',', $shareUserArray);
                    $result = $command->update('{{%customer}}', ['leader_id' => $leader_id, 'share_user_ids' => $shareUser], 'customer_id =:customer_id', [':customer_id' => $id])->execute();
                } else {
                    $result = $command->update('{{%customer}}', ['leader_id' => $leader_id, 'share_user_ids' => $users->leader_id], 'customer_id =:customer_id', [':customer_id' => $id])->execute();
                }
                if ($result == 0) {
                    return $this->flash($id . '更新失败！请稍后再试！', 'error');
                }
                $customerNo = $users->customer_no;
                $command = Yii::$app->db->createCommand();
                $command->update('{{%sale_opportunity}}', ['leader_id' => $leader_id], 'customer_no = :customer_no', [':customer_no' => $customerNo])->execute(); 
            }
            return $this->flash('转移成功！', 'success');
        }
        return $this->flash('没有可以转移的，请重新选择！', 'error');
    }

    /**
     * 左侧树形分类列表数据
     */
    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;
    }
}
