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

namespace Application\Service\DB\Item;
use Application\Mvc\Controller\BasicController;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\SDMHelper;
use Interop\Container\ContainerInterface;
use Application\Service\Extension\Laminas;
use Laminas\Db\Sql\Where;


class Info extends \Application\Service\DB\AbstractDb
{
    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $this->tableName = 'yikeen_item_info';
        parent::__construct($dbAdapter, $container);
    }

    /*
     *  yinai  2022/6/7
     * 查询当前角色是否有对项目的创建以及操作权限
     * $role   0：超级管理员   1：项目管理人员/项目经理
     * 1：超级管理员   创建项目权限  新增
     * 2：项目管理人员/项目经理    操作项目权限   编辑
     * */
    public function getRole($item_id = 0){
        $data = "";
        $user_id = $this->LocalService()->identity->getId();
        if(!empty($item_id)){
            $infodata['where'] = (new Where())->equalTo('is_mainitem', 1)
                                              ->equalTo('id', $item_id)
                                              ->nest()
                                              ->equalTo('admin_user', $user_id)
                                              ->or
                                              ->expression("find_in_set(?, manage_user)", $user_id)
                                              ->unnest();
            $infodata['columns'] = ['id'];
            $iteminfoData = $this->LocalService()->itemInfo->fetchOne($infodata);
            if(!empty($iteminfoData))$data = $user_id;
        }else{
            $superroleData = $this->LocalService()->itemSuperrole->fetchCol('userids',"is_del = 0");
            $userids = explode(",",$superroleData[1]);
            if(in_array($user_id,$userids)) $data = $user_id;
        }
        return $data;
    }


    /*
     *  yinai  2022/6/20
     * 查询当前项目下的副项目  以及项目合作方
     * $item_id  项目ID
     * $type：1:大项目  2:副项目
     * */
    public function geItemsignList($where,$item_id = 0,$type = 0){
        //查询项目下角色信息
        $whereIteminfo['where'] = $where;
        $whereIteminfo['columns'] = ['value'=>'id', 'label'=>'name','pause_random'];
        $iteminfoDatas = $this->LocalService()-> itemInfo->fetchAll($whereIteminfo);
        //项目合作方基本信息
        $itemsignatoryDatas = $this->LocalService()->itemSignatory->itemSigninfo(0, $item_id, $type);
        if(empty($itemsignatoryDatas))return $iteminfoDatas;
        foreach($iteminfoDatas as $key=>$val){
            foreach($itemsignatoryDatas as $k=>$v){
                if(!empty($v['id'])){
                    $itemsignatoryDatas[$k]['label'] = $v['info_name'];
                    $itemsignatoryDatas[$k]['value'] = $v['id'];
                    unset($itemsignatoryDatas[$k]['id']);
                    unset($itemsignatoryDatas[$k]['item_id']);
                    unset($itemsignatoryDatas[$k]['signatory_id']);
                    unset($itemsignatoryDatas[$k]['info_name']);
                }
                $itemsignatoryDatas[$k]['item_ids'] = $val['value'];
            }
            $iteminfoDatas[$key]['children'] = $itemsignatoryDatas;
        }
        return $iteminfoDatas;
    }

    /*
     * 缓存项目状态redis
     *
     */
    public function ItemsaveStatus($item_id,$status)
    {
        $redis = Laminas::$serviceManager->redisExtend->getRedisInstance();
        $keys = $item_id.'_itemid';
        $item_status = $redis->get($keys);
        if(!empty($item_status)){
            $redis->del($keys);
        }
        $str = json_encode($status);
        $redis->set($keys,$str);
    }


    /*
    * 查询项目状态redis
    * 项目非在施 无编辑权限
    */
    public function ItemStatus($item_id)
    {
        $redis = Laminas::$serviceManager->redisExtend->getRedisInstance();
        $keys = $item_id.'_itemid';
        $status = $redis->get($keys);
        return $status;
    }


    /*
    * 项目模块的读写权限
    */
    public function ItemRoel($item_id,$item_sign_id=0,$model_id)
    {
        $user_id = $this->LocalService()->identity->getId();
        //查询项目
        $itemInfoID = $this->LocalService()->itemInfo->getOneFieldVal('fid',[
            'is_del' => 0,
            'id' => $item_id,
        ]);
        $role_lookwrite = 0;
        //查询角色下的角色管理用户信息
        $roleSignatoryRelationDatas = $this->LocalService()->roleSignatoryRelation->changeUser($itemInfoID,$user_id,$item_sign_id);
        if(!empty($roleSignatoryRelationDatas)){
            $role_id_arr = array_unique(array_column($roleSignatoryRelationDatas, 'role_id'));
            //获取当前模块在当前用户的角色中是有操作的权限
            $whereroleMenuRelation['where'] = [
                'status' => 0,
                'look_write' => 1,
                'module_id' => $model_id,
                'item_id' => $itemInfoID,
                'role_id' => $role_id_arr,
            ];
            $whereroleMenuRelation['columns'] = ['id'];
            $roleMenuRelationDatas = $this->LocalService()->realRolemodulerelation->fetchAll($whereroleMenuRelation);
            if($roleMenuRelationDatas) $role_lookwrite = 1;
        }
        return $role_lookwrite;
    }

    /*
     * 项目基本信息数据同步
     * */
    function RoleAdd($item_id){
        $whereitemInfo['where'] = [
            'is_mainitem' => 1,
            'old_id' => $item_id,
        ];
        $whereitemInfo['columns'] = ['id','old_id'];
        $itemInfoDatas = $this->LocalService()->itemInfo->fetchAll($whereitemInfo);
        if(!empty($itemInfoDatas)){
            foreach($itemInfoDatas as $key=>$val){
                //当项目保存成功时默认当前项目下保存角色信息
                $result = $this->itemRealRole($val['old_id'],$val['id'],$this->LocalService()->identity->getId());
                if(!empty($result)){
                    echo '<span style="color：green">'.'同步成功'.'<span>'.'<br>';
                }else{
                    echo '<span style="color：red">'.'-'.'同步失败'.'<span>'.'<br>';
                }
            }
        }
        //多余角色
        $yikeen = new \mysqli('localhost','root','root3306',"e-yda");
        $yikeen->select_db('e-yda') or die('选择数据库失败：'.$yikeen->error);
        $yikeen->set_charset('utf8') or die('设置字符集失败：'.$yikeen->error);
        $sql='select * from oa_real_role where is_del = 0 and id > 5 and item_id = '.$item_id;
        $result = $yikeen->query($sql);
        $RealRoleDatas=[];
        while($row = $result->fetch_assoc())
        {
            $RealRoleDatas[]=$row;
        }
        $new_item_id = $this->LocalService()->itemInfo->getOneFieldVal('id',[
            'is_mainitem' => 1,
            'old_id' => $item_id,
        ]);
        if(!empty($RealRoleDatas)){
            foreach($RealRoleDatas as $k=>$v){
                $RoleData = [
                    'role_name' => $v['role_name'],
                    'status' => $v['status'],
                    'is_del' => $v['is_del'],
                    'item_id' => $new_item_id,
                    'sort' => $v['sort'],
                    'old_id' => $v['id'],
                    'old_item_id' => $v['item_id'],
                ];
                $realresult = $this->LocalService()->realRole->save($RoleData);
                if(!empty($realresult)){
                    echo '<span style="color：green">'.'同步成功'.'<span>'.'<br>';
                }else{
                    echo '<span style="color：red">'.'-'.'同步失败'.'<span>'.'<br>';
                }
            }
        }
    }

    function itemRealRole($itemoldId,$itemId,$userId){
        $time = time();
        $sortNum = 10;
        $whereArr['where'] = [
            'is_del' => 0,
            'item_id' => $itemId,
        ];
        $realSortArr = $this->LocalService()->realRole->getAdminRealRoleData($whereArr['where'],3,'sort');
        !empty($realSortArr) && $sortNum = max($realSortArr)+10;
        $itemRealRoleName = ['研究医生','研究助理','PM','CRA','CRC'];
        $whereMArr['where'] = 'is_del=0 and menu_type=1';
        $whereMArr['order'] = 'menu_order';
        $menuList = $this->LocalService()->adminMenu->getAdminMenuData($whereMArr,1);
        $menuIdArr = [];
        if (!empty($menuList)){
            $menuIdArr = array_column($menuList,'id');
        }
        $i = 1;
        foreach($itemRealRoleName as $k=>$v){
            $realRoleArr = [
                'status' => 0,
                'is_del' => 0,
                'update_time' => $time,
                'create_time' => $time,
                'update_user_id' => $userId,
                'create_user_id' => $userId,
                'item_id' => $itemId,
                'sort' => $sortNum,
                'old_id' => $i++,
                'old_item_id' => $itemoldId,
            ];
            $realRoleArr['role_name'] = $v;
            if ($k > 1){
                $realRoleArr['source_type'] = 1;
            }
            $sortNum = $sortNum+10;
            $realRoleId = $this->LocalService()->realRole->save($realRoleArr);
            if (!empty($menuIdArr)){
                foreach ($menuIdArr as $key => $value) {
                    if($value == 53 || $value == 54) continue;
                    $realRolemodulerelationArr['role_id'] = $realRoleId;
                    $realRolemodulerelationArr['module_id'] = $value;
                    $realRolemodulerelationArr['item_id'] = $itemId;
                    if(($k < 2) || ($k == 4)){
                        $realRolemodulerelationArr['look_write'] = 1;
                    }else{
                        $realRolemodulerelationArr['look_write'] = 0;

                    }
                    $this->LocalService()->realRolemodulerelation->save($realRolemodulerelationArr);
                }
            }

        }
        return $realRoleId;
    }

    /**
     * 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;
    }

    /**
     * Notes: 获取oa项目名称
     * @param
     * @return
     * @author haojinhua
     * @date 2024-07-19
     */
    public function getoaitemData(){
        $res = [];
        $oa_items = $this->LocalService()->OAClient->itemInfoList();
        if(!empty($oa_items)){
            foreach ($oa_items as $oa_item){
                $res[$oa_item['value']] = $oa_item['label'];
            }
        }
        
        return $res;
    }

    /**
     * Notes:获取项目图库有操作数据的项目
     * 按时间展示：未锁定、作废、补图、申请解锁/解锁未更新、解锁已更新
     * 常规（识别）：未锁定、申请解锁/解锁未更新、解锁已更新
     *
     * @param array $info
     * @return array
     */
    public function fetchOperateItemArr($info=[]){
        $item_arr = isset($info['item_arr']) && !empty($info['item_arr']) ? $info['item_arr'] : [];
        $arr = $this->fetchNoLockItemArr(['item_arr'=>$item_arr]);
        return $arr;
    }





    public function OLDfetchOperateItemArr($info=[]){
        $item_arr = isset($info['item_arr']) && !empty($info['item_arr']) ? $info['item_arr'] : [];

        $arr = $this->fetchNoLockItemArr(['item_arr'=>$item_arr]);
        return $arr;
    }
    /**
     * Notes:获取项目图库 有未锁定数据 的项目
     * User: lltyy
     * DateTime: 2024/8/16 10:03
     *
     * @return array
     */
    public function fetchNoLockItemArr($info=[]){
        $item_arr = isset($info['item_arr']) && !empty($info['item_arr']) ? $info['item_arr'] : [];

        //获取按时间展示【未锁定、作废、补图、申请解锁/解锁未更新、解锁已更新】、常规类识别【未锁定、申请解锁/解锁未更新、解锁已更新】 的项目
        $where = (new Where())->equalTo('is_del', 0)
                              ->nest()
                              ->equalTo('lock_state', 0)
                              ->or
                              ->equalTo('is_annul', 1)
                              ->or
                              ->equalTo('is_new', 1)
                              ->or
                              ->equalTo('is_unlock', 1)
                              ->unnest();

        if(!empty($item_arr)){
            $where->in('item_id', $item_arr);
        }
        $info_item_arr = $this->LocalService()->projectPatientwork->fetchCol('item_id',$where);
        $info_item_arr = !empty($info_item_arr) ? array_values(array_unique($info_item_arr)) : [];
        unset($where);
        return $info_item_arr;
    }
}