<?php

namespace app\admin\controller;

use think\facade\View;
use think\facade\Db;
use think\Request;
use think\facade\Cache;
use app\admin\validate\SetValidate;
use app\common\controller\Common;

/**
 * 系统设置控制器
 * Class Set
 * @package app\admin\controller
 */
class Set extends Common
{
    /**
     * 首页
     * @return string
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 聊天代码
     * @return string
     */
    public function access_code(Request $r)
    {
        $groups = Db::name('im_customer_group')
            ->where('cuid', $this->main_id)->select();
        if ($r->isAjax() && $r->isPost()) {
            $style = $r->post('style', 0, 'intval');
            $data = [
                'cuid'  => $this->custs['id'],
                'uname' => $this->custs['uname'],
                'gid'   => $this->custs['group_id'],
                'wname' => $this->main_uname,
                'style' => $style
            ];
            $data['md5'] = md5(http_build_query($data));
            $count = Db::name('im_cation_codes')->where('md5', $data['md5'])->count();
            if (empty($count)) {
                Db::name('im_cation_codes')->insert($data);
            }
            return json([
                'code'   => 200,
                'domain' => $r->domain(),
                'codes'  => $data['md5']
            ]);
        }
        View::assign('groups', $groups);
        return View::fetch();
    }

    /**
     * 聊天网页
     * @return string
     */
    public function access_web_page()
    {
        return View::fetch();
    }

    /**
     * 聊天链接
     * @return string
     */
    public function access_links()
    {
        return View::fetch();
    }

    /**
     * 通用设置
     * @return string
     */
    public function set_general(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $code = 300;
            $msg  = '未知错误';
            $data = $r->post();
            if ($data['action'] == 'open') {
                if (in_array($data['field'], ['prompt', 'clues', 'distr'])) {
                    Db::name('im_general_config')
                        ->where('id', 1)->update([
                            'mess_' . $data['field'] => $data['val']
                        ]);
                    $code = 200;
                    $msg  = '修改成功';
                }
            } elseif ($data['action'] == 'mp3') {
                Db::name('im_general_config')
                    ->where('id', 1)->update([
                        'mess_mp3' => $data['val']
                    ]);
                $code = 200;
                $msg  = '上传成功';
            }
            Cache::delete('options');
            $this->get_options();
            return json(['code' => $code, 'data' => $msg]);
        }

        $general = Db::name('im_general_config')
            ->where('id', 1)->find();
        View::assign('general', $general);
        return View::fetch();
    }

    /**
     * 客服管理
     * @return string
     */
    public function set_service(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $post = $r->post();
            $validate = new SetValidate();

            if (!$validate->scene('addService')->check($post)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            $is_service = Db::name('im_customer')
                ->where('uname', $post['uname'])->count();
            if (!$is_service) {
                $salt = random_user(8);
                $data = [
                    'pid'   => $this->main_id,
                    'avatar'=> $post['avatar'],
                    'uname' => $post['uname'],
                    'upass' => md5($post['upass'].$salt),
                    'salt'  => $salt,
                    'nick'  => $post['nick'],
                    'phone' => $post['phone'],
                    'email' => $post['email'],
                    'web_id'   => $this->main_uname,
                    'group_id' => $post['group_id'],
                    'is_main'  => 0,
                    'create_time' => time()
                ];
                Db::name('im_customer')->insert($data);
                return json(['code' => 200, 'data' => '客服添加成功']);
            } else {
                return json(['code' => 300, 'data' => '用户名重复，请换一个']);
            }
        }

        $service_lists = Db::name('im_customer')
            ->field('c.id,c.uname,c.avatar,c.nick,g.name,c.phone,c.email,c.group_id,c.is_main')
            ->alias('c')->join('we_im_customer_group g','g.id=c.group_id')
            ->where('c.pid', $this->main_id)
            ->whereOr('c.id', $this->main_id)
            ->paginate(10, false, [
                'query' => request()->param(),
                'type' => 'page\Admin',
                'var_page' => 'page'
            ]);

        View::assign([
            'service_lists' => $service_lists
        ]);
        return View::fetch();
    }

    /**
     * 删除客服
     * @return string
     */
    public function del_service(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $cuid = $r->post('cuid', 0, 'intval');
            $is_service = Db::name('im_customer')
                ->where('is_main', 0)->delete($cuid);
            if ($is_service) {
                // 删除相关对话表数据
                Db::name('im_record')->where([
                    'utype' => 'say_to',
                    'send'  => $cuid
                ])->delete();
                // 删除快捷回复表数据
                Db::name('im_fastreply')->where([
                    'cuid'  => $cuid
                ])->delete();
                // 删除快捷回复分组表数据
                Db::name('im_fastreply_group')->where([
                    'cuid'  => $cuid
                ])->delete();
                // 删除当前对话表数据
                Db::name('im_dialogue')->where([
                    'cuid'  => $cuid
                ])->delete();
                return json(['code' => 200, 'data' => '删除成功']);
            } else {
                return json(['code' => 300, 'data' => '删除失败']);
            }
        }
    }

    /**
     * 修改客服管理
     * @return string
     */
    public function edit_service(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $post = $r->post();
            $validate = new SetValidate();

            if (!$validate->scene('editService')->check($post)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            $data = [
                'avatar'=> $post['avatar'],
                'uname' => $post['uname'],
                'nick'  => $post['nick'],
                'phone' => $post['phone'],
                'email' => $post['email'],
                'group_id' => $post['group_id']
            ];
            Db::name('im_customer')->where([
                'id'     => $post['cu_id'],
                'pid'    => $this->main_id,
                'web_id' => $this->main_uname,
            ])->update($data);
            return json(['code' => 200, 'data' => '客服修改成功']);
        }
    }

    /**
     * 客服分组
     */
    public function set_service_group(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data = $r->post();
            $validate = new SetValidate();

            if (!$validate->scene('addGroup')->check($data)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            $where = [
                'name' => $data['group_name'],
                'cuid' => $this->main_id
            ];
            $is_group = Db::name('im_customer_group')->where($where)->count();
            if (!$is_group) {
                Db::name('im_customer_group')->insert($where);
                return json(['code' => 200, 'data' => '添加成功']);
            } else {
                return json(['code' => 300, 'data' => '分组名称重复']);
            }
        }

        $group_lists = Db::name('im_customer_group')
            ->where('cuid', $this->main_id)
            ->paginate(10, false, [
                'query' => request()->param(),
                'type' => 'page\Admin',
                'var_page' => 'page'
            ]);

        View::assign([
            'group_lists' => $group_lists
        ]);
        return View::fetch();
    }

    /**
     * 修改客服分组
     */
    public function set_edit_service_group(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data = $r->post();
            $validate = new SetValidate();

            if (!$validate->scene('editGroup')->check($data)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            $update = [
                'id'   => $data['group_id'],
                'name' => $data['group_name'],
                'cuid' => $this->main_id
            ];
            Db::name('im_customer_group')->update($update);
            return json(['code' => 200, 'data' => '修改成功']);
        }

        $group_lists = Db::name('im_customer_group')
            ->where('cuid', $this->main_id)
            ->paginate(10, false, [
                'query' => request()->param(),
                'type' => 'page\Admin',
                'var_page' => 'page'
            ]);

        View::assign([
            'group_lists' => $group_lists
        ]);
        return View::fetch();
    }

    /**
     * 删除客服分组
     */
    public function set_del_service_group(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data = $r->post();
            $validate = new SetValidate();

            if (!$validate->scene('delGroup')->check($data)) {
                return json(['code' => 300, 'data' => $validate->getError()]);
            }

            // 查询当前主客服是否只剩下一个，如果是则不能删除了
            $customer_group_count = Db::name('im_customer_group')
                ->where('cuid', $this->main_id)->count();
            if ($customer_group_count <= 1) {
                return json(['code' => 300, 'data' => '最少有一个客服分组']);
            }

            $where = [
                'id'   => $data['group_id'],
                'cuid' => $this->main_id
            ];
            Db::name('im_customer_group')->where($where)->delete();
            return json(['code' => 200, 'data' => '删除成功']);
        }
    }

    /**
     * 常见问题
     * @return string
     */
    public function set_problem(Request $r)
    {
        $temp = $r->get('temp', 'set_problem');
        // 添加
        if ($temp == 'add_set_problem') {
            if ($r->isAjax() && $r->isPost()) {
                $post = $r->post();
                $validate = new SetValidate();

                if (!$validate->scene('addProblem')->check($post)) {
                    return json(['code' => 300, 'data' => $validate->getError()]);
                }

                $data = [
                    'ask'     => $post['pro_ask'],
                    'ukeys'   => $post['pro_ukeys'],
                    'sort'    => $post['pro_sort'],
                    'isshow'  => $post['pro_isshow'],
                    'content' => $post['pro_content'],
                    'cuid'    => $this->main_id
                ];
                $iscomask = Db::name('im_comask')->insert($data);
                if ($iscomask) {
                    return json(['code' => 200, 'data' => '添加成功']);
                } else {
                    return json(['code' => 300, 'data' => '添加失败']);
                }
            }
        // 列表
        } elseif ($temp == 'set_problem') {
            $problem_lists = Db::name('im_comask')
                ->where('cuid', $this->main_id)
                ->order('sort desc')
                ->paginate(10, false, [
                    'query' => request()->param(),
                    'type' => 'page\Admin',
                    'var_page' => 'page'
                ]);

            View::assign([
                'problem_lists' => $problem_lists
            ]);
        // 修改
        } elseif ($temp == 'edit_set_problem') {
            if ($r->isAjax() && $r->isPost()) {
                $post = $r->post();
                $validate = new SetValidate();

                if (!$validate->scene('editProblem')->check($post)) {
                    return json(['code' => 300, 'data' => $validate->getError()]);
                }

                $data = [
                    'id'      => $post['pro_id'],
                    'ask'     => $post['pro_ask'],
                    'ukeys'   => $post['pro_ukeys'],
                    'sort'    => $post['pro_sort'],
                    'isshow'  => $post['pro_isshow'],
                    'content' => $post['pro_content'],
                    'cuid'    => $this->main_id
                ];
                $iscomask = Db::name('im_comask')->update($data);
                if ($iscomask) {
                    return json(['code' => 200, 'data' => '修改成功']);
                } else {
                    return json(['code' => 300, 'data' => '修改失败']);
                }
            }

            $pro_id = $r->get('pro_id', 0);
            $problem = Db::name('im_comask')
                ->where('cuid', $this->main_id)
                ->find($pro_id);

            View::assign([
                'problem' => $problem
            ]);
        // 删除
        } elseif ($temp == 'del_set_problem') {
            Db::name('im_comask')->where([
                'id'   => $r->post('pro_id', 0),
                'cuid' => $this->main_id
            ])->delete();
            return json(['code' => 200, 'data' => '删除成功']);
        }

        return View::fetch($temp);
    }

    /**
     * 评价设置
     * @return string
     */
    public function set_evaluation(Request $r)
    {
        $evalu = Db::name('im_evaluation_temp')
            ->where('cuid', $this->main_id)->find();
        if ($r->isAjax() && $r->isPost()) {
            $post = $r->post();
            Db::name('im_evaluation_temp')->update([
                'id'        => $post['evins_id'],
                'evins'     => $post['evins'],
                'evlimit'   => $post['evlimit'],
                'wzev_open' => $post['wzev_open'],
                'wzev_name' => $post['wzev_name'],
                'cuid'      => $this->main_id
            ]);
            return json(['code' => 200, 'data' => '设置成功']);
        }
        if (empty($evalu)) {
            Db::name('im_evaluation_temp')->insert([
                'cuid' => $this->main_id
            ]);
            $evalu = Db::name('im_evaluation_temp')
                ->where('cuid', $this->main_id)->find();
        }
        $evalu['evlimit'] = array_filter(explode(',', $evalu['evlimit']));
        View::assign('evalu', $evalu);
        return View::fetch();
    }

    /**
     * 附件设置
     * @return string
     */
    public function set_attachment()
    {
        View::assign([
            'option_list' => get_typeid_options(1, $this->main_id)
        ]);
        return View::fetch();
    }

    /**
     * 更新配置信息
     */
    public function update_options(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $post = $r->post();
            if (!empty($post['keys']) && isset($post['vals']) && !empty($post['opid'])) {
                Db::name('im_options')
                    ->save([
                        'cuid' => 1,
                        'option_id'    => $post['opid'],
                        'option_ename' => $post['keys'],
                        'option_value' => $post['vals']
                    ]);
                Cache::delete('options');
                $this->get_options();
                return json(['code' => 200, 'data' => '修改成功']);
            } else {
                return json(['code' => 300, 'data' => '修改失败']);
            }
        }
    }
}
