<?php

namespace app\admin\controller;

use app\admin\model\ProcessWait;
use think\facade\Db;
use think\facade\Validate;
use app\admin\model\ActionProcess as APModel;
use app\admin\model\Process as PModel;

//流程节点
class ActionProcess extends Base
{

    //获取流程节点列表
    public function getList()
    {

        $param = $this->request->filter('trim')->only(['process_id', 'action_type' => '', 'operation_type' => '', 'page' => 1, 'size' => 15], 'post');

        $val = Validate::rule([
            'process_id|流程id' => 'require|number|gt:0',
            'page|页码' => 'require|number|gt:0',
            'size|每页显示的页码' => 'require|number|gt:0',
        ]);

        if (!$val->check($param)) return error_show(1005, $val->getError());

        $where = [['is_del', '=', APModel::$is_del_normal]];
        if ($param['process_id'] != '') $where[] = ['process_id', '=', $param['process_id']];
        if ($param['action_type'] != '') $where[] = ['action_type', '=', $param['action_type']];
        if ($param['operation_type'] != '') $where[] = ['operation_type', '=', $param['operation_type']];

        $count = Db::name('action_process')
            ->where($where)
            ->count('id');

        $list = APModel::field('id,status_name,order_process,status,action_type,operation_type,next_action_ids,creater,addtime,remark,is_master')
            ->where($where)
            ->order('id', 'desc')
            ->page($param['page'], $param['size'])
            ->select()
            ->toArray();

        $all_next_ids = implode(',', array_column($list, 'next_action_ids'));

        //处理下一个节点的名称
        $child = Db::name('action_process')
            ->whereIn('id', $all_next_ids)
            ->column('status_name', 'id');

        foreach ($list as &$item) {
            if ($item['next_action_ids']) {
                $next_action_ids = explode(',', $item['next_action_ids']);
                foreach ($next_action_ids as $next_action_id) {
                    if (isset($child[$next_action_id])) $item['next_actions'][] = $child[$next_action_id];
                }
            } else $item['next_actions'] = [];
        }

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

    }

    //新增
    public function add()
    {

        $param = $this->request->filter('trim')->only(['token', 'process_id', 'action_type', 'operation_type', 'status_name', 'order_process', 'next_action_ids' => '', 'remark' => '','is_master'=>APModel::$is_master_no], 'post');

        $val = Validate::rule([
            'token' => 'require',
            'process_id|流程id' => 'require|number|gt:0',
            'action_type|节点类型' => 'require|number|between:' . APModel::$action_type_start . ',' . APModel::$action_type_end,
            'operation_type|操作类型' => 'require|number|in:' . APModel::$operation_type_approval . ',' . APModel::$operation_type_system,
            'status_name|节点名称' => 'require|max:255',
            'order_process|节点值' => 'require|number|egt:0|checkOrderProcess:',
            'next_action_ids|下一节点' => 'array|requireIf:action_type,' . APModel::$action_type_start . '|requireIf:action_type,' . APModel::$action_type_process,
            'is_master|是否主节点' => 'require|number|in:' . APModel::$is_master_yes . ',' . APModel::$is_master_no
        ]);

        $val->extend('checkOrderProcess', function ($val, $rule, $data) {
            return APModel::where([
                'process_id' => $data['process_id'],
                'order_process' => $val,
                'is_del' => APModel::$is_del_normal
            ])->field('id')->findOrEmpty()->isEmpty() ? true : '同一个流程编码下该节点值已存在';
        });

        if (!$val->check($param)) return error_show(1005, $val->getError());

        //获取流程
        $process = PModel::field('id,process_name,process_type')
            ->where(['id' => $param['process_id'], 'is_del' => PModel::$is_del_normal])
            ->findOrEmpty()
            ->toArray();
        if (empty($process)) return error_show(1005, '您所选的流程不存在');

        $uid = $this->uid;
        $uname = $this->uname;
        $date = date('Y-m-d H:i:s');

        return APModel::create(array_merge($param, [
            'order_type' => $process['process_type'],
            'order_name' => $process['process_name'],
            'status' => APModel::$status_disable,
            'is_del' => APModel::$is_del_normal,
            'createrid' => $uid,
            'creater' => $uname,
            'addtime' => $date,
            'updaterid' => $uid,
            'updater' => $uname,
            'updatetime' => $date,
        ]))->save() ? app_show(0, '新增流程节点成功') : error_show(1005, '新增流程节点失败');

    }

    //读取
    public function read()
    {

        $id = $this->request->filter('trim')->post('id/d', 0);

        $res = APModel::field(true)
            ->where(['id' => $id, 'is_del' => APModel::$is_del_normal])
            ->withAttr('next_action_ids', function ($val) {
                return explode(',', $val);
            })
            ->findOrEmpty()
            ->toArray();

        return app_show(0, '请求成功', $res);
    }

    //修改
    public function update()
    {

        $param = $this->request->filter('trim')->only(['token', 'id', 'process_id', 'action_type', 'operation_type', 'status_name', 'order_process', 'next_action_ids', 'remark' => '', 'status', 'is_del','is_master'], 'post');

        $val = Validate::rule([
            'token' => 'require',
            'id|ID' => 'require|number|gt:0',
            'process_id' => 'number|gt:0',
            'action_type|节点类型' => 'number|between:' . APModel::$action_type_start . ',' . APModel::$action_type_end,
            'operation_type|操作类型' => 'number|in:' . APModel::$operation_type_approval . ',' . APModel::$operation_type_system,
            'status_name|节点名称' => 'max:255',
            'order_process|节点值' => 'number|egt:0|checkOrderProcess:',
            'next_action_ids|下一节点' => 'array|requireIf:action_type,' . APModel::$action_type_start . '|requireIf:action_type,' . APModel::$action_type_process,
            'is_del|是否删除' => 'eq:' . APModel::$is_deleted,
            'status|状态' => 'in:' . APModel::$status_disable . ',' . APModel::$status_normal,
            'is_master|是否主节点' => 'number|in:' . APModel::$is_master_yes . ',' . APModel::$is_master_no
        ]);


        $val->extend('checkOrderProcess', function ($val, $rule, $data) {
            if (isset($val) && isset($data['process_id'])) return APModel::where(['process_id' => $data['process_id'], 'order_process' => $val, 'is_del' => APModel::$is_del_normal])->where('id', '<>', $data['id'])->field('id')->findOrEmpty()->isEmpty() ? true : '同一个流程编码下该节点值已存在';
            else return true;
        });

        if (!$val->check($param)) return error_show(1005, $val->getError());

        $info = APModel::where(['id' => $param['id'], 'is_del' => APModel::$is_del_normal])
            ->field('id,process_id')
            ->findOrEmpty();

        if ($info->isEmpty()) return error_show(1005, '该节点记录不存在');

        if (isset($param['status']) && $param['status'] == APModel::$status_disable) {
            //禁用节点时,要校验其所属流程是否被禁用
            $p_info = PModel::field('id')
                ->where(['id' => $info->process_id, 'is_del' => PModel::$is_del_normal, 'status' => PModel::$status_normal])
                ->findOrEmpty()
                ->isEmpty();

            if (!$p_info) return error_show(1005, '该节点所属流程尚未禁用');

        }

        $uid = $this->uid;
        $uname = $this->uname;
        $date = date('Y-m-d H:i:s');

        if (isset($param['next_action_ids']) && is_array($param['next_action_ids'])) $param['next_action_ids'] = implode(',', $param['next_action_ids']);

        return APModel::where(['id' => $param['id'], 'is_del' => APModel::$is_del_normal])->strict(false)->save(array_merge($param, ['updaterid' => $uid, 'updater' => $uname, 'updatetime' => $date])) ? app_show(0, '修改流程节点成功') : error_show(1005, '修改流程节点失败');

    }

    //获取所有流程的所有节点
    public function getAll()
    {

        $data = PModel::where(['is_del' => PModel::$is_del_normal, 'status' => PModel::$status_normal])
            ->order(['weight' => 'desc', 'id' => 'desc'])
            ->column('id,process_name,process_type', 'id');

        $action = APModel::where(['is_del' => APModel::$is_del_normal, 'status' => APModel::$status_normal, 'operation_type' => APModel::$operation_type_approval])
            ->field('id,process_id,order_process,status_name')
            ->cursor();

        foreach ($action as $item) {
            $data[$item->process_id]['child'][] = $item->toArray();
        }

        return app_show(0, '请求成功', array_column($data, null, null));

    }


}