<?php

namespace app\admin\controller;

use app\admin\model\ProcessWait;
use think\App;
use think\facade\Db;

//消息(已读未读)
class Proorder extends Base
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    //已读列表
    public function list()
    {

        /**暂时屏蔽
         * $page = isset($this->post['page']) && $this->post['page'] !==""? intval($this->post['page']) :"1";
         * $size = isset($this->post['size']) && $this->post['size'] !==""? intval($this->post['size']) :"10";
         * $where =[['is_del',"=",0],['a.order_status',"=",2]];
         * $role=$this->checkRole();
         * if(!empty($role['write'])){
         * $where[]=["a.action_uid","in",$role['write']];
         * }
         * $count = Db::name('process_order')->alias("a")->leftJoin("workflow b","a.order_id=b.order_id and a.order_code=b.order_code")->where($where)->count();
         * $total = ceil("$count/$size");
         * $page = $page>$total ? $total:$page;
         * $list = Db::name('process_order')->alias("a")->leftJoin("workflow b","a.order_id=b.order_id and a.order_code=b.order_code")
         * ->field("b.apply_id,b.apply_name,a.addtime,a.action_uid,a.action_name,a.order_status,a.action_status,a.order_type,a.action_process,a.order_code,a.order_id,a.id")
         * ->where($where)->page($page,$size)->order("a.addtime desc")->select();
         * $data=[];
         * foreach ($list as $value){
         * $str = Db::name("process")->where(['process_type' => $value['order_type']])->field("process_name,status")->find();
         * $var = Db::name("action_process")->where(['order_type'=>$value['order_type'],'order_process'=>$value['action_status']])->field("status_name,order_process,order_name,roleid")->find();
         * $value['process_name']=$str['process_name'];
         * $value['order_name']=$var['order_name'];
         * $value['status_name'] = $var['status_name'];
         * $data[]=$value;
         * }
         * return app_show(0,"获取成功",['count'=>$count,'list'=>$data]);
         * **/

        {

            $param = $this->request->filter('trim')->only(['token', 'apply_id' => '', 'action_uid' => '', 'order_code' => '', 'page' => 1, 'size' => 10], 'post');

            $db = ProcessWait::alias("a")
                ->leftJoin('workflow b', 'a.order_type=b.order_type and a.order_id=b.order_id')//这个地方不适宜用order_code,因为特殊单子没有编码,例如离职交接单
                ->where(['is_del' => 0, 'a.status' => ProcessWait::$status_finish]);

            $db->where(function ($query) use ($param) {
                //所属角色
                $role = $this->checkRole();
//                if (!empty($role['write']) || $role['roleid'] == 33) $query->whereFindInSet('roleid', $role['roleid']);
                $query->whereFindInSet('roleid', $role['roleid']);

                //本人id
//                $user = GetUserInfo($param['token']);
                //if (isset($user['data']['id']))
                $query->whereOr('wait_id', $this->uid);
            });

            if ($param['order_code'] != '') $db->whereLike("a.order_code", '%' . $param['order_code'] . '%');
            if ($param['action_uid'] != '') $db->where('a.action_uid', $param['action_uid']);

            $count = $db
//                ->field("ANY_VALUE(`a`.`id`) id,`a`.order_type,`a`.order_id,GROUP_CONCAT(`a`.`id` ORDER BY `a`.`id` DESC) ids")
                ->group('a.order_type,a.order_id')
//                ->order(['a.id'=>'desc'])
//                ->fetchSql()
//                ->withAttr('ids', function ($val) {
//                    $temp = explode(',', $val);
//                    return $temp[0];
//                })
//                ->page($page, $param['size'])
                ->count('a.id');

            $total = ceil($count / $param['size']);
            $page = $param['page'] > $total ? $total : $param['page'];

            //筛选符合条件的order_type,排除重复数据
            $order_types = $db
                ->field("ANY_VALUE(`a`.`id`) id,`a`.order_type,`a`.order_id,GROUP_CONCAT(`a`.`id` ORDER BY `a`.`id` DESC) ids")
                ->group('a.order_type,a.order_id')
                ->order(['id' => 'desc'])
                ->withAttr('ids', function ($val) {
                    $temp = explode(',', $val);
                    return $temp[0];
                })
                ->page($page, $param['size'])
                ->select()
                ->toArray();

            $list = ProcessWait::alias("a")
                ->field([
                    'b.apply_id',
                    'b.apply_name',
                    'a.addtime',
                    'a.action_uid_finally' => 'action_uid',//取实时操作人id
                    'a.action_name_finally' => 'action_name',//取实时操作人
                    'a.order_status',
                    'a.order_type',
                    'a.order_code',
                    'a.order_id',
                    'a.id',
                    'a.order_process_finally' => 'order_process',//取实时状态值
                ])
                ->whereIn('a.id', array_column($order_types, 'ids'))
                ->leftJoin("workflow b", "a.order_type=b.order_type and a.order_id=b.order_id")
//                ->page($page, $param['size'])
                ->order("a.addtime desc")
                ->select()
                ->toArray();

            //所有流程名称
            $all_process = Db::name("process")
                ->whereIn('process_type', array_column($list, 'order_type'))
                ->column("process_name", 'process_type');

            $data = [];
            foreach ($list as $value) {
                $var = Db::name("action_process")
                    ->where(['order_type' => $value['order_type'], 'order_process' => $value['order_process']])
//                    ->whereIn('order_process', [$value['order_process'], $value['order_process_finally']])
                    ->field("status_name,order_process,order_name,roleid")
//                    ->column('status_name,order_process,order_name,roleid', 'order_process');
                    ->findOrEmpty();
                $value['process_name'] = isset($all_process[$value['order_type']]) ? $all_process[$value['order_type']] : '';
                $value['order_name'] = $var['order_name'];
                $value['status_name'] = $var['status_name'];
//                $value['order_process_finally_status_name'] = $var[$value['order_process_finally']]['status_name'] ?? '';
                $data[] = $value;
            }
            return app_show(0, "获取成功", ['count' => $count, 'list' => $data]);
        }


    }

    //待处理列表
    public function waitlist()
    {

        $param = $this->request->filter('trim')->only(['token', 'apply_id' => '', 'action_uid' => '', 'order_code' => '', 'page' => 1, 'size' => 10], 'post');

        $db = ProcessWait::alias("a")
            ->leftJoin('workflow b', 'a.order_type=b.order_type and a.order_id=b.order_id')//这个地方不适宜用order_code,因为特殊单子没有编码,例如离职交接单
//            ->leftJoin('process p', 'p.process_type=a.order_type AND p.is_del=0 AND p.status=1')
            ->where(['a.status' => ProcessWait::$status_wait]);


//        $db->where(function ($query) use ($param) {
        //所属角色
        $role = $this->checkRole();
        if ($role['roleid'] != 1) $db->whereFindInSet('handle_user_list', $this->uid);

//            if (!empty($role['write']) || $role['roleid'] == 33) $query->whereFindInSet('roleid', $role['roleid']);
//            $query->whereFindInSet('roleid', $role['roleid']);

        //本人id
//            $query->whereOr('wait_id', $this->uid);
//        });

        if ($param['order_code'] != '') $db->whereLike('a.order_code', '%' . $param['order_code'] . '%');
        if ($param['action_uid'] != '') $db->where('a.action_uid', $param['action_uid']);

        $count = $db->count();

        $total = ceil($count / $param['size']);
        $page = $param['page'] > $total ? $total : $param['page'];
        $list = $db
            ->field("a.id,a.addtime,a.action_name,a.order_status,a.order_type,a.order_process,a.order_code,a.order_id,a.handle_user_list,b. apply_id,b.apply_name")
            ->page($page, $param['size'])
            ->order("a.addtime desc")
//            ->append(['handle_user_list'])
//            ->withAttr('handle_user_list', function ($val, $da) {
//                return [];
//            })
            ->select()
            ->toArray();

        //所有流程名称
        $all_process = Db::name("process")
            ->whereIn('process_type', array_column($list, 'order_type'))
            ->column("process_name", 'process_type');

        $data = [];
        foreach ($list as $value) {
            $var = Db::name("action_process")
                ->where(['order_type' => $value['order_type'], 'order_process' => $value['order_process']])
                ->field("status_name,order_process,order_name,roleid")
                ->find();
            $value['process_name'] = isset($all_process[$value['order_type']]) ? $all_process[$value['order_type']] : '';
            $value['order_name'] = $var['order_name'];
            $value['status_name'] = $var['status_name'];

            //找到流程对应记录的所有人(创建人 or 申请人 or 采购员)
//            $holder_id = 0;

//            switch ($value['order_type']) {
//                //1.采购单流程
//                case 'CGD':
//                    $holder_id = Db::name('purchease_order')->where(['id' => $value['order_id'], 'is_del' => 0])->value('cgder_id', 0);
//                    break;
//                //2.采购单入库流程
//                case 'RKD':
//                    $holder_id = Db::name('purchease_in')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //3.备货申请单流程
//                case 'BHD':
//                    $holder_id = Db::name('purchease')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //4.销售订单流程
//                case 'XSQRD':
//                    $holder_id = Db::name('sale')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //5.发货申请单流程
//                case 'CKD':
//                    $holder_id = Db::name('order_out')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //6.售后申请单流程
//                case 'SHD':
//                    $holder_id = Db::name('order_return')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //7.售后退货单流程
//                case 'CKTHD':
//                    $holder_id = Db::name('order_back')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //8.销售退货单流程
//                case 'XSTHD':
//                    $holder_id = Db::name('sale_return')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //9.采购工差单流程
//                case 'CGGCD':
//                    $holder_id = Db::name('purchease_diff')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //10.销售工差单流程
//                case 'XSGCD':
//                    $holder_id = Db::name('sale_diff')
//                        ->alias('a')
//                        ->where(['a.id' => $value['order_id']])
//                        ->leftJoin('sale s', 's.orderCode=a.orderCode')
//                        ->value('s.apply_id', 0);
//                    break;
//                //11.调拨单流程
//                case 'DBD':
//                    $holder_id = Db::name('allot_stock')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //12.盘点单流程
//                case 'PDD':
//                    $holder_id = Db::name('good_check')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //13.议价单流程
//                case 'YJD':
//                    $holder_id = Db::name('bargain_order')->where(['id' => $value['order_id'], 'is_del' => 0])->value('createrid', 0);
//                    break;
//                //14.项目单流程
//                case 'PRO':
//                    $holder_id = Db::name('project')->where(['id' => $value['order_id'], 'is_del' => 0])->value('createrid', 0);
//                    break;
//                //15.商品成本流程
//                case 'SPCB':
//                    $holder_id = Db::name('good_basic')->where(['id' => $value['order_id'], 'is_del' => 0])->value('chargerid', 0);
//                    break;
//                //16.商品上线流程
//                case 'SPSX':
//                    $holder_id = Db::name('good_platform')
//                        ->alias('a')
//                        ->where(['a.id' => $value['order_id']])
//                        ->leftJoin('good g', 'g.spuCode=a.spuCode')
//                        ->value('g.createrid', 0);
//                    break;
//                //17.活动流程
//                case 'HD':
//                    $holder_id = Db::name('good_activity')->where(['id' => $value['order_id'], 'is_del' => 0])->value('createrid', 0);
//                    break;
//                //19.有赞商品上架流程
//                case 'YZSX':
//                    $holder_id = Db::name('platform_youzan')
//                        ->alias('a')
//                        ->where(['a.id' => $value['order_id']])
//                        ->leftJoin('good g', 'g.spuCode=a.spuCode')
//                        ->value('g.createrid', 0);
//                    break;
//                //20.有赞订单审核流程
////                case 'YZQRD':
////                    $holder_id = Db::name('')->where(['id' => $value['order_id'], 'is_del' => 0])->value('', 0);
////                    break;
//                //22.离职交接流程
//                case 'LZJJ':
//                    $holder_id = Db::name('resign_info')->where(['id' => $value['order_id'], 'is_del' => 0])->value('hand_uid', 0);
//                    break;
//                //23.采购单退货流程
//                case 'CGTHD':
//                    $holder_id = Db::name('purchease_return')->where(['id' => $value['order_id'], 'is_del' => 0])->value('apply_id', 0);
//                    break;
//                //24.竞价单流程
//                case 'ZXD':
//                    $holder_id = Db::name('consult_order')->where(['id' => $value['order_id'], 'is_del' => 0])->value('createrid', 0);
//                    break;
//                //25.商品下线流程
//                case 'GOL':
//                    $holder_id = Db::name('good_offline_log')->where(['id' => $value['order_id'], 'is_del' => 0])->value('createrid', 0);
//                    break;
//            }

            //根据记录的所有人判断哪些人能看到它的记录
//            $uids_1 = $this->get_uids_by_group_share($holder_id, $value['api_url']);

            //根据角色筛选
            $uid = Db::name('user_role')
                ->field('uid')
                ->where([
                    ['is_del', '=', 0],
                    ['uid', 'in', $value['handle_user_list']],
//                    ['roleid', '<>', 1],//超级管理员不在这个范围内
                    ['status', '=', 1],
                ])
                ->buildSql();
            $value['handle_user_list'] = Db::name('depart_user')
                ->where(['is_del' => 0, 'status' => 1])
                ->where('uid IN ' . $uid)
                ->column('nickname');

//            $value['uid_1'] = $uids_1;
//            $value['uid_2'] = $uids_2;

//            $uids = array_intersect($uids_1, $uids_2);

//            $users = Db::name('depart_user')->where(['is_del' => 0, 'status' => 1])->whereIn('uid', $uids)->column('nickname');

            //当前操作人
//            $value['handle_user_list'] = $value['wait_name'] ? array_merge($users, [$value['wait_name']]) : $users;

            $data[] = $value;
        }
        return app_show(0, "获取成功", ["list" => $data, 'count' => $count]);
    }

    public function all()
    {
        $token = isset($this->post['token']) ? trim($this->post['token']) : "";
        if ($token == "") {
            return error_show(101, 'token不能为空');
        }
        $effetc = VerifyTokens($token);
        if (!empty($effetc) && $effetc['code'] != 0) {
            return error_show($effetc['code'], $effetc['message']);
        }
        $where = [["is_del", "=", 0]];
        $process_name = isset($this->post['process_name']) && $this->post['process_name'] !== "" ? trim($this->post['process_name']) : "";
        if ($process_name != "") {
            $where[] = ["process_name", "like", "%$process_name%"];
        }
        $process_type = isset($this->post['process_type']) && $this->post['process_type'] !== "" ? trim($this->post['process_type']) : "";
        if ($process_type != "") {
            $where[] = ["process_type", "like", "%$process_type%"];
        }
        $list = Db::name('process')->where($where)->order("addtime desc")->select();
        return app_show(0, "获取成功", $list);
    }


}