<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Maintain as Maintainmodel;
use think\Db;
/**
 * 保修
 */
class Maintain extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    //报修
    public function addone()
    {
        $info     = input('info','');
        $filedata = input('filedata','','htmlspecialchars_decode');
        $mobile   = input('mobile','');
        $address  = input('address','');

        //视频类型追加缩略图
        if(!empty($filedata)){
            $filedata = json_decode($filedata,true);
            if(is_array($filedata) && !empty($filedata)){
                foreach($filedata as $key => $file){
                    if($file['type'] == 'video'){
                        $file_url = explode('.', $file['url']);
                        unset($file_url[count($file_url) - 1]);
                        $file['images_thumb'] = implode('.', $file_url) . '_0.jpg';
                    }else{
                        $file['images_thumb'] = $file['url'];
                    }
                    $filedata[$key] = $file;
                }
                $filedata = json_encode($filedata);
            }else{
                $filedata = '';
            }
        }else{
            $filedata = '';
        }

        $nowtime = time();

        //
        if(empty($this->auth->company_id)){
            $this->error('您还没绑定维保公司');
        }
        $uc_id = Db::name('user_company')->where('user_id',$this->auth->id)->where('company_id',$this->auth->company_id)->value('id');
        if(empty($uc_id)){
            $this->error('您还没绑定维保公司');
        }

        //写入
        $data = [
            'orderno' => createUniqueNo('',''),
            'user_id' => $this->auth->id,
            'company_id' => $this->auth->company_id,
            'uc_id' => $uc_id,
            'createtime' => $nowtime,
            'updatetime' => $nowtime,
            'info' => $info,
            'filedata' => $filedata,
            'mobile' => $mobile,
            'address' => $address,
            'status' => 0,
        ];

        $order_id = Db::name('maintain')->insertGetId($data);
        $this->success('提交成功', $order_id);
    }

    //列表
    public function lists(){
        //待审核,0
        //报价中,20,22
        //报价确认,30
        //维修中,40,50,60,70,80,90,92
        //已完成,100
        $status = input('status',0); //默认待审核

        $map = [
            'user_id' => $this->auth->id,
            'status'  => $status,
        ];

        if($status == 20){
            $map['status'] = ['IN',[20,22]];
        }
        if($status == 40){
            $map['status'] = ['IN',[40,50,60,70,80,90,92]];
        }

        $field = ['id','orderno','createtime','info','filedata','status','eva_time'];
        $list = Db::name('maintain')->field($field)
            ->where($map)->order('id desc')
            ->autopage()->select();
        if(!empty($list)){

            //负责人的电话
            $header_mobile = Db::name('user_company')->where('user_id',$this->auth->id)->value('header_mobile');

            $maintain_model = new Maintainmodel();
            foreach($list as $key => $val){
                $list[$key]['header_mobile'] = $header_mobile;
                $list[$key]['status_text'] = $maintain_model->status_data($val['status']);
            }
        }

        $this->success(1,$list);
    }

    //详情
    public function info(){
        $id = input('id',0);

        $map = [
            'user_id' => $this->auth->id,
            'id'      => $id,
        ];

        $field = ['id','orderno','createtime','info','filedata','mobile','address','status','finishtime','worker_id','shangmen_time','eva_info','eva_time','eva_score','weixiu_id'];
        $info = Db::name('maintain')->field($field)
            ->where($map)
            ->find();

        if(empty($info)){
            $this->error('没找到该订单');
        }

        $maintain_model = new Maintainmodel();
        $info['status_text'] = $maintain_model->status_data($info['status']);

        //负责人的电话
        $header_mobile = Db::name('user_company')->where('user_id',$this->auth->id)->value('header_mobile');
        $info['header_mobile'] = $header_mobile;

        //追加维修师傅
        $info['worker_info'] = [];

        if($info['worker_id'] != 0){
            $worker_info = Db::name('worker')->field('avatar,truename,mobile')->where('id',$info['worker_id'])->find();
            if(!empty($worker_info)){
                $worker_info['avatar'] = localpath_to_netpath($worker_info['avatar']);
                $info['worker_info'] = $worker_info;
            }
        }

        //追加进度
        //追加多次维修+对应进度历史
        $last_jindulist = [];
        $new_jindulist = [];
        $jindu_list = Db::name('maintain_jindu')->alias('jd')
            ->join('worker','jd.worker_id = worker.id','LEFT')
            ->field('jd.id,jd.worker_id,jd.weixiu_times,jd.title,jd.images,jd.createtime,worker.avatar,worker.truename')
            ->where('jd.order_id',$id)
            ->order('jd.id desc')->select();
        $jindu_list = list_domain_image($jindu_list,['avatar','images']);
        if(!empty($jindu_list)){
            for($i=$jindu_list[0]['weixiu_times'];$i>=1;$i--){
                foreach($jindu_list as $key => $val){
                    if($i == $val['weixiu_times']){
                        $new_jindulist[$i][] = $val;
                    }
                }
            }
            foreach($new_jindulist as $key => $val){
                $last_jindulist[] = [
                    'title' => '第'.$val[0]['weixiu_times'].'次',
                    'child' => $val
                ];
            }
        }
        $info['jindu'] = $last_jindulist;

        $this->success(1, $info);
    }

    //取消上报
    public function cancel(){
        $id = input('id',0);

        $map = [
            'user_id' => $this->auth->id,
            'id'      => $id,
        ];

        $info = Db::name('maintain')
            ->where($map)
            ->find();
        if(empty($info)){
            $this->error('不存在的订单');
        }

        if($info['status'] >= 40){ //报价都审核过了,可派师傅了
            $this->error('现在已经不能取消了');
        }

        $nowtime = time();
        $update = [
            'status' => 2,
            'canceltime' => $nowtime, //取消时间
            'finishtime' => $nowtime,
            'updatetime' => $nowtime,
        ];
        $rs = Db::name('maintain')
            ->where($map)->update($update);

        $this->success('取消成功');
    }

    //报价详情
    public function baojia_info(){
        $order_id = input('order_id',0);
        //找出最新报价日志
        $baojia_log = Db::name('maintain_baojia')->field('id,baojia_filename,baojia_file')->where('order_id',$order_id)->where('status',30)->order('id desc')->find();
        $baojia_log = info_domain_image($baojia_log,['baojia_file']);

        $this->success(1,$baojia_log);
    }

    //报价确认
    public function baojia_confirm(){
        $id = input('order_id',0);

        Db::startTrans();

        //检查订单
        $map = [
            'user_id' => $this->auth->id,
            'id'      => $id,
        ];
        $info = Db::name('maintain')->where($map)->lock(true)->find();
        if(empty($info)){
            Db::rollback();
            $this->error('不存在的订单');
        }
        if($info['status'] != 30){ //用户待确认
            Db::rollback();
            $this->success('订单错误,请刷新重试');
        }

        //找出最新报价日志
        $baojia_log = Db::name('maintain_baojia')->where('order_id',$id)->where('status',30)->order('id desc')->find();

        $nowtime = time();

        //更新订单
        $update = [
            'status' => 40,
            'updatetime' => $nowtime,
            'baojia_confirmtime' => $nowtime,  //报价确认时间
        ];

        //更新报价记录
        $update_baojia = [
            'status' => 40,
            'updatetime' => $nowtime,

            'baojia_useraudit_time' => $nowtime,
        ];

        $rs1 = Db::name('maintain')->where('id',$id)->update($update);
        if($rs1 === false){
            Db::rollback();
            $this->error('确认失败');
        }

        $rs2 = Db::name('maintain_baojia')->where('id',$baojia_log['id'])->update($update_baojia);
        if($rs2 === false){
            Db::rollback();
            $this->error('确认失败');
        }

        Db::commit();
        $this->success('报价已确认');
    }

    //验收
    public function yanshou(){
        $id = input('order_id',0);
        $status = input('status',2);//1=通过,2=拒绝
        $reason = input('reason','','trim');

        //必填
        if($status == 2 && empty($reason)){
            $this->error('请输入拒绝原因');
        }

        Db::startTrans();

        //检查订单
        $map = [
            'user_id' => $this->auth->id,
            'id'      => $id,
        ];
        $info = Db::name('maintain')->where($map)->lock(true)->find();
        if(empty($info)){
            Db::rollback();
            $this->error('不存在的订单');
        }
        if($info['status'] != 90){ //师傅完成
            Db::rollback();
            $this->success('订单错误,请刷新重试');
        }

        $nowtime = time();

        //更新订单
        //更新维修
        if($status == 2){
            $update = [
                'status' => 92,  // '用户验收驳回'
                'updatetime' => $nowtime,
                'finishtime' => $nowtime,
            ];
            $update_weixiu = [
                'status' => 92,  // '用户验收驳回'
                'updatetime' => $nowtime,

                'audit_time' => $nowtime,
                'audit_reason' => $reason,
            ];

            $remark = '验收已驳回';
            $jindutitle = $remark.':'.$reason;
        }else{
            $update = [
                'status' => 100, //用户验收通过
                'updatetime' => $nowtime,
                'finishtime' => $nowtime,
            ];
            $update_weixiu = [
                'status' => 100, //用户验收通过
                'updatetime' => $nowtime,

                'audit_time' => $nowtime,
            ];

            $jindutitle = $remark = '验收已通过';
        }

        //最后一个轮回,追加验收进度
        $jindu = [
            'order_id'   => $info['id'],
            'company_id' => $info['company_id'],
            'user_id'    => $info['user_id'],
            'worker_id'  => $info['worker_id'],

            'weixiu_times' => $info['weixiu_times'],
            'weixiu_id'    => $info['weixiu_id'],

            'title'       => $jindutitle,
            'createtime'  => $nowtime,
        ];
        $jindu_id = Db::name('maintain_jindu')->insertGetId($jindu);
        if(!$jindu_id){
            Db::rollback();
            $this->error('验收失败');
        }

        $rs1 = Db::name('maintain')->where('id',$id)->update($update);
        if($rs1 === false){
            Db::rollback();
            $this->error('验收失败');
        }

        $rs2 = Db::name('maintain_weixiu')->where('id',$info['weixiu_id'])->update($update_weixiu);
        if($rs2 === false){
            Db::rollback();
            $this->error('验收失败');
        }

        Db::commit();
        $this->success($remark);
    }

    //评价
    public function evaluate(){
        $id = input('order_id',0);
        $eva_info  = input('eva_info','');
        $eva_score = input('eva_score',5);

        //检查订单
        $map = [
            'user_id' => $this->auth->id,
            'id'      => $id,
        ];
        $info = Db::name('maintain')->where($map)->find();
        if(empty($info)){
            $this->error('不存在的订单');
        }
        if($info['status'] != 100){
            $this->success('订单未验收通过,请刷新重试');
        }
        if($info['eva_time'] != 0){
            $this->success('订单已评价,无需重复评价');
        }

        //更新
        $update = [
            'eva_info'  => $eva_info,
            'eva_score' => $eva_score,
            'eva_time'  => time(),
        ];
        $rs1 = Db::name('maintain')->where('id',$id)->update($update);

        //维保公司的平均分修改

        $this->success('评价完成');
    }




}