<?php

namespace app\admin\controller\sys_manage;

use app\admin\validate\sys_manage\TaskValidate;
use app\controller\Curd;
use app\model\Appointment;
use app\model\OrderSheet;
use app\model\SysCategory;
use app\model\Task;
use app\model\TaskProcess;
use support\Db;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

class TaskController extends Curd
{
    public function __construct()
    {
        $this->model = new Task();
        $this->validate = true;
        $this->validateClass = new TaskValidate();
    }

    /**
     * @Desc 列表查询
     * @Author Gorden
     * @Date 2024/4/7 15:52
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'task_addtimes';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'user' => function ($query) {
                $query->select('user_name', 'user_login_name', 'user_id');
            },
            'cert'
        ]);
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    /**
     * @Desc 工单详情
     * @Author Gorden
     * @Date 2024/4/7 16:15
     *
     * @param Request $request
     * @return Response
     */
    public function info(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('info')->check(['task_id' => $request->get('id')])) {
            return json_fail($this->validateClass->getError());
        }

        $data = $this->model->with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'user' => function ($query) {
                $query->select('user_name', 'user_login_name', 'user_id');
            },
            'memberInfo',
            'cert'

        ])->where('task_id', $request->get('id'))
            ->first();
        if (!empty($data)) {
            $data = $data->toArray();
        }
        // 查订单详情
        if (!empty($data['join_task_order_id'])) {
            $order = OrderSheet::with([
                'goods' => function ($query) {
                    $query->select('goods_id', 'goods_name', 'goods_market_price', 'goods_sales_price', 'goods_status', 'join_goods_category_id', 'goods_cover');
                },
                'order' => function ($query) {
                    $query->select('order_id', 'order_name', 'order_amount_total', 'order_amount_pay', 'order_category', 'order_status_system', 'order_status_payment', 'order_status_storage', 'order_addtimes');
                },
                'running'
            ])->where('join_sheet_order_id', $data['join_task_order_id'])
                ->first();
            if ($order->goods) {
                $order->goods->goods_cover = getenv('STORAGE_DOMAIN') . $order->goods->goods_cover;
                if (!empty($order->goods->join_goods_category_id)) {
                    $order->goods->join_goods_category_id = SysCategory::where('category_id', $order->goods->join_goods_category_id)->value('category_name');
                }
                $data['order'] = $order ?? null;
            }
        }
        // 查预约详情
        if (!empty($data['join_task_appointment_id'])) {
            $appointment = Appointment::with([
                'goods' => function ($query) {
                    $query->select('goods_id', 'goods_name', 'goods_market_price', 'goods_sales_price', 'goods_status', 'join_goods_category_id', 'goods_cover');
                },
                'member' => function ($query) {
                    $query->select('member_id', 'member_mobile');
                },
                'memberInfo',
                'cert',
                'running'

            ])->where('appointment_id', $data['join_task_appointment_id'])
                ->first();
            if ($appointment) {
                if (!empty($appointment->goods->join_goods_category_id)) {
                    $appointment->goods->join_goods_category_id = SysCategory::where('category_id', $appointment->goods->join_goods_category_id)->value('category_name');
                }
                $appointment->goods->goods_cover = getenv('STORAGE_DOMAIN') . $appointment->goods->goods_cover;

                $data['appointment'] = $appointment ?? null;
            }
        }
        // 查询工单处理记录
        $process = TaskProcess::with('user')
            ->where('join_process_task_id',$request->get('id'))
            ->get()
            ->toArray();

        $data['process'] = $process;

        return json_success('', $data);
    }

    /**
     * @Desc 处理工单
     * @Author Gorden
     * @Date 2024/4/8 10:30
     *
     * @param Request $request
     * @return Response
     */
    public function process(Request $request)
    {
        $params = $request->post();
        $params['task_id'] = $request->post('id');
        if ($this->validate && !$this->validateClass->scene('process')->check($params)) {
            return json_fail($this->validateClass->getError());
        }

        Db::beginTransaction();
        try {
            // 更新工单状态
            Task::where('task_id', $params['task_id'])->update(['task_status' => $params['task_status']]);
            // 创建处理记录
            $process = new TaskProcess();
            $process->join_process_task_id = $params['task_id'];
            $process->join_task_process_user_id = JwtToken::getCurrentId();
            $process->task_process_status = $params['task_process_status'];
            $process->task_process_category = $params['task_process_category'] ?? null;
            $process->task_process_begin_datetimes = date('Y-m-d H:i:s', strtotime($params['task_process_datetimes'][0])) ?? null;
            $process->task_process_end_datetimes = date('Y-m-d H:i:s', strtotime($params['task_process_datetimes'][1])) ?? null;
            $process->task_process_json = $params['task_process_json'] ?? null;
            $process->task_process_config_json = $params['task_process_config_json'] ?? null;
            $process->task_process_notify_json = $params['task_process_notify_json'] ?? null;
            $process->task_process_remark = $params['task_process_remark'] ?? null;
            $process->task_process_addtimes = time();
            $process->save();

            // 写日志
            _syslog("工单状态变更", "工单状态变更为：" . $params['task_status']);
            _syslog("工单处理", "处理状态：" . $process->task_process_status . "; 处理分类：" . $process->task_process_category ?? '无');

            Db::commit();
            return json_success('success');
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('工单处理失败');
        }
    }

    /**
     * @Desc 操作日志
     * @Author Gorden
     * @Date 2024/4/8 11:04
     *
     * @param Request $request
     * @return Response
     */
    public function processLog(Request $request)
    {
        if ($this->validate && !$this->validateClass->scene('info')->check(['task_id' => $request->get('id')])) {
            return json_fail($this->validateClass->getError());
        }

        $taskId = $request->get('id');
        $log = TaskProcess::with('user')
            ->where('join_process_task_id', $taskId)
            ->get()
            ->toArray();

        foreach ($log as &$item) {
            $item['datetimes'] = $item['task_process_begin_datetimes'] . ' ~ ' . $item['task_process_end_datetimes'];
        }

        return json_success('', $log);
    }
}