<?php

namespace app\enterprise\controller;

use app\enterprise\common\EnterpriseController;
use app\common\state\CommonConst;
use app\common\api\EnterpriseApi;
use app\common\model\Enterprise;
use app\common\api\Nhc;
use app\common\model\TalentChecklog;
use app\common\model\MessageRecord;
use app\common\api\TalentState;
use app\common\api\ChuanglanSmsApi;

/**
 * Description of Hospital
 *
 * @author sgq
 */
class Hospital extends EnterpriseController {

    //put your code here
    public function list() {
        return view("");
    }

    public function getList() {
        $request = $this->request;
        $ep = EnterpriseApi::getOne($this->user["uid"]);
        if ($ep["isGeneral"] == 1) {
            EnterpriseApi::getList($request);
            $where = [];
            $where[] = ["type", "=", CommonConst::ENTERPRISE_WJ];
            $where[] = ["delete", "=", 0];
            $where[] = ["isGeneral", "=", 2];
            $where[] = ["medicalCommunityId", "=", $ep["medicalCommunityId"]];
            $where[] = ["step", "=", 0];


            $offset = trim($request->param("offset")) ?: 0;
            $limit = trim($request->param("limit")) ?: 10;

            $name = urldecode(trim($request->param("name")));
            $idCard = urldecode(trim($request->param("idCard")));
            $legal = urldecode(trim($request->param("legal")));
            $ephone = urldecode(trim($request->param("ephone")));
            $agentName = urldecode(trim($request->param("agentName")));
            $agentPhone = urldecode(trim($request->param("agentPhone")));
            $checkState = urldecode(trim($request->param("checkState")));

            if ($name) {
                $where[] = ["name", "like", "%{$name}%"];
            }
            if ($idCard) {
                $where[] = ["idCard", "like", "%{$idCard}%"];
            }
            if ($legal) {
                $where[] = ["legal", "like", "%{$legal}%"];
            }
            if ($ephone) {
                $where[] = ["ephone", "like", "%{$ephone}%"];
            }
            if ($agentName) {
                $where[] = ["agentName", "like", "%{$agentName}%"];
            }
            if ($agentPhone) {
                $where[] = ["agentPhone", "like", "%{$agentPhone}%"];
            }
            if ($checkState) {
                $where[] = ["checkState", "=", "{$checkState}"];
            }
            $count = Enterprise::where($where)->count();

            $medicalCommunityList = Nhc::getMedicalCommunityMap();
            $list = Enterprise::where($where)->limit($offset, $limit)->order("createTime", 'desc')->select()->toArray();

            foreach ($list as $k => &$v) {
                unset($v['password']);
                $v['medicalCommunityName'] = $v['medicalCommunityId'] ? $medicalCommunityList[$v['medicalCommunityId']] : "";
            }
            return ["total" => $count, "rows" => $list];
        }
    }

    public function detail() {
        $id = $this->request["id"];
        $ep = EnterpriseApi::getOne($id);
        return view("", ["ep" => $ep]);
    }

    public function examine() {
        $id = $this->request["id"];
        $ep = EnterpriseApi::getOne($id);
        $lastLog = \app\common\api\TalentLogApi::getLastLog($id, 10);
        if ($lastLog["active"] == 0) {
            $ep["checkState"] = $lastLog["state"];
            $ep["checkMsg"] = $lastLog["description"];
        }
        if (!$ep) {
            return "无此企业";
        }
        $fieldsAndFiles = $this->getFieldAndFilesBySpecialAndType($ep->special, $ep->type);
        $fields = $fieldsAndFiles["fields"];
        $files = $fieldsAndFiles["files"];

        $modify_fields = [];
        $modify_files = [];
        $_modify_fields = explode(",", $ep["modify_fields"]);
        foreach ($fields as $key => $value) {
            $checked = in_array($key, $_modify_fields);
            $modify_fields[$key] = ["field" => $key, "name" => $value, "checked" => $checked];
        }
        $_modify_files = explode(",", $ep["modify_files"]);
        foreach ($files as $key => $value) {
            $checked = in_array($key, $_modify_files);
            $modify_files[$key] = ["field" => $key, "name" => $value, "checked" => $checked];
        }
        return view("", ['ep' => $ep, 'checkUser' => session('user')['name'], 'fields' => $modify_fields, "files" => $modify_files]);
    }

    public function doExamine() {
        $id = trim($this->request['id']);
        $doSubmit = $this->request["submit"] == 1 ? true : false;
        if (!$id) {
            return json(["msg" => 'ID不能为空!']);
        }
        $ep = EnterpriseApi::getOne($id);
        if (!$ep) {
            return json(["msg" => '无此企业!']);
        }

        $oriCheckState = $ep["checkState"];
        if ($ep["step"] > 0 || $ep["isGeneral"] != 2) {
            return json(["msg" => "不在审核范围内"]);
        }
        if (!in_array($ep["checkState"], [1, 2, 4, 5]))
            return json(["msg" => "不在审核范围内"]);
        $checkState = $this->request['checkState'];
        if ($checkState == null || ($checkState != 5 && $checkState != 6)) {
            return json(["msg" => '请选择审核状态!']);
        }
        $checkMsg = $this->request['checkMsg'];
        $fields = $this->request['fields'];
        $files = $this->request['files'];
        if ($checkState == 5 && $ep["type"] == CommonConst::ENTERPRISE_WJ) {
            if (\StrUtil::isEmpOrNull($checkMsg)) {
                return json(["msg" => '请填写审核意见!']);
            }
            if (strlen($checkMsg) > 1000) {
                return json(["msg" => '审核意见最多1000个字符!']);
            }
            if (!$fields && !$files) {
                return json(["msg" => '请选择驳回修改的字段或者附件!']);
            }
        }
        try {
            $lastLog = \app\common\api\TalentLogApi::getLastLog($id, 10);
            $companyName = session('user')["companyName"] ?: session('user')["rolename"];
            if ($checkState == 6) {
                $fields = null;
                $files = null;
            }
            $newCheckState = $checkState;
            if ($doSubmit) {
                $checkData = [
                    'id' => $id,
                    'checkState' => $newCheckState,
                    'checkMsg' => $checkMsg,
                    'modify_fields' => $fields ? implode(",", $fields) : null,
                    'modify_files' => $files ? implode(",", $files) : null,
                    'checkUser' => session('user')['name'],
                    'updateUser' => session('user')['uid'],
                    'updateTime' => date("Y-m-d H:i:s")
                ];
                if ($ep["type"] == CommonConst::ENTERPRISE_WJ) {
                    if ($newCheckState == 5) {
                        $checkData["step"] = 0;
                    } else {
                        $checkData["step"] = 1;
                    }
                }

                $res = EnterpriseApi::updateById($checkData);

                //短信入库数据
                $record_data = [
                    'id' => getStringId(),
                    'bizId' => getStringId(),
                    'userId' => $id,
                    'type' => 2,
                    'smsType' => 2,
                    'name' => $ep['name'],
                    'phone' => $ep['agentPhone'],
                    'params' => '机构注册信息',
                    'state' => 1,
                    'sendingDate' => date("Y-m-d H:i:s", time()),
                    'createTime' => date("Y-m-d H:i:s", time())
                ];

                if ($checkState == 5) {
                    $record_data['templateCode'] = "【晋江市人才服务平台】您好！您提交的晋江市现代产业体系人才机构注册信息因信息填写错误或上传不完整已被退回，请及时登录“晋江市人才综合服务申报平台”根据审核意见修改并重新提交。退订回复TD。";
                }

                if ($checkState == 5) {
                    $smsapi = new ChuanglanSmsApi();

                    $result = $smsapi->sendSMS($ep['agentPhone'], $record_data['templateCode']);

                    MessageRecord::create($record_data);
                }
                if ($lastLog["active"] === 0) {
                    TalentChecklog::update([
                        'id' => $lastLog["id"],
                        'active' => 1,
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => TalentState::stateEnum($newCheckState),
                        'description' => $checkMsg,
                        'updateTime' => date("Y-m-d H:i:s", time()),
                        'updateUser' => session('user')['name'] . "({$companyName})"
                    ]);
                } else {
                    TalentChecklog::create([
                        'id' => getStringId(),
                        'mainId' => $id,
                        'type' => 10,
                        'typeFileId' => null,
                        'active' => 1,
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => TalentState::stateEnum($newCheckState),
                        'description' => $checkMsg,
                        'createTime' => date("Y-m-d H:i:s", time()),
                        'createUser' => session('user')['name'] . "({$companyName})"
                    ]);
                }

                return json(["msg" => '操作成功!', "code" => 200]);
            } else {
                $checkData = [
                    'id' => $id,
                    'modify_fields' => $fields ? implode(",", $fields) : null,
                    'modify_files' => $files ? implode(",", $files) : null,
                    'checkUser' => session('user')['name'],
                    'updateUser' => session('user')['uid'],
                    'updateTime' => date("Y-m-d H:i:s")
                ];
                $res = EnterpriseApi::updateById($checkData);

                if ($lastLog["active"] === 0) {
                    TalentChecklog::update([
                        'id' => $lastLog["id"],
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => TalentState::stateEnum($newCheckState),
                        'description' => $checkMsg,
                        'updateTime' => date("Y-m-d H:i:s", time()),
                        'updateUser' => session('user')['name'] . "({$companyName})"
                    ]);
                } else {
                    TalentChecklog::create([
                        'id' => getStringId(),
                        'mainId' => $id,
                        'type' => 10,
                        'typeFileId' => null,
                        'active' => 0,
                        'state' => $newCheckState,
                        'step' => 101,
                        'stateChange' => TalentState::stateEnum($checkState),
                        'description' => $checkMsg,
                        'createTime' => date("Y-m-d H:i:s", time()),
                        'createUser' => session('user')['name'] . "({$companyName})"
                    ]);
                }
                return json(["msg" => '保存成功!', "code" => 200]);
            }
        } catch (\Exception $e) {
            return json(["msg" => $e->getMessage()]);
        }
    }

    private function getFieldAndFilesBySpecialAndType($special, $type) {
        $fields = ["name" => "医院名称", "idCard" => "登记号", "legal" => "法人代表", "medicalCommunityId" => "医共体", "isGeneral" => "是否总院", "ephone" => "医院电话", "province" => "地址省", "city" => "地址市", "county" => "地址县\区", "address" => "医院地址",
            "bankCard" => "银行账号", "bank" => "开户银行", "bankNetwork" => "开户银行网点",
            "agentName" => "人才联络员姓名", "agentPhone" => "人才联络员电话", "agentEmail" => "人才联络员邮箱"];
        $files = ["imgurl" => "医疗机构执业许可证", "bankImg" => "开户许可证/基本存款账户信息", "beian" => "人才联络员信息备案表"];
        return ["fields" => $fields, "files" => $files];
    }

}
