<?php

namespace app\admin\controller\nhc;

use app\admin\common\AdminController;
use app\common\api\DictApi;
use app\common\api\UploadApi;
use think\facade\Db;

/**
 * 医院管理
 */
class Hospital extends AdminController {

    public function index() {
        $where = [];
        $where[] = ["status", "<>", 3];
        $medicalCommunities = Db::table("nhc_medical_community")->where($where)->order("num asc")->select()->toArray();
        return view("", ["medicalCommunities" => $medicalCommunities]);
    }

    public function list() {
        $order = trim($this->request->param("order")) ?: "desc";
        //$offset = trim($this->request->param("offset")) ?: 0;
        //$limit = trim($this->request->param("limit")) ?: 10;
        $name = trim($this->request->param("name"));
        $communityId = trim($this->request->param("communityId"));

        $where = [];
        $where[] = ["h.status", "<>", 3];
        if ($name) {
            $where[] = ["h.name", "like", "%" . $name . "%"];
        }
        if ($communityId) {
            $where[] = ["h.communityId", "=", $communityId];
        }

        //$count = Db::table("nhc_hospital")->alias("h")->leftJoin("nhc_medical_community mc", "mc.id=h.communityId")->where($where)->count();
        $rows = Db::table("nhc_hospital")->alias("h")->leftJoin("nhc_medical_community mc", "mc.id=h.communityId")
                        ->field("h.*,mc.name as medicalCommunityName")
                        ->where($where)->order("mc.num asc,h.num asc,h.createTime " . $order)
                        ->select()->toArray();

        return $rows;
    }

    public function add() {
        $where = [];
        $where[] = ["status", "<>", 3];
        $medicalCommunities = Db::table("nhc_medical_community")->where($where)->order("num asc")->select()->toArray();
        return view("edit", ["medicalCommunities" => $medicalCommunities]);
    }

    public function edit() {
        $id = \StrUtil::getRequestDecodeParam($this->request, 'id');
        $info = Db::table("nhc_hospital")->where("id", $id)->find();
        $where = [];
        $where[] = ["status", "<>", 3];
        $medicalCommunities = Db::table("nhc_medical_community")->where($where)->order("num asc")->select()->toArray();
        return view("edit", ["row" => $info, "medicalCommunities" => $medicalCommunities]);
    }

    public function upsert() {
        $response_obj = new \StdClass();
        $response_obj->code = 500;
        $id = \StrUtil::getRequestDecodeParam($this->request, 'id');
        $where = [];
        if ($id) {
            $info = Db::table("nhc_hospital")->where("id", $id)->find();
            if (!$info) {
                $response_obj->msg = '找不到记录';
                return \StrUtil::back($response_obj, 'HospitalInfo.callBack');
            }
            $where[] = ["id", "<>", $id];
        }

        $name = trim($this->request['name']);
        if (\StrUtil::isEmpOrNull($name)) {
            $response_obj->msg = '医院名称不能为空';
            return \StrUtil::back($response_obj, 'HospitalInfo.callBack');
        }
        $where[] = ["name", "=", $name];
        $repeat = Db::table("nhc_hospital")->where($where)->find();

        if ($repeat) {
            $response_obj->msg = '医院名称已经被使用';
            return \StrUtil::back($response_obj, 'HospitalInfo.callBack');
        }
        $communityId = trim($this->request['communityId']);
        if (!$communityId) {
            $response_obj->msg = '请选择医院所属医共体';
            return \StrUtil::back($response_obj, 'HospitalInfo.callBack');
        }
        $isGeneral = trim($this->request['isGeneral']);
        if (!$isGeneral) {
            $response_obj->msg = '请选择是否总院（当前医共体）';
            return \StrUtil::back($response_obj, 'HospitalInfo.callBack');
        }

        $num = trim($this->request['num']);
        if (\StrUtil::isNotEmpAndNull($num) && !is_numeric($num)) {
            $response_obj->msg = '序号只能是数字';
            return \StrUtil::back($response_obj, 'HospitalInfo.callBack');
        }
        $status = trim($this->request['status']);
        if (\StrUtil::isEmpOrNull($status)) {
            $response_obj->msg = '启用状态不能为空';
            return \StrUtil::back($response_obj, 'HospitalInfo.callBack');
        }
        Db::startTrans();
        try {
            if ($isGeneral == 1) {
                //各医共体下最多仅有一家总院，检查是否有其它设置，如有，变更为2，当前设为1
                $where = [];
                $where[] = ["communityId", "=", $communityId];
                $where[] = ["isGeneral", "=", 1];
                if ($id) {
                    $where[] = ["id", "<>", $id];
                }
                $updOther["isGeneral"] = 2;
                $updOther["updateTime"] = date("Y-m-d H:i:s");
                $updOther["updateUser"] = $this->user["uid"];
                Db::table("nhc_hospital")->where($where)->save($updOther);
            }

            $data["name"] = $name;
            $data["communityId"] = $communityId;
            $data["isGeneral"] = $isGeneral;
            $data["status"] = $status;
            $data["num"] = $num;
            $data["description"] = \StrUtil::getRequestDecodeParam($this->request, "description");
            if ($id) {
                $data["id"] = $id;
                $data["updateTime"] = date("Y-m-d H:i:s");
                $data["updateUser"] = $this->user['uid'];
                Db::table("nhc_hospital")->save($data);
            } else {
                $data["createTime"] = date("Y-m-d H:i:s");
                $data["createUser"] = $this->user['uid'];
                Db::table("nhc_hospital")->insert($data);
            }
            Db::commit();
            $response_obj->code = 200;
            $response_obj->msg = '修改成功';
            return \StrUtil::back($response_obj, "HospitalInfo.callBack");
        } catch (\Exception $e) {
            Db::rollback();
            $response_obj->msg = $e->getMessage();
            return \StrUtil::back($response_obj, "HospitalInfo.callBack");
        }
    }

    public function setGeneral() {
        $id = \StrUtil::getRequestDecodeParam($this->request, 'id');
        if (\StrUtil::isEmpOrNull($id)) {
            return json(['code' => 500, 'msg' => '缺少参数']);
        }

        $info = Db::table("nhc_hospital")->where("id", $id)->find();

        if (!$info) {
            return json(['code' => 500, 'msg' => '没有查询到对应医院信息']);
        }
        $communityId = $info["communityId"];
        Db::startTrans();
        try {
            //各医共体下最多仅有一家总院，检查是否有其它设置，如有，变更为2，当前设为1
            $where = [];
            $where[] = ["communityId", "=", $communityId];
            $where[] = ["isGeneral", "=", 1];
            $where[] = ["id", "<>", $id];
            $updOther["isGeneral"] = 2;
            $updOther["updateTime"] = date("Y-m-d H:i:s");
            $updOther["updateUser"] = $this->user["uid"];
            Db::table("nhc_hospital")->where($where)->save($updOther);

            $updOther["id"] = $id;
            $updOther["isGeneral"] = 1;
            Db::table("nhc_hospital")->save($updOther);
            Db::commit();
            return json(['code' => 200, 'msg' => "设置成功"]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    public function delete() {
        $id = \StrUtil::getRequestDecodeParam($this->request, 'id');
        if (\StrUtil::isEmpOrNull($id)) {
            return json(['code' => 500, 'msg' => '缺少参数']);
        }
        $data["id"] = $id;
        $data["status"] = 3;
        $data["updateTime"] = date("Y-m-d H:i:s");
        $data["updateUser"] = $this->user["uid"];
        try {
            Db::table("nhc_hospital")->save($data);
            return json(['code' => 200, 'msg' => "删除成功"]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

}
