1, 'YYTG' => 2, 'YYDS' => 3 ]; public function _initialize() { parent::_initialize(); $this->model = new \app\admin\model\institution\Institution; } /** * 列表 * @return string|JsonAlias * @throws Exception * @author matielong */ public function index() { // 设置过滤方法 $this->request->filter(['strip_tags']); if ($this->request->isAjax()) { //如果发送的来源是Selectpage,则转发到Selectpage if ($this->request->request('keyField')) { return $this->selectpage(); } list($where, $sort, $order, $offset, $limit) = $this->buildparams($this->searchFields,true); // 只查看自己机构以及下级机构的信息 $childInsIds = $this->auth->getMyInsId(); if($childInsIds == false){ $more = false; } else { $more = ['institution.id' => ['in', $childInsIds]]; } // 关联 $join = [['fa_admin', 'institution.agent_id = fa_admin.id', 'LEFT']]; $field = ['institution.*','fa_admin.nickname as agent_name']; try{ $total = $this->model ->join($join) ->where($more) ->where($where) ->count(); $list = $this->model ->join($join) ->where($more) ->where($where) ->order($sort, $order) ->limit($offset, $limit) ->field($field) ->select(); foreach ($list as $k=>$v) { if(is_object($v)) { foreach ($v->toArray() as $k1=>$v1) { $list[$k][strtolower($k1)] = $v1; } } } } catch ( Exception $e){ $this->error($e->getMessage()); } $result = array("total" => $total, "rows" => $list); 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); } if(empty($params['install_time'])){ $params['install_time'] = null; } // 机构ID是否存在 $is_exist = $this->model->where('id', $params['id'])->value('id'); if($is_exist){ $this->error('机构ID已存在!'); } // 去掉顶级节点 0 // $params['parent_institution'] = $params['parent_institution'] == '0' ? '0' : ''; // 省市区 $area = explode('/',$params['area']); $params['ris_province'] = $area[0] ?? ''; $params['ris_city'] = $area[1] ?? ''; $params['ris_district'] = $area[2] ?? ''; foreach ($params['institution_condition'] as $k=>$v) { if($v == '-1') { unset($params['institution_condition'][$k]); } } $filter = []; if(!empty($params['exam_datetime'])) { $filter['exam_datetime'] = $params['exam_datetime']; } unset($params['exam_datetime']); if(!empty($params['exam_class'])) { $filter['exam_class'] = $params['exam_class']; } unset($params['exam_class']); $params['filter'] = json_encode($filter); $params['institution_condition'] = implode(',',$params['institution_condition']); $params['custom_field'] = implode(',',$params['custom_field']); unset($params['area']); if($params['sale_id']){ $names = model('Admin') ->whereIn('id',explode(',', $params['sale_id'])) ->column('nickname'); $params['sale_name'] = implode(',', $names); } $arr = []; foreach ($params as $k=>$v){ $arr[strtoupper($k)] = $v; } $result = $this->model->allowField(true)->save($arr); // 添加机构账号对应关系 $uid = $this->auth->getUserInfo()['id']; $institution_id = $params['id']; $insert = [ [ 'uid' => $uid , 'institution_id' => $institution_id ] ]; if($params['sale_id']){ foreach (explode(',', $params['sale_id']) as $sale_id){ $insert[] = [ 'uid' => $sale_id , 'institution_id' => $institution_id ]; } } model('AuthInstitutionAccess')->insertAll($insert); SysLog::recode("institution", "C", $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) { $this->success(); } else { $this->error(__('No rows were inserted')); } } $this->error(__('Parameter %s can not be empty', '')); } $this->view->conditionDict = $this->conditionDict(); $this->view->customField = Config::get('ins_custom_field'); 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 ($this->request->isPost()) { $params = $this->request->post("row/a"); if ($params) { $params = $this->preExcludeFields($params); $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); } // 去掉顶级节点 0 // $params['parent_institution'] = $params['parent_institution'] == '0' ? '' : $params['parent_institution']; // 省市区 if(empty($params['install_time'])){ $params['install_time'] = null; } $area = explode('/',$params['area']); $params['ris_province'] = $area[0] ?? ''; $params['ris_city'] = $area[1] ?? ''; $params['ris_district'] = $area[2] ?? ''; foreach ($params['institution_condition'] as $k=>$v) { if($v == '-1') { unset($params['institution_condition'][$k]); } } $filter = []; if(!empty($params['exam_datetime'])) { $filter['exam_datetime'] = $params['exam_datetime']; } unset($params['exam_datetime']); if(!empty($params['exam_class'])) { $filter['exam_class'] = $params['exam_class']; } unset($params['exam_class']); $params['filter'] = json_encode($filter); $params['institution_condition'] = implode(',',$params['institution_condition']); $params['custom_field'] = implode(',',$params['custom_field']); unset($params['area']); if($params['sale_id']){ $params['sale_name'] = model('Admin')->where('id',$params['sale_id'])->value('nickname'); $res = $this->updateSaleInsId($row['sale_id'], $params['sale_id'], $params['id']); if($res === false){ Db::rollback(); $this->error('更新机构绑定的销售人员失败'); } } $result = $this->model->where('id',$ids)->update($params); $params['old_id'] = $ids; SysLog::recode("institution", "U", $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) { $this->success(); } else { $this->error(__('No rows were updated')); } } $this->error(__('Parameter %s can not be empty', '')); } // $row['parent_institution'] = empty($row['parent_institution']) ? 0 : $row['parent_institution']; $row['area'] = $row['ris_province'] . '/' . $row['ris_city'] . '/' . $row['ris_district']; if($row['institution_condition'] === '') { $row['institution_condition'] = ['-1']; }else{ $row['institution_condition'] = explode(',',$row['institution_condition']); } if($row['custom_field'] === '') { $row['custom_field'] = []; }else{ $row['custom_field'] = explode(',',$row['custom_field']); } $filter_arr = json_decode($row['filter'],true); $row['exam_class'] = $filter_arr['exam_class'] ?? ''; $row['exam_datetime'] = $filter_arr['exam_datetime'] ?? ''; $this->view->assign("row", $row); $this->view->customField = Config::get('ins_custom_field'); $this->view->conditionDict = $this->conditionDict(); return $this->view->fetch(); } /** * 删除 */ public function del($ids = "") { if ($ids) { $pk = $this->model->getPk(); $adminIds = $this->getDataLimitAdminIds(); if (is_array($adminIds)) { $this->model->where($this->dataLimitField, 'in', $adminIds); } $list = $this->model->where($pk, 'in', $ids)->select(); $count = 0; Db::startTrans(); try { foreach ($list as $k => $v) { $count += $v->delete(); model('AuthInstitutionAccess')->where('institution_id',$v['id'])->delete(); } SysLog::recode("institution", "D", $ids); 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')); } /** * 等级下拉 * @author matielong */ public function levelSelectList() { try{ $list = $this->model ->group('institution_level') ->column('institution_level'); } catch ( DbException $exception){ $this->error($exception->getMessage()); } $data = []; foreach ($list as $v){ if(empty($v)) continue; $data[] = ['id'=>$v,'name'=>$v]; } $data = ['searchlist' => $data]; $this->success('success', null, $data); } /** * 机构搜索列表 * @return JsonAlias * @author matielong */ public function institutionSelectList() { try{ // 当前可见机构 if($this->auth->isSuperAdmin()){ $more = false; } else { $admin = $this->auth->getUserInfo(); $childInsIds = $admin['institution']['my_institution']; $more = ['id' => ['in', $childInsIds]]; } // 获取列表 $total = $this->model ->where($more) ->count(); $list = $this->model ->where($more) ->field('id,name,parent_institution') ->select(); foreach ($list as $key => &$val){ $val['index'] = $key; } // 格式化 return json(array("total" => $total, "rows" => $list)); } catch ( Exception $exception){ $this->error($exception->getMessage()); } } /** * 代理商下拉列表 * @return JsonAlias * @author matielong */ public function agentSelectList() { try { $uid = model('AuthGroupAccess') ->where('group_id', $this->agentGroupId) ->column('uid'); // 查询 $where = [ 'id' => ['in', $uid], 'status' => '1' ]; $total = model('Admin') ->where($where) ->count(); $list = model('Admin') ->where($where) ->field('id,username as name') ->select(); return json(array("total" => $total, "rows" => $list)); } catch (Exception $exception) { $this->error($exception->getMessage()); } } /** * 代表销售下拉列表 * @return JsonAlias * @author matielong */ public function saleSelectList() { try { $uid = model('AuthGroupAccess') ->whereIn('group_id', $this->saleGroupIds) ->column('uid'); // 查询 $where = [ 'id' => ['in', $uid], 'status' => '1' ]; $total = model('Admin') ->where($where) ->count(); $list = model('Admin') ->where($where) ->field('id,nickname as name') ->select(); return json(array("total" => $total, "rows" => $list)); } catch (Exception $exception) { $this->error($exception->getMessage()); } } /** * 科室下拉选择 * @param $institution_id * @return JsonAlias * @author matielong */ public function departSelectList($institution_id) { try{ $total = model('Depart','model\institution') ->where('institution_id',$institution_id) ->count(); $list = model('Depart','model\institution') ->where('institution_id',$institution_id) ->field('id,department_name as name') ->order('order_num') ->select(); foreach ($list as $key => &$val){ $val['index'] = $key; } return json(array("total" => $total, "rows" => $list)); } catch ( Exception $exception){ $this->error($exception->getMessage()); } } // 当前医院医生下拉 public function doctorSelectList($institution_id) { try{ $total = DoctorModel::where('institution_id',$institution_id) ->count(); $list = DoctorModel::where('institution_id',$institution_id) ->field('id,realname as name') ->order('createdAt') ->select(); return json(array("total" => $total, "rows" => $list)); } catch ( Exception $exception){ $this->error($exception->getMessage()); } } /** * 上下级机构选择 * @param $level * @return bool|JsonAlias */ public function institutionContactList($level) { try{ // 当前可见机构 if($this->auth->isSuperAdmin()){ $more = false; } else { $admin = $this->auth->getUserInfo(); $childInsIds = $admin['institution']['child_institution']; $more = ['id' => ['in', $childInsIds]]; } // 判断上级下级 switch ($level){ case 'lower': // $where = ['super_level' => 0]; $where = false; break; case 'super': $where = ['super_level' => 1]; $more = false; break; default: return false; } // 获取列表 $total = $this->model ->where($more) ->where($where) ->count(); $list = $this->model ->where($more) ->where($where) ->field('id,name,parent_institution') ->select(); foreach ($list as $key => &$val){ $val['index'] = $key; } // 格式化 return json(array("total" => $total, "rows" => $list)); } catch ( Exception $exception){ $this->error($exception->getMessage()); } } /** * 获取远程医生 * @param $institution_id * @return false|\PDOStatement|string|\think\Collection */ public function initRemoteDoctor($institution_id) { try { $where = [ 'institution_id' => $institution_id, 'status' => '1', ]; $remote_doctor_id = '3002'; $total = model('DoctorModel','model\doctors') ->where($where) ->whereLike('doctor_role',"%$remote_doctor_id%") ->count(); $list = model('DoctorModel','model\doctors') ->where($where) ->whereLike('doctor_role',"%$remote_doctor_id%") ->field('id,realname as name') ->select(); $ids = implode(',', array_column($list, 'id')); return json(array("total" => $total, "rows" => $list, "ids" => $ids)); } catch ( Exception $exception){ $this->error($exception->getMessage()); } } /** * 更新收费模式 * @param $ids * @return string * @throws DbException * @throws Exception */ public function setChargeMode($ids) { $ins = $this->model->get($ids); if($this->request->isPost()){ $info = $this->request->post(); if(!in_array($info['charge_mode'], $this->charge_mode)){ $this->error('收费模式传值错误'); } if($info['film_price'] < 0){ $this->error('金额传值错误'); } $res = $this->model->where('id', $ids)->update([ 'charge_mode' => $info['charge_mode'], 'film_price' => $info['film_price'] * 100, 'supplement_pay' => $info['supplement_pay'] ]); if(!$res){ $this->error('更新失败'); } $this->success(); return true; } $this->view->ins = $ins; return $this->view->fetch('charge_mode'); } /** * 更新机构绑定的销售人员 * @param $old_sale_id * @param $new_sale_id * @param $ins_id * @return bool|int|string */ protected function updateSaleInsId($old_sale_id, $new_sale_id, $ins_id) { if($old_sale_id == $new_sale_id){ return true; } $res = model('AuthInstitutionAccess') ->whereIn('uid', explode(',', $old_sale_id)) ->where('institution_id', $ins_id) ->delete(); if(!$res){ return false; } $insert = []; foreach (explode(',', $new_sale_id) as $sale_id){ $insert[] = [ 'uid' => $sale_id, 'institution_id' => $ins_id, ]; } $res = model('AuthInstitutionAccess')->insertAll($insert); return $res; } /** * 获取经纬度 */ public function getLngLat() { $name = $this->request->post('name'); $ak = '6e7njING4jPNrRGjG2RibUcv37oWGzPi'; $output = 'json'; $api = Config::get('baidu_url'); $url = $api."/geocoding/v3/?address=$name&output=$output&ak=$ak"; $data = Http::get($url); if(!empty($data)){ ini_set('precision',-1); $po = json_decode($data, true); $this->success('ok',null,[ 'lng' => $po['result']['location']['lng'], 'lat' => $po['result']['location']['lat'] ]); } $this->error(); } protected function conditionDict() { return [ '-1' => '未知' , '0' => '手机' , '1' => '身份证' , '2' => '病历号' , '3' => '检查号' , '4' => '住院号' , '5' => '门诊号' , '6' => '病人id' , ]; } public function topUp($ids) { $ins = $this->model->get($ids); if(!$ins){ return false; } if($this->request->isPost()){ $money = (float) $this->request->post('money'); if(!is_float($money)){ $this->error('金额必须为一个数字'); } if($money === 0){ $this->error('金额不可以为0'); } if($money < 0 && $ins['current_money'] < abs($money * 100)) { $this->error('余额不足,无法扣除'); } $acc = strlen(explode('.', $money)[1] ?? ''); if($acc > 2){ $this->error('小数点后最多2位'); } $admin = Session::get('admin'); $insert = [ 'institution_id' => $ins['id'] , 'institution_name' => $ins['name'] , 'old_amount' => $ins['current_money'] , 'amount' => $money * 100 , 'user_id' => $admin['id'] , 'user_name' => $admin['nickname'] , 'created_time' => date('Y-m-d H:i:s') ]; $new_amount = $ins['current_money'] + ($money * 100); Db::transaction(function () use ($ids, $new_amount, $insert){ Db::table('ins_top_up_record')->insert($insert); $this->model->where('id', $ids) ->update([ 'current_money' => $new_amount ]); }); $this->success(); } $record = Db::table('ins_top_up_record') ->order('id desc') ->where('institution_id', $ids) ->select(); $this->view->record = $record; $this->view->ins = $ins; $this->view->money = $ins['current_money'] / 100; return $this->view->fetch('top_up'); } //已废弃接口 public function setDict($ids) { $ins = $this->model->get($ids); $model = model(InsDockingField::class); $dict = $model ->where('institution_id', $ids) ->column('field, name'); $default = [ '0' => ['field' => 'phone', 'name' => '手机号'], '1' => ['field' => 'card_num', 'name' => '身份证'], '2' => ['field' => 'patient_num', 'name' => '病历号'], '3' => ['field' => 'accession_num', 'name' => '检查号'], '4' => ['field' => 'hopitalized_no', 'name' => '住院号'], '5' => ['field' => 'out_patient', 'name' => '门诊号'], ]; if($this->request->isPost()){ $row = $this->request->post('row/a'); Db::startTrans(); foreach ($row as $key => $val){ $where = [ 'institution_id' => $ids, 'field' => $key ]; $exist = $model->where($where)->find(); if ($exist) { if(empty($val)){ $res = $exist->delete(); } else { $res = $exist->where($where)->update(['name' => $val]); } } else { if(empty($val)){ continue; } $res = $model->where($where)->insert([ 'institution_id' => $ids, 'name' => $val, 'field' => $key, ]); } if($res === false){ Db::rollback(); $this->error('操作失败'); } } Db::commit(); $this->success(); } $this->view->ins = $ins; $this->view->assign([ 'ins' => $ins, 'dict' => $dict, 'default' => $default, ]); return $this->view->fetch('set_dict'); } public function setMonitoring($ids) { $ins = $this->model->get($ids); $user = $this->auth->getUserInfo(); $mon_model = model(InsMonitoring::class); $mon = $mon_model->where('ins_id',$ids)->find(); if($this->request->isPost()){ $info = $this->request->post(); $save = [ 'ins_id' => $info['ins_id'], 'ins_name' => $ins['name'], 'open' => $info['open'], 'admin_id' => $user['id'], 'safe_time' => json_encode($info['safe_time']), 'warning_time' => $info['warning_time'], 'notice_type' => $info['notice_type'] ]; if ($mon) { $res = $mon_model->where('id', $mon['id'])->update($save); } else { $res = $mon_model->insert($save); } if(!$res){ $this->error(); } $this->success(); } $this->view->ins = $ins; $this->view->user = $user; $this->view->mon = $mon; $this->view->status = $mon; $this->view->safe_time = $mon ? json_decode($mon['safe_time'], true) : []; return $this->view->fetch('set_monitoring'); } public function checkMonitoring($token = '') { if(!$token){ return 0; } if($token !== '9hfghn0fsdfa099eq31235n23nakdksad*^'){ return 0; } $time = time(); $ins_data = model(InsMonitoring::class) ->where('open', 1) ->select(); foreach ($ins_data as $val){ $warning_second = $val['warning_time'] * 60; if(!$warning_second){ continue; } // 安全区间判断 $safe_range = json_decode($val['safe_time'], true); $safe = false; $time_arr = []; foreach ($safe_range as $range){ if($range[0] && $range[1]){ $start = strtotime($range[0]); $end = strtotime($range[1]); $tom_start = $start + (3600 * 24); $tom_end = $end + (3600 * 24); $time_arr[] = $start; $time_arr[] = $end; $time_arr[] = $tom_start; $time_arr[] = $tom_end; if(($time > $start && $time < $end) || ($time < $start && $time > $end) || ($time > $tom_start && $time < $tom_end) || ($time < $tom_start && $time > $tom_end)){ $safe = true; continue; } } } if($safe){ continue; } $last_upload_time = InstitutionService::getLastUploadTime($val['ins_id']); if(!$last_upload_time){ continue; } if($time - $last_upload_time > $warning_second){ // 判断最(最后上传时间 ~ 当前预警时时间)区间是否存在安全时间段 $closest = 0; foreach ($time_arr as $sa_time){ if($last_upload_time <= $sa_time && $sa_time <= $time){ $closest = $sa_time; } } if($closest === 0 || $time - $closest >= $warning_second){ // 达到预警条件 $res = InstitutionService::saveException($val['ins_id'], $val['ins_name'], $last_upload_time, $time); if($res && InstitutionService::$push === true){ $datetime = date('Y-m-d H:i:s', $last_upload_time); DingTalk::instance()->sendInstitutionNotice($val['ins_name'], $datetime, []); } } } } return 1; } public function filterList() { $data = [ ['id'=>'exam_datetime','name'=>'检查时间'], ['id'=>'exam_class','name'=>'检查类型'] ]; return json(array("total" => 2, "rows" => $data)); } }