Institution.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. namespace app\admin\controller\institution;
  3. use app\admin\model\Admin;
  4. use app\common\library\Upload;
  5. use think\facade\Cache;
  6. use think\facade\Db;
  7. use think\db\exception\DataNotFoundException;
  8. use think\db\exception\ModelNotFoundException;
  9. use think\exception\DbException;
  10. use Throwable;
  11. use app\common\controller\Backend;
  12. /**
  13. * 机构管理
  14. */
  15. class Institution extends Backend
  16. {
  17. /**
  18. * Institution模型对象
  19. * @var object
  20. * @phpstan-var \app\admin\model\institution\Institution
  21. */
  22. protected object $model;
  23. protected array|string $preExcludeFields = ['id', 'update_time'];
  24. protected array $withJoinTable = ['parentInstitution'];
  25. protected string|array $quickSearchField = ['name'];
  26. protected array $noNeedPermission = ['getInstitutionTree','getInsList','getTypeList','makeEmpower'];
  27. protected array $noNeedLogin = [];
  28. public function initialize(): void
  29. {
  30. parent::initialize();
  31. $this->model = new \app\admin\model\institution\Institution();
  32. }
  33. /**
  34. * 查看
  35. * @throws Throwable
  36. */
  37. public function index(): void
  38. {
  39. // 如果是 select 则转发到 select 方法,若未重写该方法,其实还是继续执行 index
  40. if ($this->request->param('select')) {
  41. $this->select();
  42. }
  43. /**
  44. * 1. withJoin 不可使用 alias 方法设置表别名,别名将自动使用关联模型名称(小写下划线命名规则)
  45. * 2. 以下的别名设置了主表别名,同时便于拼接查询参数等
  46. * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
  47. */
  48. list($where, $alias, $limit, $order) = $this->queryBuilder();
  49. $res = $this->model
  50. ->withJoin($this->withJoinTable, $this->withJoinType)
  51. ->alias($alias)
  52. ->where($where)
  53. ->order($order)
  54. ->paginate($limit);
  55. $res->visible(['parentInstitution' => ['name']]);
  56. $list = $res->items();
  57. $list = (json_decode(json_encode($list), true));
  58. $arr = [];
  59. foreach ($list as $k=>$v) {
  60. foreach ($v as $kk => $vv) {
  61. $arr[$k][strtolower($kk)] = $vv;
  62. }
  63. }
  64. $this->success('', [
  65. 'list' => $arr,
  66. 'total' => $res->total(),
  67. 'remark' => get_route_remark(),
  68. ]);
  69. }
  70. /**
  71. * 若需重写查看、编辑、删除等方法,请复制 @throws \Exception
  72. * @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
  73. */
  74. public function import()
  75. {
  76. set_time_limit(0);
  77. // 获取文件
  78. // $file = $this->request->request('file');
  79. $file = $this->request->file('file');
  80. if (!$file) {
  81. $this->error('上传文件错误');
  82. }
  83. $attachment = '';
  84. try {
  85. $upload = new Upload($file);
  86. $attachment = $upload->upload(null, $this->auth->id);
  87. unset($attachment['create_time'], $attachment['quote']);
  88. } catch (Throwable $e) {
  89. $this->error($e->getMessage());
  90. }
  91. if (!is_file($_SERVER['DOCUMENT_ROOT'].$attachment['url'])) {
  92. $this->error(__('No results were found'));
  93. }
  94. $url = $_SERVER['DOCUMENT_ROOT'].$attachment['url'];
  95. $allInstitution = $this->model->cache('allIns',300)->column('id','institution_code');
  96. if (!(is_file($url))) {
  97. $this->error('文件获取失败');
  98. }
  99. // 读取内容
  100. $excel_data = read_excel($url);
  101. if (empty($excel_data)) {
  102. $this->error('请填写导入数据');
  103. }
  104. $data = [];
  105. foreach ($excel_data as $key=>$val) {
  106. foreach ($val as &$v) {
  107. $v = str_replace(' ', '', trim($v));
  108. $v = str_replace("\xC2\xA0", '', $v);
  109. }
  110. $parent = '';
  111. if(!empty($val[3]))
  112. {
  113. $parent = $allInstitution[$val[3]] ?? '';
  114. }
  115. if(empty($val[0]))
  116. {
  117. continue;
  118. }
  119. unset($v);
  120. $data[] = [
  121. 'name'=>$val[0], //机构名称
  122. 'institution_code'=>$val[1], //机构编码
  123. 'institution_type'=>$val[2], //机构类型
  124. 'parent_institution_id'=>$parent, //上级医院
  125. 'port_empower'=>md5($val[1].rand(100000,999999)), //接口授权ID
  126. 'area'=>$val[5], //互认范围
  127. ];
  128. }
  129. Cache::delete('institution_dashboard');
  130. Cache::delete('allIns');
  131. if(!empty($data))
  132. {
  133. $this->model->saveAll($data);
  134. }else{
  135. $this->error('导入失败,未读取到数据');
  136. }
  137. $this->success('导入成功');
  138. }
  139. /**
  140. * @throws DataNotFoundException
  141. * @throws DbException
  142. * @throws ModelNotFoundException
  143. * @throws \think\db\exception\DbException
  144. */
  145. public function getInstitutionTree(): bool|string
  146. {
  147. $id= $this->request->post('institution_id') ?? '';
  148. $name= $this->request->post('institution_name') ?? '';
  149. $ins = $this->model->select()->toArray();
  150. $institution = [];
  151. foreach ($ins as $k=>$v)
  152. {
  153. $institution[$v['PARENT_INSTITUTION_ID']][] = $v;
  154. }
  155. if(!empty($id))
  156. {
  157. $organization = $this->model->where('id',$id)->select()->toArray();
  158. }elseif(!empty($name)){
  159. $organization = $this->model->where('name',$name)->select()->toArray();
  160. }else{
  161. $organization = $this->model->where('parent_institution_id',0)->select()->toArray();
  162. }
  163. $data = $this->makeInsData($institution,$organization);
  164. $this->success('success',$data);
  165. }
  166. public function makeInsData($institution,$organization): array
  167. {
  168. $data = [];
  169. if($organization['NAME'] ?? '')
  170. {
  171. $data[] = ['label'=>$organization['NAME']];
  172. return $data;
  173. }
  174. foreach ($organization as $k=>$v)
  175. {
  176. if(!empty($institution[$v['ID']]))
  177. {
  178. $child = $this->makeInsData($institution,$institution[$v['ID']]);
  179. $data[] = [
  180. 'label'=>$v['NAME'],
  181. 'id'=>$v['ID'],
  182. 'children'=>$child
  183. ];
  184. }else{
  185. $data[] = [
  186. 'label'=>$v['NAME'],
  187. 'id'=>$v['ID'],
  188. 'children'=>[]
  189. ];
  190. }
  191. }
  192. return $data;
  193. }
  194. public function getInsList(): void
  195. {
  196. $res = $this->model->field(['id','name'])->select()->toArray();
  197. $this->success('', ['list' => $res]);
  198. }
  199. public function getTypeList(): void
  200. {
  201. $type= $this->request->post('type');
  202. if(empty($type))
  203. {
  204. $this->error('参数错误');
  205. }
  206. $res = Db::name('dict_common_data')->where('type',$type)->field(['id','name'])->select()->toArray();
  207. $this->success('', ['list' => $res]);
  208. }
  209. /**
  210. * 添加
  211. */
  212. public function add(): void
  213. {
  214. if ($this->request->isPost()) {
  215. $data = $this->request->post();
  216. if (!$data) {
  217. $this->error(__('Parameter %s can not be empty', ['']));
  218. }
  219. $data = $this->excludeFields($data);
  220. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  221. $data[$this->dataLimitField] = $this->auth->id;
  222. }
  223. $result = false;
  224. $this->model->startTrans();
  225. try {
  226. // 模型验证
  227. if ($this->modelValidate) {
  228. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  229. if (class_exists($validate)) {
  230. $validate = new $validate();
  231. if ($this->modelSceneValidate) $validate->scene('add');
  232. $validate->check($data);
  233. }
  234. }
  235. if(!empty($data['create_user_id']))
  236. {
  237. $data['create_user'] = Admin::where('id',$data['create_user_id'])->value('nickname');
  238. }
  239. $data['port_empower'] = md5($data['institution_code'].rand(100000,999999));
  240. $result = $this->model->save($data);
  241. $this->model->commit();
  242. Cache::delete('institution_dashboard');
  243. Cache::delete('allIns');
  244. } catch (Throwable $e) {
  245. $this->model->rollback();
  246. $this->error($e->getMessage());
  247. }
  248. if ($result !== false) {
  249. $this->success(__('Added successfully'));
  250. } else {
  251. $this->error(__('No rows were added'));
  252. }
  253. }
  254. $this->error(__('Parameter error'));
  255. }
  256. /**
  257. * 编辑
  258. * @throws Throwable
  259. */
  260. public function edit(): void
  261. {
  262. $pk = $this->model->getPk();
  263. $id = $this->request->param($pk);
  264. $arr = $this->model->find($id);
  265. $row = [];
  266. foreach ($arr as $k=>$v)
  267. {
  268. $row[strtolower($k)] = $v;
  269. }
  270. if (!$row) {
  271. $this->error(__('Record not found'));
  272. }
  273. $dataLimitAdminIds = $this->getDataLimitAdminIds();
  274. if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
  275. $this->error(__('You have no permission'));
  276. }
  277. if ($this->request->isPost()) {
  278. $data = $this->request->post();
  279. if (!$data) {
  280. $this->error(__('Parameter %s can not be empty', ['']));
  281. }
  282. $data = $this->excludeFields($data);
  283. $result = false;
  284. $this->model->startTrans();
  285. try {
  286. // 模型验证
  287. if ($this->modelValidate) {
  288. $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  289. if (class_exists($validate)) {
  290. $validate = new $validate();
  291. if ($this->modelSceneValidate) $validate->scene('edit');
  292. $data[$pk] = $row[$pk];
  293. $validate->check($data);
  294. }
  295. }
  296. $this->checkChild($data['parent_institution_id'],$id);
  297. if(!empty($data['create_user_id']))
  298. {
  299. $data['create_user'] = Admin::where('id',$data['create_user_id'])->value('nickname');
  300. }
  301. if($row['port_empower'] != $data['port_empower'])
  302. {
  303. $info = Cache::get($row['port_empower']);
  304. if(!empty($info))
  305. {
  306. foreach ($info as $k=>$v)
  307. {
  308. Cache::delete($v[$row['port_empower']]);
  309. }
  310. }
  311. Cache::delete($row['port_empower']);
  312. }
  313. $result = $row->save($data);
  314. $this->model->commit();
  315. Cache::delete('institution_dashboard');
  316. Cache::delete('allIns');
  317. } catch (Throwable $e) {
  318. $this->model->rollback();
  319. if(empty($e->getMessage()))
  320. {
  321. $this->error($this->auth->getError());
  322. }else{
  323. $this->error($e->getMessage());
  324. }
  325. }
  326. if ($result !== false) {
  327. $this->success(__('Update successful'));
  328. } else {
  329. $this->error(__('No rows updated'));
  330. }
  331. }
  332. $this->success('', [
  333. 'row' => $row
  334. ]);
  335. }
  336. public function checkChild($parent,$id)
  337. {
  338. if($parent == $id)
  339. {
  340. $this->auth->setError('当前医院的上级医院不能为自己');
  341. $this->error('当前医院的上级医院不能为自己');
  342. }
  343. $child = $this->model->where('parent_institution_id',$id)->find();
  344. if(!empty($child))
  345. {
  346. if($child['id'] == $parent)
  347. {
  348. $this->auth->setError('当前医院的上级医院不能为自己');
  349. $this->error('当前医院的上级医院不能为自己的下级');
  350. }else{
  351. $this->checkChild($parent,$child['id']);
  352. }
  353. }
  354. }
  355. public function makeEmpower(): string
  356. {
  357. $code = $this->request->post('code');
  358. $this->success('success',md5($code.rand(100000,999999)));
  359. }
  360. }