<?php

namespace app\admin\controller;

use app\BaseController;
use Exception;
use app\admin\model\Complaint as ComplaintModel;
use app\admin\validate\ComplaintValidate;

/**
 * 客服投诉列表
 */
class Complaint extends BaseController
{

    /**
     * @api {get} /complaint/list 列表
     */
    function list()
    {
        try {
            $params = $this->request->param();

            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            $language_code = $params['language_code'] ?? $this->lang;
            
            $query = ComplaintModel::alias('complaint')->join('admin', 'admin.id=complaint.kefu_id','left')
                                    ->where('complaint.language_code', $language_code); 
            if (!empty($params['keyword'])) {
                $query = $query->where('admin.nickname', 'like', '%'.$params['keyword'].'%')
                    ->whereOr('admin.phone', 'like', '%'.$params['keyword'].'%');
            }
            if (!empty($params['complaint_item_id'])) {
                $query->where('complaint.complaint_item_id', $params['complaint_item_id']);
            }
            if (isset($params['status'])) {
                $query->where('complaint.status', $params['status']);
            }
            if (!empty($params['start_time'])) {
                $query->where('complaint.created_at', '>=', $params['start_time'] . ' 00:00:00');
            }
            if (!empty($params['end_time'])) {
                $query->where('complaint.created_at', '<=', $params['end_time'] . ' 23:59:59');
            }
            $count = $query->count();
            $list = $query->with(['complaint_item', 'user', 'operation'])
                        ->field(['complaint.*', 'admin.nickname','admin.phone'])
                        ->order('complaint.created_at','desc')
                        ->limit($limit)
                        ->page($page)
                        ->select();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);
    }

    //编辑
    public function update()
    { 
        try {
            $params = (new ComplaintValidate())->post()->goCheck('edit');
            $id = $this->request->param('id',0);
            
            $language_code = $params['language_code'] ?? $this->lang;

            $complaint = ComplaintModel::where('id', $id)->find();
            if (!$complaint) {
                return $this->error('投诉项不存在');
            }
            $complaint->name = $params['name'];
            $complaint->weight = $params['weight'];
            $complaint->language_code = $language_code;
            $complaint->save();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success([], '操作成功');
    }

}