<?php

/**
|--------------------------------------------------------------------------
 * 售后服务
|--------------------------------------------------------------------------
| 售后服务处理逻辑
 * @author DouBin
 * @Date: 2021/08/05
 * @Time: 上午 10:16
 * @Email: db@sudianwang.com
 * @version 1.0
 * @copyright BlueCity
 */
namespace App\Services;
use App\Exports\AfterCustExport;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use Cassandra\Date;
use Illuminate\Support\Facades\Log;
use App\Models\Aftercust;
use DB;
use Maatwebsite\Excel\Facades\Excel;
use phpDocumentor\Reflection\Types\False_;


class AftercustService extends Service
{
    public static $instance;
    public $modelMain = null;

    public function __construct()
    {
        $this->modelMain = new Aftercust();
    }

    /**
     * 根据条件搜索数据内容
     *
     * @param array $where 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function search($where, $columns = array('*'), $page = 1, $pageSize = 20)
    {
        $offset = ($page - 1) * $pageSize;
        $query = Aftercust::leftJoin('admin', 'admin.id', '=', 'aftercust.afc_serid')
            ->leftJoin('pt', 'pt.id', '=', 'aftercust.afc_pid')
            ->leftJoin('user', 'user.id', 'aftercust.afc_user');

        $count = $query->where($where)->count();

        $totalPage = 1;
        if ($pageSize > 0) {
            $totalPage = ceil($count / $pageSize);
            $offset = ($page - 1) * $pageSize;

            $list = $query->select('afc_id', 'afc_sys', 'afc_order', 'afc_serial', 'afc_pid', 'afc_ordertime', 'afc_gid', 'afc_price', 'afc_num', 'afc_user', 'afc_serid', 'afc_creactime', 'afc_creacter', 'afc_refund', 'afc_dealtime', 'afc_dealer', 'afc_state', 'afc_creactid', 'afc_dealid', 'afc_centent', 'afc_dealcenent', 'afc_goodname', 'afc_code', 'afc_orderstatus', 'company_name', 'pt_name', 'shr_name', 'shr_phone', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress')
                ->where($where)
                ->orderBy('afc_sort','DESC')
                    ->orderBy('afc_id','DESC')
                ->offset($offset)
                ->limit($pageSize)
                ->get();

        } else {
            $list = $query->select('afc_id', 'afc_sys', 'afc_order', 'afc_serial', 'afc_pid', 'afc_ordertime', 'afc_gid', 'afc_price', 'afc_num', 'afc_user', 'afc_serid', 'afc_creactime', 'afc_creacter', 'afc_refund', 'afc_dealtime', 'afc_dealer', 'afc_state', 'afc_creactid', 'afc_dealid', 'afc_centent', 'afc_dealcenent', 'afc_goodname', 'afc_code', 'afc_orderstatus', 'company_name', 'pt_name', 'shr_name', 'shr_phone', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress')
                ->where($where)
                ->limit(20)
                ->orderBy('afc_sort','DESC')
                ->orderBy('afc_id','DESC')
                ->get();
        }
        $result = [];
        $result['page'] = ['totalPage' => $totalPage, 'count' => $count, 'page' => $page, 'page_size' => $pageSize];
        $result['list'] = $list;

        return $result;
    }

    public static function searchNum($where) {
        $showMenu = [
            ['show_name' => "未处理",'status'=>'1', 'show_num' => "--"],
            ['show_name' => "需跟进",'status'=>'2', 'show_num' => "--"],
            ['show_name' => "待审核", 'status'=>'3','show_num' => "--"],
            ['show_name' => "已完成", 'status'=>'4','show_num' => "--"],
        ];
        $query = Aftercust::leftJoin('admin', 'admin.id', '=', 'aftercust.afc_serid')
            ->leftJoin('pt', 'pt.id', '=', 'aftercust.afc_pid')
            ->leftJoin('user', 'user.id', 'aftercust.afc_user');

        $showNum = $query->selectRaw("afc_state,count('afc_id') as num")
            ->where('afc_state', '!=', 4)
            ->groupBy('afc_state')
            ->get();

        if (!$showNum->isEmpty()) {
            $showNum = $showNum->toArray();
            foreach ($showNum as $k => $v) {
                if ($v['afc_state'] == 1) {
                    $state1 = $v['num'];
                }
                if ($v['afc_state'] == 2) {
                    $state2 = $v['num'];
                }
                if ($v['afc_state'] == 3) {
                    $state3 = $v['num'];
                }
                //if($v['afc_state']==4){$state4=$v['num'];}
            }
            $wcl = $state1 ?? '0';//未处理
            $xgj = $state2 ?? '0';//需跟进
            $dsh = $state3 ?? '0';//待审核
            //$ywc = $state4??'0';//已完结
            $showMenu = [
                ['show_name' => "未处理",'status'=>'1', 'show_num' => $wcl],
                ['show_name' => "需跟进", 'status'=>'2','show_num' => $xgj],
                ['show_name' => "待审核",'status'=>'3', 'show_num' => $dsh],
                ['show_name' => "已完成", 'status'=>'4','show_num' => "--"],
            ];
        }

        return $showMenu;
    }

    public function formatPageContent($token, $priID, $data , $login_id = '')
    {
        $all_button = BmmcService::wherebutton($token, $priID );
        $addPt = BmmcService::getTopButton('export,updatedata', '', $all_button);
        $data['button_top'] = $addPt['button_top'] ?? [];//顶部按钮
        $data['button_search'] = $addPt['button_search'] ?? [];//搜索栏按钮
        $list = $data['list'];
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            $typeName = self::getTypeName(true);
            $stateNma = self::getStateName(true);
            $orderStateName = OrderService::getOrderStatusName();
            foreach ($list as $k => $v) {
                // -----------button 处理开始-----------
                $buttonData = [];
                if ($v['afc_state'] == 1 && $v['afc_refund'] == 1) {
                    $buttonData[] = 'remarks,Deals';
                } elseif ($v['afc_state'] == 2 && $v['afc_refund'] == 1) {
                    $buttonData[] = 'remarks,Deals,Audits';
                } elseif ($v['afc_state'] == 3 && $v['afc_refund'] == 1) {
                    $buttonData[] = 'remarks,Audits,updatecl';
                } elseif ($v['afc_state'] == 4 && $v['afc_refund'] == 1) {
                    $buttonData[] = 'remarks,updatecl';
                }
                if ($v['afc_state'] == 1 && $v['afc_refund'] > 1) {
                    $buttonData[] = 'remarks,refundprocc';
                }
                $button = BmmcService::getListButton($buttonData,$all_button);
                $list[$k]['button_one'] = $button['button_one'] ?? [];
                $list[$k]['button_two'] = $button['button_two'] ?? [];
                $list[$k]['button_three'] = $button['button_three'] ?? [];
                // -----------button 处理结束-----------


                $list[$k]['type_name'] = $typeName[$v['afc_refund']]??'未定义';
                $list[$k]['afc_state_name'] = $stateNma[$v['afc_state']]??'状态未定义';
                $list[$k]['status'] = $orderStateName[$v['afc_orderstatus']]??'订单状态未定义';
                $list[$k]['reminder_num'] = SerInforService::getSerInforBy('sin_ordernum', $v['afc_order'],'sin_id','count');
                $list[$k]['id'] = $v['afc_id'];
                $list[$k]['sys_num'] = $v['afc_sys'];
                //}
            }

            $data['list'] = $list;
        } else {
            $data['list'] = [];
        }

        return $data;
    }

    /**
	 * 添加
	 * @param  $afc_sys
	 * @param  $afc_order
	 * @param  $afc_pid
	 * @param  $afc_ordertime
	 * @param  $afc_gid
	 * @param  $afc_price
	 * @param  $afc_num
	 * @param  $afc_user
	 * @param  $afc_serid
	 * @param  $afc_creacter
	 * @param  $afc_creactid
	 * @param  $afc_centent
	 * @param  $afc_goodname
	 * @param  $afc_orderstatus
	 * @param  $afc_refund
	 * @return int
	 * @author du 2021年8月10日下午4:02:22
	 */
	public static function createAftercust($afc_sys,$afc_order,$afc_pid,$afc_ordertime,$afc_gid,$afc_price,$afc_num,$afc_user,$afc_serid,$afc_creacter,$afc_creactid,$afc_centent,$afc_goodname,$afc_orderstatus,$afc_refund){
		$poss['afc_sys'] = $afc_sys;
		$poss['afc_order'] = $afc_order;
		$poss['afc_pid'] = $afc_pid;
		$poss['afc_ordertime'] = $afc_ordertime;
		$poss['afc_gid'] = $afc_gid;
		$poss['afc_price'] = $afc_price;
		$poss['afc_num'] = $afc_num;
		$poss['afc_user'] = $afc_user;
		$poss['afc_serid'] = $afc_serid;
		$poss['afc_creactime'] = date("Y-m-d H:i:s");
		$poss['afc_creacter'] = $afc_creacter;
		$poss['afc_creactid'] = $afc_creactid;
		$poss['afc_centent'] = $afc_centent;
		$poss['afc_goodname'] = $afc_goodname;
		$poss['afc_orderstatus'] = $afc_orderstatus;
		$poss['afc_refund'] = $afc_refund;
        $poss['afc_code'] = 'G' . date("Ymdhis") . str_pad(rand(0, 999), 3, '0', STR_PAD_LEFT);
		$res = Aftercust::insertGetId($poss);
		return $res;
	}


    /**
     * 获取售后单信息
     * @param array $params 请求参数
     * @param string $key 返回键
     * @param array $select 返回键
     * @param string $type 返回键
     * @return mixed:array
     * @author dou 2021年8月5日
     */
    public static function getAfterCustData ( $params , $key = '' , $select = [] , $type = ''){
        $db = new Aftercust();
        $data = CommonService::getMysqlData($db,$params,$select,['afc_id'=>'ASC']);
        if($key){
            if(!$type){
                if($key == 'afc_id'){
                    $type = 1;
                }else{
                    $type = 2;
                }
            }
            $data = CommonService::jointArrayKey($data, $key , $type);
        }
        return $data;
    }

    public static function exportCollection() {
        return AfterCustExport::getColumns();
    }

    public function export($data, $fields, $fileName, $fileExt = '.xlsx') {
        $filePath = $fileName.$fileExt;
        $filePath = 'DHGT/' . date('Ym') .'/'.$filePath; //电话沟通的独有目录
        $excel = new AfterCustExport($data, $fields);
//        $excel->setColumnWidth(['A' => 10, 'B' => 20, 'C' => 30, 'D' => 10, 'E' => 20, 'F' => 20, 'G' => 20, 'H' => 20]);//设置第一行标题宽度
//        $excel->setRowHeight([1 => 25]);    //设置第一行标题高度
//        $excel->setFont(['A1:P1' => '微软雅黑']); //设置标题字体
//        $excel->setBold(['A1:P1' => true]);//设置标题加粗显示
//        $excel->setFontSize(['A1:C1' => 12, 'A2:Z5' => 10]);
//        $excel->setColors(['A1:D1' => 'FF0000']);
//        $excel->setBackground(['A1:A1' => '808080', 'C1:C1' => '708080']);
//        $excel->setMergeCells(['A1:I1']);
//        $excel->setBorders(['A2:D5' => 'FF0000']);

        if (Excel::store($excel, $filePath)) {
            return $filePath;
        } else {
            return false;
        }
    }

    public static function updateByKey($key, $value, $data) {
        return Aftercust::where($key, $value)->update($data);
    }

    public static function updateByWhere($where, $data) {
        return Aftercust::where($where)->update($data);
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取沟通类型名称
     * @retrun /multitype:array
     * @author dou 2021/10/19 17:06
     * |---------------------------------------------------------------------------------
    */
    public static function getTypeName ( $type = false ){
        $typeName = array(array('type'=>'1','name'=>'安装问题'),array('type'=>'2','name'=>'退款回访'),array('type'=>'3','name'=>'催单回访'),array('type'=>'4','name'=>'预约回访'),array('type'=>'5','name'=>'安装问题'));
        if($type == 1){
            $typeName = array_column($typeName, 'name','type');
        }
        return $typeName;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取处理类型名称
     * @retrun /multitype:array
     * @author dou 2021/10/19 17:24
     * |---------------------------------------------------------------------------------
    */
    public static function getStateName ( $type = false ){
        $stateNma = array(array('type'=>'1','name'=>'未处理'),array('type'=>'2','name'=>'需跟进'),array('type'=>'3','name'=>'待审核'),array('type'=>'4','name'=>'已完成'));
        if($type == 1){
            $stateNma = array_column($stateNma, 'name','type');
        }
        return $stateNma;
    }

}
