<?php
namespace Base\Domain;

use Base\Model\Countries;
use Base\Model\File;
use Base\Model\WorkOrder as WorkOrderModel;
use PhalApi\Exception\BadRequestException;

class WorkOrder extends Base {

    public static $workOrderStatus = [
        'wailt_status'=>1,  //待受理
        'reply_status'=>2, //待回复
        'resolved_status'=>3, //已解决
        'closed_status'=>4, //已关闭
    ];

    //-----------------------前台

    //获得模块列表接口
    public function getModuleLst(){
        $workOrderConfigArr =   \PhalApi\DI()->config->get('app.work_order_config');

        $result[] = [
            'key'=>0,
            'name'=>\PhalApi\T('全部')
        ];

        if (!empty($result)){
            foreach ($workOrderConfigArr as $k=>$v){
                $reWorkOrderConfig = [
                    'key'=>$k,
                    'name'=>\PhalApi\T($v)
                ];
                $result[] = $reWorkOrderConfig;
            }
        }

        return  $result;
    }

    //获取全部区号
    public function getAreaCodeLst(){
       $result = Countries::model()->getAllList();
       return empty($result)?[]:$result;
    }


    //添加
    public function add($title, $moduleId, $problemDesc, $phone, $fileIds = '', $email, $phonePre){

        //api模块判断
        $workOrderConfigArr =  \PhalApi\DI()->config->get('app')['work_order_config'];
        if (empty($workOrderConfigArr[$moduleId])){
            throw new BadRequestException('模块不存在，请检查参数');
        }

        $newData = array(
            'title' => $title,
            'module_id' => $moduleId,
            'problem_desc' => $problemDesc,
            'phone'=>$phone,
            'chat_recode'=>'',
            'order_no'=>time(),
            'email'=>$email,
            'phone_pre'=>$phonePre
        );

        if (!empty($fileIds)){
           $fileIdArr = explode(',', $fileIds);
           $fileIdArr  = array_filter($fileIdArr);

           if (!empty($fileIdArr)){
               $fileIdStrS = implode(',',$fileIdArr);
               $newData['file_ids'] = $fileIdStrS;
           }
        }else{
            $newData['file_ids'] = '';
        }

        //基本数据
        $newData = $this->prepareNewData($newData, true);

        $id = WorkOrderModel::model()->insert($newData);
        return $id;
    }

    //列表
    public function lst($searchWord = array(), $page = 1, $perpage = 100,$sortTime = 0){
        $where = $this->prepareWhere(['admin_id'=>$this->uid]);
        $where = array_merge($where,$searchWord);

        $orderWhere = empty($sortTime)?'update_time DESC':'update_time ASC';

        $rs = WorkOrderModel::model()->getListEx($where, [], '*', $orderWhere, $page, $perpage);  //分页来的

        $this->module_name_add($rs['items']);

        return $rs;
    }

    //详情
    public function detail($id){
        $where = $this->prepareWhere(array('id' => $id, 'admin_id'=>$this->uid));
        $product = WorkOrderModel::model()->getData($where);

        if (empty($product)){
            return [];
        }

        //查询附件表
        $product['file_arr'] = [];
        if (!empty($product['file_ids'])){
            $product['file_arr']  = File::model()->getList(['id'=>explode(',', $product['file_ids'])]);
            foreach ($product['file_arr'] as $k=>&$v){
              $file_type_simple = explode('/',$v['file_type']);
              $v['file_type_simple'] = $file_type_simple[0];
            }
        }

        //聊天记录
        $product['chat_recode'] = empty( $product['chat_recode']) ? '' :json_decode($product['chat_recode'], true);
        $this->module_name_add($product);

        return $product;
    }

    //局部更新
    public function updateChatRecodeWorkOrder($id, $chatRecode = '', $status = 0,$chatRecodeFile = '') {
        if (!empty($chatRecode)){
            //写入变更数据
            //先读出来
            $info = $this->detail($id);
            if (empty($info)){
                throw new BadRequestException('该id不存在请检查参数');
            }

            $chatRecodeArr =  empty($info['chat_recode'])?[]:$info['chat_recode'];

            $ownUserInfo =  (new User())->profileByUid($this->uid);
            $chat_recode = [
                'name'=>$ownUserInfo['nickname'],
                'date'=>date('Y-m-d H:i:s'),
                'avatar'=>$ownUserInfo['avatar'],
                'mobile'=>$ownUserInfo['mobile'],
                'chat_recode' => $chatRecode
            ];

            //回复附件
            if (!empty($chatRecodeFile)){
                $chatRecodeFile= json_decode($chatRecodeFile, true);
                if (!is_array($chatRecodeFile)){
                    throw new BadRequestException('回复附件参数不是json格式');
                }
//                $chatRecodeFile =  json_decode($chatRecodeFile, true);
                foreach ($chatRecodeFile as $k=>$v){
                    $chat_recode_file = [];
                    $chat_recode_file['file_type'] = 'application';
                    $ext = explode('.',$v);
                    $ext = array_reverse($ext);
                    if (in_array($ext[0],['jpg','png','jpeg'])){
                        $chat_recode_file['file_type'] = 'image';
                    }
                    $chat_recode_file['web_url'] = $v;

                    $chat_recode['chat_recode_file_arr'][] = $chat_recode_file;
                }
            }else{
                $chat_recode['chat_recode_file_arr'] = [];
            }

            $chatRecodeArr[] = $chat_recode;

            $updateChatRecod = [
                'chat_recode' => json_encode($chatRecodeArr),
                'update_time'=>date('Y-m-d H:i:s')
            ];
        }

        //已解决
        if (($info['status'] != self::$workOrderStatus['closed_status']) && in_array($status,[3])){
            $updateChatRecod['status'] = $status;
            $updateChatRecod['update_time'] = date('Y-m-d H:i:s');;
        }

        if (!empty($updateChatRecod)){
            WorkOrderModel::model()->update($id, $updateChatRecod);
        }

        return true;
    }

    //代办工单统计
    public function wailtcount(){
      return  WorkOrderModel::model()->count(['admin_id'=>$this->getUid(),'status'=>[1,2]]);
    }

    //---------------------后台
    //后台工单列表
    public function adminWorkOrderLst($searchWord = array(), $page = 1, $perpage = 100){
        $rs = WorkOrderModel::model()->getListEx($searchWord, [], '*', 'id DESC', $page, $perpage);  //分页来的

        $this->module_name_add($rs['items']);
        return $rs;
    }

    //后台工单详情
    public function adminDetail($id){
        $product = WorkOrderModel::model()->getData(array('id' => $id));

        if (empty($product)){
            return [];
        }

        //查询附件表
        $product['file_arr'] = [];
        if (!empty($product['file_ids'])){
            $product['file_arr']  = File::model()->getList(['id'=>explode(',', $product['file_ids'])]);
            foreach ($product['file_arr'] as $k=>&$v){
                $file_type_simple = explode('/',$v['file_type']);
                $v['file_type_simple'] = $file_type_simple[0];
            }
        }

        //聊天记录
        $product['chat_recode'] = empty( $product['chat_recode']) ? '' :json_decode($product['chat_recode'], true);

        $this->module_name_add($product);
        return $product;
    }

    //后台局部更新
    public function updateChatRecodeWorkOrderAdmin($id, $status=0, $chatRecode, $chatRecodeFile = []) {

        //写入变更数据
        //先读出来
        $info = $product = WorkOrderModel::model()->getData(['id'=> $id]);
        if (empty($info)){
            throw new BadRequestException('该id不存在请检查参数');
        }

        //更新数据
        $updateChatRecod = [];
        //更新聊天记录
        if (!empty($chatRecode)){
            $chatRecodeArr =  empty($info['chat_recode'])?[]:json_decode($info['chat_recode'], true);

            $ownUserInfo =  (new User())->profileByUid($this->uid);
            $chat_recode = [
                'name'=>$ownUserInfo['nickname'],
                'date'=>date('Y-m-d H:i:s'),
                'avatar'=>$ownUserInfo['avatar'],
                'mobile'=>$ownUserInfo['mobile'],
                'chat_recode' => $chatRecode
            ];

            //回复附件
            if (!empty($chatRecodeFile)){
                $chatRecodeFile =  json_decode($chatRecodeFile, true);
                if (!is_array($chatRecodeFile)){
                    throw new BadRequestException('回复附件参数不是json格式');
                }

                foreach ($chatRecodeFile as $k=>$v){
                    $chat_recode_file = [];
                    $chat_recode_file['file_type'] = 'application';
                    $ext = explode('.',$v);
                    $ext = array_reverse($ext);
                    if (in_array($ext[0],['jpg','png','jpeg'])){
                        $chat_recode_file['file_type'] = 'image';
                    }

                    $chat_recode_file['web_url'] = $v;

                    $chat_recode['chat_recode_file_arr'][] = $chat_recode_file;
                }
            }else{
                $chat_recode['chat_recode_file_arr'] = [];
            }

            $chatRecodeArr[] = $chat_recode;

            $updateChatRecod = [
                'chat_recode' => json_encode($chatRecodeArr),
                'update_time'=>date('Y-m-d H:i:s')
            ];

            //只要管理员回复，1标为2 ---并且设置该管理员为客户
            if (empty($status) && ($info['status'] == self::$workOrderStatus['wailt_status'])){
                $status = self::$workOrderStatus['reply_status'];
                //受理的客服
                $updateChatRecod['accept_service_id'] = $this->getUid();
                $updateChatRecod['accept_service_name'] = (new User())->getUsername($this->getUid());
            }

        }

        if (!empty($status)){
            $updateChatRecod['status'] = $status;
            $updateChatRecod['update_time'] = date('Y-m-d H:i:s');
        }

        if (!empty($updateChatRecod)){
            WorkOrderModel::model()->update($id, $updateChatRecod);
        }

        return true;
    }


    //---------------------------通用

    //给返回的字段添加模块名
    protected function module_name_add(&$data){
       $workOrderConfigArr = \PhalApi\DI()->config->get('app')['work_order_config'];
        if ($data){
            foreach ($data as $k=>&$v){
                if (is_array($v) && is_numeric($k)){
                    $v['module_name'] = empty($workOrderConfigArr[$v['module_id']])?'':\PhalApi\T($workOrderConfigArr[$v['module_id']]);
                }else{
                    if ($k == 'module_id'){
                        $data['module_name'] = empty($workOrderConfigArr[$v])?'':\PhalApi\T($workOrderConfigArr[$v]);
                    }
                }

            }
        }
    }
}
