<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/6 10:57
 * @Description：
 *
 */

namespace Application\Service\DB\Signatory;

use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Helper\StringHelper;
use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\IsNotNull;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Stdlib\ArrayUtils;
use Laminas\Validator\Regex;

class User extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $this->tableName = 'yikeen_signatory_user';
        $this->maskingFieldList = ['user_tel'];
        parent::__construct($dbAdapter, $container);
    }

    public function save(array $saveData)
    {
        $result = parent::save($saveData); // TODO: Change the autogenerated stub
        $signatory_user_id = $saveData['id'] ?: $result;

        $this->syncRelation((int)$signatory_user_id);
        return $result;
    }

    public function insert(array $insertData)
    {
        $signatory_user_id = parent::insert($insertData); // TODO: Change the autogenerated stub
        if($signatory_user_id) $this->syncRelation((int)$signatory_user_id);
        return $signatory_user_id;
    }

    /**
     * Notes: 检测合作方联系人手机号
     * User: llbjj
     * DateTime: 2022/9/7 16:41
     *
     * @param array $checkMobileDatas
     * @param int $signatory_info_id
     */
    public function checkMobile(int $signatory_info_id, array &$checkMobileDatas,$userDatas = []) {
        $filterEmptyMobileDatas = array_filter($checkMobileDatas);
        if(count($checkMobileDatas) !== count($filterEmptyMobileDatas)) throw new InvalidArgumentException('请检查手机号是否都填写完毕！');

        $preg_mobile = '/^1[3456789]\d{9}$/';
        $validator = new Regex(['pattern' => $preg_mobile]);

        // 检测手机号格式是否正确
        $arr = [];
        $remind = '';

        foreach($filterEmptyMobileDatas as $k => $mobile) {
            if(!$validator->isValid($mobile)) throw new InvalidArgumentException("手机号【{$mobile}】格式不正确！");
            if(isset($arr[$mobile])){
                $remind.= "    【".$userDatas[$k]['user_name']."与".$userDatas[$arr[$mobile]]['user_name']."手机号一致】           ";
            }
            $arr[$mobile] += $k;
        }
        if(!empty($remind)) {
            throw new InvalidArgumentException($remind."请修改后提交!");
        }


        // 获取所有已经存在的手机号
        $mobileData = $this->fetchCol('user_tel', 'user_tel > 0 and is_del = 0 and info_id != '.$signatory_info_id);

        $repeatMobileData = array_unique(array_intersect($mobileData, $filterEmptyMobileDatas));
        $msg = [];
        foreach($repeatMobileData as $k=>$v){
            $result = $this->fetchOne(['where'=>"id = $k",'columns'=>['user_name','info_id']]);
            $signInfo = $this->LocalService()->signatoryInfo->fetchOne(['where'=>"id = ".$result['info_id'],'columns'=>['info_name']]);

            $msg[] = "手机号".$v."已被【".$signInfo['info_name']."】中心【".$result['user_name']."】占用";

        }

        if(!empty($repeatMobileData)) {
            throw new InvalidArgumentException(implode('、', $msg)."请修改后提交!");
        }

    }

    /**
     * Notes: 同步研究中心联系人关联信息
     * User: llbjj
     * DateTime: 2022/9/6 18:52
     *
     * @param int $signatory_user_id
     */
    public function syncRelation(int $signatory_user_id) {
        $signatoryUser = $this->isShowMaskingField(true)->fetchOne([
            'where' => "id = {$signatory_user_id}",
            'columns' => ['user_name', 'is_del', 'status', 'user_tel', 'admin_user_id']
        ]);

        if(empty($signatoryUser)) return false;

        // 同步系统账户表(AdminUser)
        if(!empty($signatoryUser['user_tel'])){
            $adminUserExistsWhere = $signatoryUser['admin_user_id'] ? [
                'id' => $signatoryUser['admin_user_id']
            ] : [
                'mobile' => $signatoryUser['user_tel']
            ];

            $adminUserData = $this->LocalService()->adminUser->fetchOne([
                'where' => $adminUserExistsWhere,
                'columns' => [
                    'id', 'is_del'
                ]
            ]);
            $signatoryUser['admin_user_id'] = $adminUserData['id'] ?? 0;
            if ( ! $signatoryUser['admin_user_id'] ) {
                // 新增系统账户信息，之开启研究者登录
                $signatoryUser['admin_user_id'] = $this->LocalService()->adminUser->save([
                    'mobile' => $signatoryUser['user_tel'],
                    'realname' => $signatoryUser['user_name'],
                    'status' => 1,
                    'real_status' => 0,
                    'patient_status' => 1
                ]);
            }else {
                $upAdminUserData = [
                    'id' => $signatoryUser['admin_user_id'],
                    'mobile' => $signatoryUser['user_tel'],
                    'real_status' => ($signatoryUser['is_del'] || $signatoryUser['status']) ? 1 : 0,
                ];
                // 如果中心人员的real_status开启，则将is_del = 0,有时会有对应已删除的数据
                if (!$upAdminUserData['real_status']) {
                   $upAdminUserData['is_del'] = 0;

                   if ($adminUserData['is_del']) {
                       $upAdminUserData['realname'] = $signatoryUser['user_name'];
                   }
                }

                $this->LocalService()->adminUser->save($upAdminUserData);

            }
            $this->updateField($signatory_user_id, 'admin_user_id', $signatoryUser['admin_user_id']);
        }

        // 同步角色联系人关系表(ItemRoleSinatoryRelation)
        $upField = [
            'status' => $signatoryUser['status'],
            'is_del' => $signatoryUser['is_del']
        ];


        //美美老师要求取消此操作
//        $upWhere = 'signatory_user = '.$signatory_user_id.' and status != '.$signatoryUser['status'].' and is_del = 0';
//        if($signatoryUser['is_del']) $upWhere = 'signatory_user = '.$signatory_user_id.' and is_del = 0';
//        $this->LocalService()->roleSignatoryRelation->update($upField, $upWhere);

        if($this->LocalService()->config['isOpenWechatWork']) {
            $roleSignatoryRelationDatas = $this->LocalService()->roleSignatoryRelation->fetchAll([
                'where' => [
                    'signatory_user' => $signatory_user_id,
                ]
            ]);
            if(!empty($roleSignatoryRelationDatas)) {
                foreach($roleSignatoryRelationDatas as &$roleSignatoryRelationData) {
                    $this->LocalService()->workUser->syncUserToWork($roleSignatoryRelationData['item_id'], $roleSignatoryRelationData['item_sign_id'], $signatory_user_id);
                }

            }
        }
    }

    /*
     * 修改保存联系人时同步数据到后台联系人
     * $adminFiledId 后台联系人 手机号-用户ID
     * $adminFiledType 后台联系人 手机号-登录状态
     * $user_tel    合作方联系人手机号码
     * $user_name  合作方联系人手机号码
     * $status   合作方联系人手否禁用
     * */
    public function saveAdminUser($adminFiledId,$adminFiledType,$user_tel,$user_name,$status){
        $user_id = $this->LocalService()->identity->getId();
        //当前合作方联系人存在在后台联系人
        if(array_key_exists($user_tel,$adminFiledId)){
            //当合作方联系人禁用  判断相同后台联系人状态并更改
            if(($status == 1)){
                $admin_val['real_status'] = 1;
            }else{
                $admin_val['real_status'] = 0;
            }
            //同步联系人信息
            $this->LocalService()->adminUser->update($admin_val,[
                'is_del' => 0,
                'id' => $adminFiledId[$user_tel],
            ]);
            //当前合作方联系人不存在在后台联系人直接新增
        }else{
            if(empty($status)){
                $admin_val['mobile'] = $user_tel;
                $admin_val['realname'] = $user_name;
                $admin_val['is_del'] = 0;
                $admin_val['status'] = 1;
                $admin_val['real_status'] = 0;
                $admin_val['group_type'] = 1;
                $admin_val['create_user_id'] = $user_id;
                $admin_val['update_time'] = $admin_val['create_time'] = time();
                $this->LocalService()->adminUser->insert($admin_val); //新增
            }
        }

    }

    /**
     * yinai  2022 6 27
     * 删除联系人时同时处理adminuser下的数据同步状态 status  group_type
     * @param $mobile  手机号码唯一查询
     */
    public function updateAdminuser($mobile){
        $adminData['real_status'] = 1;
        $this->LocalService()->adminUser->update($adminData,[
            'is_del' => 0,
            'mobile' => $mobile,
        ]);
    }


    /**
     * yinai  2022 6 27
     * 删除联系人时同时处理adminuser下的数据同步状态 status  group_type
     * @param $mobile  手机号码唯一查询
     */
    public function findsignatoryUser($userID){
        if(empty($userID)){
            return '';
        }

        $signatoryUser = $this->getOneFieldVal('id', [
            'admin_user_id' => $userID,
            'is_del' => 0,
        ]);

        return $signatoryUser ?? 0;
    }

    /**
     * Notes: 获取ID和名称的对应数组
     * @param  $where 条件
     * @param  $filed  查询字段
     * @param  $key  键名
     * @param  $type  对应关系 1 一对一 2 一对多
     * @return array
     * @author haojinhua
     * @date 2024-04-18
     */
    public function getFiledRelation($where,$filed,$key ='id',$type = 1){
        $res = [];
        $where = empty($where) ? [
            'is_del' => 0,
            'status' => 0,
        ]: $where;
        $cond = [
            'where' => $where,
            'columns' => $filed,
            'order' => ['info_id'],
        ];
        $datas = $this->fetchAll($cond);
        if(!empty($datas)){
            foreach ($datas as $data){
                if($type == 1 ){
                    $res[$data[$key]] = $data;
                }else{
                    $res[$data[$key]][] = $data;
                }
            }
        }

        return  $res;
    }

    /**
     * Notes: 获取中心人员对应的AdminUser信息
     * User: lltyy
     * DateTime: 2024/11/21 9:03
     *
     * @param array $info
     * @return array
     */
    public function fetchUserAdminData($info = []){
        $sigUserArr = isset($info['id']) && !empty($info['id']) ? $info['id'] : [];
        $arr = [];
        //重组中心人员手机信息【手机为键值，人员ID为值】
        $sigUserTelArr = [];
        $select_user_where_arr = [];//获取中心人员在adminUser表的信息条件
        $sigUserWhere = [
            'is_del' => 0,
            new Operator('user_tel', Operator::OP_NE, ''),
            new IsNotNull('user_tel'),
        ];
        if(!empty($sigUserArr)){
            $sigUserWhere['id'] = StringHelper::toArray($sigUserArr);
        }
        $sigUserTelDatas = $this->isShowMaskingField(true)->fetchAll([
            'where'=>$sigUserWhere,
            'columns'=>['id','user_tel']
        ]);
        unset($sigUserArr);
        if(!empty($sigUserTelDatas)){
            foreach($sigUserTelDatas as $sigUserTelKey=>$sigUserTelData){
                $sigUserTelArr[$sigUserTelData['user_tel']] = $sigUserTelData['id'];
                if($sigUserTelData['user_tel']) $select_user_where_arr[$sigUserTelData['user_tel']] = $sigUserTelData['user_tel'];
                unset($sigUserTelDatas[$sigUserTelKey]);
            }
        }
        unset($sigUserTelDatas);

        //获取手机号对应的人员信息
        $adminUserWhere = [
            'is_del' => 0,
            new Operator('mobile', Operator::OP_NE, ''),
            new IsNotNull('mobile'),
        ];
        if(!empty($select_user_where_arr)) {
            $adminUserWhere['mobile'] = StringHelper::toArray($select_user_where_arr);
        }else {
            $adminUserWhere = 'id < 0';
        }
        unset($select_user_where_arr);
        $adminUserDatas = $this->LocalService()->adminUser->isShowMaskingField(true)->fetchAll([
            'where'=>$adminUserWhere,
            'columns'=>['id','openid','mobile']
        ]);
        if(!empty($adminUserDatas)){
            foreach($adminUserDatas as $adminUserKey=>$adminUserData){
                $adminUser_sigUser = isset($sigUserTelArr[$adminUserData['mobile']]) && !empty($sigUserTelArr[$adminUserData['mobile']]) ? $sigUserTelArr[$adminUserData['mobile']] : 0;
                if(!empty($adminUser_sigUser)){
                    $arr[$adminUser_sigUser] = [
                        'signatory_user' => $adminUser_sigUser,
                        'admin_user' => $adminUserData['id'],
                        'mobile' => $adminUserData['mobile'],
                        'openid' => $adminUserData['openid']
                    ];
                }
                unset($adminUserDatas[$adminUserKey]);
            }
        }
        unset($adminUserDatas);

        return $arr;
    }

}