<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/9/8 15:18
 * @Description：
 *
 */
namespace Application\SdmWork;

use Application\Service\BaseService;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Item\Listeners\CacheItemSetListener;
use Laminas\Json\Json;

class WorkUser extends BaseService {
    /**
     * Notes: 获取指定项目下研究医生角色的id值
     * User: llbjj
     * DateTime: 2022/9/8 15:32
     *
     * @param int $item_id
     * @return \phpDocumentor\Reflection\Types\Mixed|string|void|null
     */
    private function getStudyDoctorRole(int $item_id) {
        $studyDoctorRoleCode = $this->LocalService()->config['work']['studyDoctorRoleCode'];
        return $this->LocalService()->realRole->getOneFieldVal('id', [
            'code' => $studyDoctorRoleCode,
            'is_del' => 0,
            'item_id' => $item_id,
        ]);
    }

    function handleRedisList() {
        $database = $this->LocalService()->config['caches']['Redis']['adapter']['options']['database'];
        $redisExtend = $this->LocalService()->redisExtend->setDatabase($database);

        $syncList = [];
        for ($i = 0; $i < 20; $i ++ ){
            $cacheData = $redisExtend->rPop(CacheItemSetListener::SYNC_QY_WORK_USER);
            if ( empty($cacheData) ) break;
            $syncList[] = $cacheData;
        }

        if(!empty($syncList)) {
            foreach($syncList as $sync) {
                $sync = Json::decode($sync, true);

                $this->LocalService()->{$sync['svName']}->{$sync['methodName']}(...array_values($sync['params']));
            }
        }
    }

    /**
     * Notes: 同步合作方联系人到企业微信( 暂时屏蔽 )
     *        暂时先支持研究医生的角色，一个联系人只能再一个中心中担任研究医生
     * User: llbjj
     * DateTime: 2022/9/8 15:22
     *
     * @param int $signatoryUserId
     */
    function syncUserToWork(int $item_id, int $itemsig_id, int $signatoryUserId) {
        return ;
        $studyDoctorRole_id = $this->getStudyDoctorRole($item_id);

        if(!$studyDoctorRole_id) return ;
        $roleSignatoryRelationData = $this->LocalService()->roleSignatoryRelation->fetchOne([
            'where' => [
                'signatory_user' => $signatoryUserId,
                'role_id' => $studyDoctorRole_id,
                'item_id' => $item_id,
                'item_sign_id' => $itemsig_id,
            ]
        ]);

        if(!empty($roleSignatoryRelationData)) {
            if($roleSignatoryRelationData['is_del']) {
                $this->LocalService()->wechatWork->delUser($signatoryUserId);
                // 删除用户后，将对应的【联系我】配置删除
                $contactWayId = $this->LocalService()->signatoryUser->getOneFieldVal('contact_way_id', [
                    'id' => $signatoryUserId
                ]);
                if($contactWayId) $this->LocalService()->wechatWork->delContactWay($contactWayId);
            } else {
                if($roleSignatoryRelationData['status']){
                    $this->LocalService()->wechatWork->setUserEnable($signatoryUserId,  0);
                } else {
                    self::saveUser($itemsig_id, $signatoryUserId);
                }
            }
        }
    }

    /**
     * Notes: 同步受试者信息到企业微信
     *
     * DateTime: 2024/4/17 14:07
     *
     * @param int $item_id
     * @param int $itemsig_id
     * @param int $patient_id
     */
    function syncPatientToWork(int $item_id, int $itemsig_id, int $patient_id) {
        $patientData = $this->LocalService()->patient->fetchOne([
            'where' => ['is_del' => 0, 'id' => $patient_id, 'item_id' => $item_id, 'itemsig_id' => $itemsig_id],
            'columns' => ['patient_number', 'patient_tel']
        ]);

        if(!empty($patientData)) {
            if($this->syncDepartmentToWork($itemsig_id)) {
                $this->LocalService()->wechatWork->saveUser($patient_id, $patientData['patient_number'], $patientData['patient_tel'], $itemsig_id, 1, 'patient');
            }
        }
    }

    /**
     * @throws InvalidConfigException
     */
    function delDepatrmentFromWork(int $item_id) {
        $itemsigIdData = $this->LocalService()->itemSignatory->fetchCol('id', ['item_id' => $item_id]);

        if( !empty($itemsigIdData) ) {
            foreach($itemsigIdData as $itemsigId) {
                $this->LocalService()->wechatWork->delDepartment($itemsigId, 'itemsig');
            }
        }

        $this->LocalService()->wechatWork->delDepartment($item_id);
    }

    /**
     * Notes: 新增/更新用户
     * User: llbjj
     * DateTime: 2022/9/8 16:10
     *
     * @param int $itemsigId
     * @param int $signatoryUserId
     */
    private function saveUser(int $itemsigId, int $signatoryUserId) {
        $signatoryUserData = $this->LocalService()->signatoryUser->fetchOne([
            'where' => [
                'is_del' => 0,
                'status' => 0,
                'id' => $signatoryUserId,
            ],
            'colomns' => ['id', 'user_name', 'user_tel']
        ]);
        if(!empty($signatoryUserData)) {
            // 新增用户之前，要保证部门都存在
            if(self::syncDepartmentToWork($itemsigId)) {
                // saveUser 返回是用户是否存在，也就同步用户是新增还是更新，存在则表示的是更新
                $isUp = $this->LocalService()->wechatWork->saveUser($signatoryUserId, $signatoryUserData['user_name'], $signatoryUserData['user_tel'], $itemsigId);
                if(!$isUp) {
                    // 自动创建【联系我】
                    $result = $this->LocalService()->wechatWork->addContactWay($signatoryUserId);
                    //将 【联系我】  的信息存入数据库中
                    $this->LocalService()->signatoryUser->update([
                        'contact_way_qrcode' => $result['qr_code'],
                        'contact_way_id' => $result['config_id']
                    ], "id = {$signatoryUserId}");
                }
            }
        }
    }

    /**
     * Notes: 同步部门信息
     * User: llbjj
     * DateTime: 2022/9/8 16:27
     *
     * @param int $itemsigID
     * @return false|void
     */
    private function syncDepartmentToWork(int $itemsigID) {
        $itemsigData = $this->LocalService()->itemSignatory->fetchOne([
            'where' => [
                'id' => $itemsigID,
                'is_del' => 0,
            ],
            'columns' => ['id', 'item_id', 'signatory_id']
        ]);

        if(empty($itemsigData)) return false;
        $itemName = $this->LocalService()->itemInfo->getOneFieldVal('name', [
            'id' => $itemsigData['item_id'],
            'is_del' => 0
        ]);

        if($itemName == '') return false;
        $this->LocalService()->wechatWork->saveDepartment($itemsigData['item_id'], $itemName);
        // 创建中心
        $signatoryName = $this->LocalService()->signatoryInfo->getOneFieldVal('info_name', [
            'id' => $itemsigData['signatory_id'],
            'is_del' => 0
        ]);

        if($signatoryName == '') return false;
        $this->LocalService()->wechatWork->saveDepartment($itemsigID, $signatoryName, 'itemsig', $itemsigData['item_id']);
        return true;
    }
}