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

namespace Application\Service\DB\Listset;

use Interop\Container\ContainerInterface;
use Laminas\Db\Sql\Predicate\Expression;
use Laminas\Db\Sql\Predicate\Operator;

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

    /**
     * Notes:
     * User: lltyy
     * DateTime: 2022/11/18 9:24
     *
     * @param $user_tel //联系人手机号
     * @param array $data
     * @param $list_type //工作清单类型【1 项目工作清单 2 中心工作清单】
     * @param $parent_item //主项目ID
     * @param $itemsig_id //项目中心ID
     * @param $return_type //返回数据【0 权限角色 2 操作状态（0 无 1 提交审核 2 评审）】
     * @return array
     */
    public function fetchUserRole($user_tel,array $data=[]){
        $list_type = isset($data['list_type']) && !empty($data['list_type']) ? $data['list_type'] : 1;
        $parent_item = isset($data['parent_item']) && !empty($data['parent_item']) ? $data['parent_item'] : 0;
        $itemsig_id = isset($data['itemsig_id']) && !empty($data['itemsig_id']) ? $data['itemsig_id'] : 0;
        $return_type = isset($data['return_type']) && !empty($data['return_type']) ? $data['return_type'] : 0;
        $job_arr = [];
        if($list_type == 1){//获取该人员在项目中担任的角色信息
            $user_id = $this->LocalService()->adminUser->getOneFieldVal('id',[
                'mobile' => $user_tel,
                'is_del' => 0,
                'status' => 0,
            ]);
            $user_id = empty($user_id) ? 0 : $user_id;
            if(!empty($user_id)){
                $itemjob_staff_where = [
                    'item_id' => $parent_item,
                    new Expression('find_in_set(?,user_id)', $user_id),
                ];
                $job_arr = $this->LocalService()->itemJobstaff->fetchCol('job_id',$itemjob_staff_where);
            }
        }else{
            //获取该人员在项目中心中担任的角色信息
            $user_id = $this->LocalService()->signatoryUser->getOneFieldVal('id',[
                'user_tel' => $user_tel,
                'is_del' => 0,
                'status' => 0,
            ]);
            $user_id = empty($user_id) ? 0 : $user_id;
            if(!empty($user_id)){
                $itemsigjob_staff_where = [
                    'is_del' => 0,
                    'signatory_user' => $user_id,
                    'status' => 0,
                ];
                if(!empty($parent_item)){
                    $itemsigjob_staff_where['item_id'] = $parent_item;
                }
                if(!empty($itemsig_id)){
                    $itemsigjob_staff_where['item_sign_id'] = $itemsig_id;
                }
                $job_arr = $this->LocalService()->roleSignatoryRelation->fetchCol('role_id',$itemsigjob_staff_where);
            }
        }
        if($return_type == 1){
            $is_flow = 0;
            $flow_state = isset($data['flow_state']) && !empty($data['flow_state']) ? $data['flow_state'] : 0;
            if($flow_state == 2){//判断当前登陆人是否有提交审核权限
                $update_role_arr = isset($data['update_role']) && !empty($data['update_role']) ? explode(',',$data['update_role']) : [];
                $update_role_arr = array_values($update_role_arr);
                $repeat_update_arr = array_intersect($job_arr,$update_role_arr);
                if(!empty($repeat_update_arr)){
                    $is_flow = 1;
                }
            }elseif($flow_state == 3){//判断当前登陆人是否有评审权限
                $flow_role_arr = isset($data['flow_role']) && !empty($data['flow_role']) ? explode(',',$data['flow_role']) : [];
                $flow_role_arr = array_values($flow_role_arr);
                $repeat_flow_arr = array_intersect($job_arr,$flow_role_arr);
                if(!empty($repeat_flow_arr)){
                    $is_flow = 2;
                }
            }
            return $is_flow;
        }else{
            return $job_arr;
        }
    }

    /**
     * Notes: 获取工作清单的实际完成时间
     * User: lltyy
     * DateTime: 2023/2/2 15:29
     *
     * @param string $where
     * @return array
     */
    public function getListOverDate($where = ''){
        $arr = [];
        $cond = [
            'where'=>$where,
            'columns'=>['list_id','operate_time'],
            'order'=>['operate_time']
        ];
        $datas = $this->fetchAll($cond);
        if(!empty($datas)){
            foreach($datas as $data){
                $list_id = $data['list_id'];
                $arr[$list_id] = date('Y-m-d',$data['operate_time']);
            }
        }
        return $arr;
    }

    /**
     * Notes:获取未完成的工作清单信息【进行中、审核中】
     * User: lltyy
     * DateTime: 2023/2/3 10:47
     *
     */
    public function fetchSendMesData(){
        $arr = [];

        //获取工作清单数据
        $datas = [];
        $where = [
            'is_del' => 0,
            'flow_state' => [2, 3]
        ];
        $cond = [
            'where' => $where,
            'columns'=>['id','item_id','itemsig_id','list_title','end_date','update_role','flow_role','flow_state'],
            'order'=>['end_date asc']
        ];
        //获取项目类工作清单
        $item_datas = $this->LocalService()->listsetItemlist->fetchAll($cond);
        if(!empty($item_datas)){
            foreach($item_datas as &$item_data){
                $item_data_end = !empty($item_data['end_date']) ? $item_data['end_date'] : 0;
                $item_data['list_type'] = 1;
                $datas[$item_data_end][] = $item_data;
            }
        }
        //获取中心类工作清单
        $sig_datas = $this->LocalService()->listsetSiglist->fetchAll($cond);
        if(!empty($sig_datas)){
            foreach($sig_datas as &$sig_data){
                $sig_data_end = !empty($sig_data['end_date']) ? $sig_data['end_date'] : 0;
                $sig_data['list_type'] = 2;
                $datas[$sig_data_end][] = $sig_data;
            }
        }

        //重组发信数据
        if(!empty($datas)){
            ksort($datas);
            $itemDatas = $this->LocalService()->itemInfo->fetchDataByKey('is_del = 0',['id','name','number'],['id'],['id'=>0]);
            $itemData = isset($itemDatas['id']) ? $itemDatas['id'] : [];
            $sigUserData = $this->LocalService()->signatoryUser->fetchCol('user_tel','is_del = 0');
            $userDatas = $this->LocalService()->adminUser->fetchDataByKey([
                'is_del' => 0,
                [
                    'or' => [
                        'status' => 0,
                        'real_status' => 0,
                    ]
                ]
            ],['id','mobile','openid','realname'],['id'],['mobile'=>0]);
            $userData = isset($userDatas['mobile']) ? $userDatas['mobile'] : [];
            $sigRoleUserData = $this->LocalService()->roleSignatoryRelation->fetchUserBySigRole([
                'is_del' => 0,
                'status' => 0,
                new Operator('signatory_user', Operator::OP_GT, 0),
            ]);//项目中心角色人员信息
            foreach($datas as $dataInfos){
                foreach($dataInfos as $data){
                    $item_id = $data['item_id'];
                    $itemsig_id = $data['itemsig_id'];
                    $role_arr = [];
                    if($data['flow_state'] == 2){
                        $role_arr = !empty($data['update_role']) ? explode(',',$data['update_role']) : [];
                    }else{
                        $role_arr = !empty($data['flow_role']) ? explode(',',$data['flow_role']) : [];
                    }
                    if(isset($itemData[$item_id]) && isset($sigRoleUserData[$itemsig_id]) && !empty($role_arr)) {
                        $data_list_type = $data['list_type'];
                        $data_flow = $data['flow_state'] == 3 ? 1 : 0;
                        $send_data = [
                            'id' => $data['id'],
                            'item_id' => $item_id,
                            'type' => $data_list_type.'_'.$data_flow,
                            'show_remark' => $data['list_title'] . '【' . $data['end_date'] . '】',
                            'show_item' => empty($itemData[$item_id]['number']) ? $itemData[$item_id]['name'] : '【'.$itemData[$item_id]['number'].'】'.$itemData[$item_id]['name'],
                        ];
                        foreach($role_arr as $role){
                            $role_user_arr = isset($sigRoleUserData[$itemsig_id][$role]) ? $sigRoleUserData[$itemsig_id][$role] : [];
                            if(!empty($role_user_arr)){
                                foreach($role_user_arr as $role_user){
                                    $sigUserTel = isset($sigUserData[$role_user]) ? $sigUserData[$role_user] : '';
                                    if(!empty($role_user) && !empty($sigUserTel) && isset($userData[$sigUserTel])){
                                        $send_user_name = $userData[$sigUserTel]['realname'];
                                        $send_user_openid = $userData[$sigUserTel]['openid'];
                                        $arr[$send_user_openid]['user_name'] = $send_user_name;
                                        $arr[$send_user_openid]['openid'] = $send_user_openid;
                                        $arr[$send_user_openid]['first'] = "工作清单待处理通知";
                                        $arr[$send_user_openid]['thing3'] = "工作清单";
                                        $arr[$send_user_openid]['item_operate'] = isset($arr[$send_user_openid]) && isset($arr[$send_user_openid]['item_operate']) && !empty($arr[$send_user_openid]['item_operate']) ? $arr[$send_user_openid]['item_operate'] : 0;
                                        $arr[$send_user_openid]['item_flow'] = isset($arr[$send_user_openid]) && isset($arr[$send_user_openid]['item_flow']) && !empty($arr[$send_user_openid]['item_flow']) ? $arr[$send_user_openid]['item_flow'] : 0;
                                        $arr[$send_user_openid]['sig_operate'] = isset($arr[$send_user_openid]) && isset($arr[$send_user_openid]['sig_operate']) && !empty($arr[$send_user_openid]['sig_operate']) ? $arr[$send_user_openid]['sig_operate'] : 0;
                                        $arr[$send_user_openid]['sig_flow'] = isset($arr[$send_user_openid]) && isset($arr[$send_user_openid]['sig_flow']) && !empty($arr[$send_user_openid]['sig_flow']) ? $arr[$send_user_openid]['sig_flow'] : 0;
                                        if($send_data['type'] == '1_0'){//项目类待执行
                                            $arr[$send_user_openid]['item_operate'] += 1;
                                        }elseif($send_data['type'] == '1_1'){//项目类待审核
                                            $arr[$send_user_openid]['item_flow'] += 1;
                                        }elseif($send_data['type'] == '2_0'){//中心类待执行
                                            $arr[$send_user_openid]['sig_operate'] += 1;
                                        }elseif($send_data['type'] == '2_1'){//中心类待审核
                                            $arr[$send_user_openid]['sig_flow'] += 1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if(!empty($arr)){
            foreach($arr as &$arrInfo){
                $arrInfo['time5'] = date('Y年m月d日');
                $remark = '您好，'.$arrInfo['user_name'].'！截止目前待处理工作清单信息如下：';
                if(!empty($arrInfo['item_operate']) || !empty($arrInfo['item_flow'])){
                    $remark .= '项目类';
                    $item_work = [];
                    if(!empty($arrInfo['item_operate'])){
                        $item_work[] = '待执行'.$arrInfo['item_operate'].'条';
                    }
                    if(!empty($arrInfo['item_flow'])){
                        $item_work[] = '待审核'.$arrInfo['item_flow'].'条';
                    }
                    $remark .= '【'.implode('、',$item_work).'】';
                }
                if(!empty($arrInfo['sig_operate']) || !empty($arrInfo['sig_flow'])){
                    $remark .= '中心类';
                    $item_work = [];
                    if(!empty($arrInfo['sig_operate'])){
                        $item_work[] = '待执行'.$arrInfo['sig_operate'].'条';
                    }
                    if(!empty($arrInfo['sig_flow'])){
                        $item_work[] = '待审核'.$arrInfo['sig_flow'].'条';
                    }
                    $remark .= '【'.implode('、',$item_work).'】';
                }
                $arrInfo['remark'] = $remark;
                unset($arrInfo['item_operate']);
                unset($arrInfo['item_flow']);
                unset($arrInfo['sig_operate']);
                unset($arrInfo['sig_flow']);
                unset($arrInfo['user_name']);
            }
            $arr = array_values($arr);
        }
        return $arr;
    }



    public function scanData(){
        //获取患者填写的检查点表单信息
        $where = 'is_del = 0 and is_complete != -1';
        $bool = true;
        $page = 0;
        $limit = 1000;
        $last_id = 0;
        while ($bool) {
            $page++;
            echo "PAGE {$page}：" . PHP_EOL;
            $last_id = $this->mateData($where.' and id > '.$last_id,$limit,0);
            if(!$last_id) $bool = false;
        }
    }

    public function mateData($where,$limit=0,$offset=0){
        $cond = [
            'where'=>$where,
            'columns'=>['id','item_id','itemsig_id','patient_id','checktime_id','form_id','formgroup_id','update_user_id','update_time'],
            'order'=>['id']
        ];
        if(!empty($limit) || !empty($offset)){
            $cond['limit'] = $limit;
            $cond['offset'] = $offset;
        }
        $datas = $this->LocalService()->projectPatientworkbatch->fetchAll($cond);
        $last_id = 0;
        if(!empty($datas)){
            $contentArr = [];
            $content_infos = $this->LocalService()->projectPatientworkinfo->fetchAll([
                'where'=>'is_del = 0 and batch_id in ('.implode(',',array_column($datas,'id')).')',
                'columns'=>['batch_id','content_id']
            ]);
            if(!empty($content_infos)){
                foreach($content_infos as $content_key=>$content_info){
                    $contentArr[$content_info['batch_id']][] = $content_info['content_id'];
                    unset($content_infos[$content_key]);
                }
            }
            unset($content_infos);
            foreach($datas as $dataKey=>$data){
                $last_id = $data['id'];
                $this->LocalService()->projectPatientworkbatch->multipleUpdateData([
                    'item_id'=>$data['item_id'],
                    'itemsig_id'=>$data['itemsig_id'],
                    'patient_id'=>$data['patient_id'],
                    'checktime_id'=>$data['checktime_id'],
                    'form_id'=>$data['form_id'],
                    'formgroup_id'=>$data['formgroup_id'],
                    'content_id'=>isset($contentArr[$data['id']]) && !empty($contentArr[$data['id']]) ? $contentArr[$data['id']] : [],
                    'user_id'=>$data['update_user_id'],
                    'time'=>$data['update_time'],
                    'operate_type'=>11
                ]);
                if(isset($contentArr[$data['id']])){
                    unset($contentArr[$data['id']]);
                }
                unset($datas[$dataKey]);
            }
            unset($contentArr);
        }

        //释放空间
        unset($datas);
        unset($cond);
        unset($where);

        return $last_id;

    }

}