<?php
namespace Application\Service\DB\Admin;

use Application\Command\Swoole\Server\WebSocketCommand;
use Interop\Container\ContainerInterface;
use Laminas\Json\Json;
use Swoole\Coroutine\Http\Client;
use function Co\run;

class User extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        if (!$this->tableName) {
            $this->tableName = 'yikeen_admin_user';
        }

        $this->is_update_info = 0;
        $this->maskingFieldList = ['mobile'];
        parent::__construct($dbAdapter, $container);
    }

    public function getAdminUserData($whereData=[],$type = 0,$field=''){
        $data = [];
        switch ($type){
            case 1:
                $data = $this->LocalService()->adminUser->fetchAll($whereData);
                break;
            case 2:
                $data = $this->LocalService()->adminUser->fetchOne($whereData);
                break;
            case 3:
                $data = $this->LocalService()->adminUser->fetchCol($field,$whereData);
                break;
            default:
                $data['data'] = $this->LocalService()->adminUser->fetchAll($whereData);
                $data['count'] = $this->LocalService()->adminUser->getCount($whereData['where']);
                break;
        }
        return $data ;
    }

    /**
     * 字段group用来判断是哪个端的用户, 0 => 后台用户, 1 => real端用户, 2 => 既是后台又是real用户
     * 如果后台端被禁了, group需要变成real端用户
     * @param array $query
     * @return int
     */
    public static function getGroup(array $query): int
    {
        // 后台状态
        $status = $query['status'];
        // real端状态
        $realStatus = $query['real_status'];
//        $group = $query['group_type'];
        $group = -1;

        if ($status == 0 && $realStatus == 0) {
            $group = 2;
        } elseif ($realStatus == 0) {
            $group = 1;
        } elseif ($status == 0) {
            $group = 0;
        }

        return $group;
    }

    public function pushWsMessageServer($params)
    {
        run(function() use ($params){
            $cli = new Client('0.0.0.0', WebSocketCommand::LISTEN_PORT);
            $cli->upgrade('/');
            $cli->push(json_encode([
                'action' => $params['action'],
                'to' => $params['to']
            ]));
        });
    }

    /**
     * Notes:获取指定键值下的信息
     * User: lltyy
     * DateTime: 2022/9/21 14:53
     *
     * @param $where //查询条件
     * @param array $columns //查询字段
     * @param array $order //排序值
     * @param array $key_arr //键值数组【键值=>数据类型（0 单笔 1 多笔）】
     * @return array
     * @return array
     */
    public function fetchDataByKey($where,$columns=[],$order=[],$key_arr=[]){
        $arr = [];
        $where_cond = [
            'where'=>$where,
            'columns'=>$columns,
            'order'=>$order
        ];
        $datas = $this->fetchAll($where_cond);
        if(!empty($datas)){
            foreach($datas as $data){
                foreach($key_arr as $key=>$data_type){
                    $key_id = $data[$key];
                    if($data_type == 1){
                        $arr[$key][$key_id][] = $data;
                    }else{
                        $arr[$key][$key_id] = $data;
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * @note 同步signatory_user、item_patient表手机号
     * @param string $oldMobile
     * @return void
     */
    public function syncUpdateUserMobile(string $oldMobile) {
        if(empty($oldMobile)) return ;

        $adminUserData = $this->fetchOne([
            'where'=>[
                'id' => $this->LocalService()->identity->getId(),
                'is_del' => 0
            ]
        ]);

        if (empty($adminUserData)) return;

        // 手机号没有发生更新就不需要更新了
        if ($oldMobile == $adminUserData['mobile']) return;

        // 如果开启real账户，则同步修改 signatory_user表对应的手机号
        if (! $adminUserData['real_status']) {
            $this->LocalService()->signatoryUser->update([
                'user_tel' => $adminUserData['mobile'],
            ], [
                'is_del' => 0,
                'user_tel' => $oldMobile
            ]);
        }

        // 如果patient账户，则同步修改item_patient表对应的手机号
        if(! $adminUserData['patient_status']) {
            $patientData = $this->LocalService()->patient->fetchOne([
                'where' => [
                    'patient_tel' => $oldMobile,
                    'is_del' => 0
                ],
                'columns' => ['id', 'patient_tel', 'patient_content']
            ]);

            if (!empty($patientData)) {
                $patient_content = Json::decode($patientData['patient_content'], Json::TYPE_ARRAY);
                array_walk($patient_content, function (&$value) use ($adminUserData) {
                    if($value['field'] == 'tel') $value['value'] = $adminUserData['mobile'];
                });
                $adminUserData['patient_content'] = Json::encode($patient_content);

                $this->LocalService()->patient->update([
                    'patient_tel' => $adminUserData['mobile'],
                    'patient_content' => $adminUserData['patient_content'],
                ], [
                    'id' => $patientData['id']
                ]);
            }
        }
    }
}