Agentlist.php 13.1 KB
<?php

namespace app\admin\controller\agent;

use app\common\controller\Backend;
use think\Db;
use app\api\controller\v1\WxXcxQrcode;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 企业管理
 *
 * @icon fa fa-circle-o
 */
class Agentlist extends Backend
{
    protected $noNeedRight = ['index'];
    /**
     * Agentlist模型对象
     * @var \app\admin\model\agent\Agentlist
     */
    protected $model = null;
    protected $dataLimit = 'auth'; //默认基类中为false,表示不启用,可额外使用auth和personal两个值
    protected $dataLimitField = 'admin_id'; //数据关联字段,当前控制器对应的模型表中必须存在该字段
    protected $isSup = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\agent\Agentlist;
        $this->view->assign("agentStuList", $this->model->getAgentStuList());
        $this->view->assign("payStuList", $this->model->getPayStuList());
        //判断是否是超级管理员
        if (in_array($this->auth->id, [1, 2, 26, 32, 37])) {
            $this->isSup = 1;
        } else {
            $this->isSup = 0;
        }
        $this->view->assign("isSup", $this->isSup);
    }

    public function import()
    {
        parent::import();
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparamsAdm();

            $list = $this->model
                ->with(['user', 'agentcategory'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'user_id', 'agent_name', 'head_image', 'createtime', 'fr_name', 'fr_mobile', 'fzr_name', 'fzr_mobile', 'address', 'latitude', 'longitude', 'add_day', 'yeji', 'year_pays', 'pay_amount', 'card_image', 'cert_images', 'cert_desc', 'agent_content', 'agent_stu', 'start_pay_time', 'end_pay_time', 'pay_stu', 'credit']);
                $row->visible(['user', 'agentcategory']);
                $row->getRelation('user')->visible(['username', 'nickname']);
                $row->getRelation('agentcategory')->visible(['catname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;

                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if ($params['agent_stu'] == "1") {
                        //审核通过;生成小程序二维码
                        $qrcode_api = new WxXcxQrcode();
                        $path = '/pages/home/company/detail?id=' . $this->model->id;
                        $qrcode = $qrcode_api->qrcode($this->model->id, $path, true);
                        if (!empty($qrcode)) {
                            Db::name("agent_list")->where("id", $this->model->id)->update(["qrcode" => $qrcode, 'updatetime' => time()]);
                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        /*if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }*/
        if (!in_array($this->auth->id, [1, 2, 26, 32, 37])) {
            if (is_array($adminIds)) {
                if (!in_array($row[$this->dataLimitField], $adminIds)) {
                    $this->error(__('You have no permission'));
                }
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->isSup == 0) {
                    $params['agent_stu'] = 0;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if ($params['agent_stu'] == "1") {
                        //审核通过;生成小程序二维码
                        $qrcode_api = new WxXcxQrcode();
                        $path = '/pages/home/company/detail?id=' . $row->id;
                        $params['qrcode'] = $qrcode_api->qrcode($row->id, $path, true);

                        //用法人手机号创建管理员和角色组
                        $rr = add_group_and_admin($params['fr_mobile'], $params['agent_name']);
                        if ($rr['back_falg'] == true) {
                            //更新admin_id
                            $params['admin_id'] = $rr['uid'];
                        }

                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //推送公众号消息给入驻人
                    if ($params['agent_stu'] == '1' || $params['agent_stu'] == '2') {
                        if ($params['agent_stu'] == '1') {
                            $desctit = "企业入驻审核通过";
                            $remark = '审核通过';
                        }
                        if ($params['agent_stu'] == '2') {
                            $desctit = "企业入驻审核不通过";
                            $remark = '不通过原因:' . $params['remark'];
                        }
                        //获得入驻人openid
                        $openid = Db::name('user')
                            ->alias('u')
                            ->join('wct_user wct', 'u.unionid=wct.unionid')
                            ->where(['u.id' => $params['user_id']])
                            ->field('wct.id,wct.wx_openid')
                            ->find();
                        if (!empty($openid['wx_openid'])) {
                            //推送公众号模板信息给企业管理人
                            $this->senWxmsgToAgentUser($desctit, $openid['wx_openid'], $remark);
                        }
                    }

                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /***
     * 公众号推送审核信息给经纪人
     */
    private function senWxmsgToAgentUser()
    {
        $remark="";
        $titdesc="";
        $wxopenid="oYhYi6fEAxSnlAV1qNm2BwaJdQOQ";
        $sendInfo = array(
            'first' => array('value' => urlencode($titdesc), 'color' => "#743A3A"),
            'keyword1' => array('value' => urlencode(date('Y-m-d H:i:s', time())), 'color' => '#173177'),
            'keyword2' => array('value' => urlencode('企业入驻'), 'color' => '#173177'),
            'remark' => array('value' => urlencode($remark), 'color' => '#173177'),
        );
        if ($wxopenid) {
            $config = get_addon_config('wechat');
            $tourl = 'https://fdc.xp.yn.cn/h5/';
            $ywt_appid = 'wx9f73637c6b8f2c47';
            $pagepath = 'pages/home/index';
            $res = sendAstuWxMsgToAgent($sendInfo, $wxopenid, $tourl, $config['app_id'], $config['secret'], $ywt_appid, $pagepath);
            //file_put_contents("pcl_wct_send.log", date("Y-m-d H:i:s") . "1-2-" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        }
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', [1, 2, 26, 32, 37]);
            }
            $list = Db::name('agent_list')->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    //获得企业下门店信息
                    $shoplist = Db::name('agent_shop')
                        ->where(['agent_list_id' => $v['id']])
                        ->select();
                    $list[$k]['shop_list'] = $shoplist;
                    //先生成数据日志
                    $logs['admin_id'] = $this->auth->id;
                    $logs['type'] = 'del';
                    $logs['tablename'] = 'agent_list';
                    $logs['content'] = json_encode($list[$k], JSON_UNESCAPED_UNICODE);
                    $logs['createtime'] = time();
                    Db::name('agent_admin_dologs')->insertGetId($logs);
                    //禁用企业后台管理员账号
                    if ($v['admin_id'] > 2 && $v['admin_id'] != $this->auth->id) {
                        $adminadm['status'] = 'hidden';
                        $adminadm['updatetime'] = time();
                        Db::name('admin')
                            ->where(['id' => $v['admin_id']])
                            ->update($adminadm);
                    }
                    if ($shoplist) {
                        //删除企业的门店信息
                        Db::name('agent_shop')
                            ->where(['agent_list_id' => $v['id']])
                            ->delete();
                    }
                    //删除企业信息

                    $count = Db::name('agent_list')->where(['id' => $v['id']])->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


}