<?php


namespace App\Exports;


use App\Models\Admin;
use App\Models\SetmoneyType;
use App\Services\DataStatisticsService;
use Chumper\Zipper\Zipper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Services\ExceloutService;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use DB;

class BasicExport
{
    public function creacrExporSerStatistics( $data )
    {
        if(empty($data)){
            return false;
        }
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $session = $data['session'];
        // 设置表头样式
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN, // 边框的样式
                ],
            ],
            'alignment' => [
                // 水平居中
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                // 垂直居中
                'vertical' => Alignment::VERTICAL_CENTER,
                // 自动换行
//                'wrapText' => true
            ],
            'font' => [
                'bold' => true,
                'name' => '微软雅黑',
                'size'=>'12',
                'color' => ['argb' => '000000'],
            ],
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['argb' => 'ACB9CA'],
            ],
        ];
        // 设置内容样式
        $styleDataArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN, // 边框的样式
                ],
            ],
            'alignment' => [
                // 水平居中
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                // 垂直居中
                'vertical' => Alignment::VERTICAL_CENTER,
                // 自动换行
//                'wrapText' => true
            ],
            'font' => [
                'name' => '微软雅黑',
                'size'=>'12',
                'color' => ['argb' => '000000'],
            ],
        ];

        // 合并单元格作为复杂表头
        $sheet->mergeCells('A1:A2');
        $sheet->setCellValue('A1', '序号');
        $sheet->getStyle('A1:A2')->applyFromArray($styleArray);
        $sheet->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        $sheet->mergeCells('B1:B2');
        $sheet->setCellValue('B1', '服务商（公司名称）');
        $sheet->getStyle('B1:B2')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        $sheet->mergeCells('C1:J1');
        $sheet->setCellValue('C1', $data['time']);
        $sheet->getStyle('C1:J1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->setCellValue('C2', '总推送单量');
        $sheet->setCellValue('D2', '接单量');
        $sheet->setCellValue('E2', '拒单量');
        $sheet->setCellValue('F2', '拒单率');
        $sheet->setCellValue('G2', '超十分钟接单量');
        $sheet->setCellValue('H2', '超十分钟比例');
        $sheet->setCellValue('I2', '接单时效');
        $sheet->setCellValue('J2', '履约时效');
        $sheet->getStyle('C2:J2')->applyFromArray($styleArray);
        $sheet->getStyle('C2:J2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        $sheet->mergeCells('K1:R1');
        $sheet->setCellValue('K1', '累计至今');
        $sheet->getStyle('K1:R1')->applyFromArray($styleArray);
        $sheet->getStyle('K1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        $sheet->setCellValue('K2', '总推送单量');
        $sheet->setCellValue('L2', '接单量');
        $sheet->setCellValue('M2', '拒单量');
        $sheet->setCellValue('N2', '拒单率');
        $sheet->setCellValue('O2', '超十分钟接单量');
        $sheet->setCellValue('P2', '超十分钟比例');
        $sheet->setCellValue('Q2', '接单时效');
        $sheet->setCellValue('R2', '履约时效');
        $sheet->getStyle('K2:R2')->applyFromArray($styleArray);
        $sheet->getStyle('K2:R2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        // 填充其他数据
        $num = 3;
        $nums = 1;
        $data = $data['data'];
        foreach($data as $k => $v){
            $sheet->setCellValue('A'.$num, $nums);
            $sheet->setCellValue('B'.$num, $v['company_name']);
            $sheet->setCellValue('C'.$num, $v['all_num']);
            $sheet->setCellValue('D'.$num, $v['order_listnum']);
            $sheet->setCellValue('E'.$num, $v['order_rejectednum']);
            $sheet->setCellValue('F'.$num, $v['rejectRate']);
            $sheet->setCellValue('G'.$num, $v['order_fivenum']);
            $sheet->setCellValue('H'.$num, $v['fiveRate']);
            $sheet->setCellValue('I'.$num, $v['pdAgeing']);
            $sheet->setCellValue('J'.$num, $v['sgAgeing']);
            $sheet->setCellValue('K'.$num, $v['all_nums']);
            $sheet->setCellValue('L'.$num, $v['order_listnums']);
            $sheet->setCellValue('M'.$num, $v['order_rejectednums']);
            $sheet->setCellValue('N'.$num, $v['rejectRates']);
            $sheet->setCellValue('O'.$num, $v['order_fivenallum']);
            $sheet->setCellValue('P'.$num, $v['fiveRates']);
            $sheet->setCellValue('Q'.$num, $v['pdAgeings']);
            $sheet->setCellValue('R'.$num, $v['sgAgeings']);
            $num++;
            $nums++;
        }
        $sheet->getStyle('A3:R'.$num)->applyFromArray($styleDataArray);

        $sheet->getColumnDimension('A')->setWidth(8);
        $sheet->getColumnDimension('B')->setWidth(45);
        $sheet->getColumnDimension('C')->setWidth(12);
        $sheet->getColumnDimension('D')->setWidth(8);
        $sheet->getColumnDimension('E')->setWidth(8);
        $sheet->getColumnDimension('F')->setWidth(10);
        $sheet->getColumnDimension('G')->setWidth(20);
        $sheet->getColumnDimension('H')->setWidth(30);
        $sheet->getColumnDimension('I')->setWidth(30);
        $sheet->getColumnDimension('J')->setWidth(20);
        $sheet->getColumnDimension('K')->setWidth(12);
        $sheet->getColumnDimension('L')->setWidth(8);
        $sheet->getColumnDimension('M')->setWidth(8);
        $sheet->getColumnDimension('N')->setWidth(10);
        $sheet->getColumnDimension('O')->setWidth(30);
        $sheet->getColumnDimension('P')->setWidth(30);
        $sheet->getColumnDimension('Q')->setWidth(20);
        $sheet->getColumnDimension('R')->setWidth(20);
        $sheet -> getDefaultRowDimension() -> setRowHeight(24); //设置默认行高为28
        $sheet->freezePane('A3');//冻结第二行
        $allnum = count($data);
        $el['el_action'] = 'getSerStatistics';//'Car';
        $el['el_dataname'] = '服务商时效统计';//'车型数据';
        $el['el_adminid'] = $session['id'];//'225';
        $el['el_adminname'] = $session['admin_acc'];//'研发';
        $el['el_creactime'] = date("Y-m-d H:i:s");
        $el['el_path'] = 'excel/'.date("Ym").'/'.$el['el_action']."_".uniqid()."_".rand(111,999);
        $el['el_sql'] = '';
        $el['el_state'] = 2;
        $el['el_allnum'] = $allnum;
        $el['el_item'] = $allnum;
        $el['company_id'] = $session['company_id'];
        $ed_elid = DB::table("excel_list")->insertGetId($el);
        $excelname = uniqid().".xlsx";
        $path = $el['el_path'].'/'.$excelname;
        if (!file_exists($el['el_path'])) {
            // 创建文件夹
            mkdir($el['el_path'],0775,true);
            chmod($el['el_path'],0775);
        }
        // 保存Excel文件
        $writer = new Xlsx($spreadsheet);
        $writer->save($path);
        $zipper = new Zipper();
        $arr = glob(public_path($el['el_path']));   //$public_path  被压缩的文件名
        $reduce_path = $el['el_path'].'.zip';
        $zipper->make(public_path($reduce_path))->add($arr)->close();  //public_path($reduce_path)  压缩之后 */
        $zip = new \ZipArchive();
        $zip->open($reduce_path);
        return $ed_elid;
    }
    public function creacrExporHeader( $con,$res,$detail,$freezePane='A2' )
    {
        // 设置表头样式
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN, // 边框的样式
                ],
            ],
            'alignment' => [
                // 水平居中
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                // 垂直居中
                'vertical' => Alignment::VERTICAL_CENTER,
                // 自动换行
//                'wrapText' => true
            ],
            'font' => [
                'bold' => true,
                'name' => '微软雅黑',
                'size'=>'12',
                'color' => ['argb' => '000000'],
            ],
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['argb' => 'ACB9CA'],
            ],
        ];
        // 设置内容样式
        $styleDataArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN, // 边框的样式
                ],
            ],
            'alignment' => [
                // 水平居中
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                // 垂直居中
                'vertical' => Alignment::VERTICAL_CENTER,
                // 自动换行
//                'wrapText' => true
            ],
            'font' => [
                'name' => '微软雅黑',
                'size'=>'12',
                'color' => ['argb' => '000000'],
            ],
        ];
        $adg_data = DB::table('admin_excel')->where(['adg_admin'=>$res['el_adminid'],'adg_action'=>$con])->value('adg_data');
        $adg_data = json_decode($adg_data,true);
        //dump($adg_data);
        if (!Empty($adg_data)){
            foreach ($adg_data as $k =>$v){
                $field_value[] = $v['field_value'];
                $excel_name[$v['field_value']] = $v['field_name'];
                $field_with[$v['field_value']] = $v['field_with'];
            }
        }else{
            return false;
        }
        $group = $field_value;
        $file = $res['el_path']."/".$detail['ed_excelname'];
        if (!file_exists($file)) {
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            $title = self::getHeaderTitle();
            foreach( $group as $kg => $vg ){
                $sheet->setCellValue($title[$kg].'1', self::getTitleName($excel_name, $vg));
                $sheet->getStyle($title[$kg].'1')->applyFromArray($styleArray);
                $sheet->getStyle($title[$kg].'1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
                $sheet->getColumnDimension($title[$kg])->setWidth($field_with[$vg]);
            }
            $sheet -> getDefaultRowDimension() -> setRowHeight(24); //设置默认行高为28
            $sheet->freezePane($freezePane);//冻结第二行
            $writer = new Xls($spreadsheet);
            $writer->save($file);
        }
        $db = self::creactWhere($res['el_sql'],$detail['ed_offset'],$detail['ed_limit']);
        $db = ltrim($db,' " ');
        $db = DB::select($db);
        $data['db'] = $db;
        $data['group'] = $group;
        $data['file'] = $file;
        return $data;
    }
    /**|---------------------------------------------------------------------------------
     * @name 添加表格数据
     * @param string  $file 文件地址
     * @param string  $data 待添加数据
     * @param string  $group 表格权限
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/11/1 17:30
     * |---------------------------------------------------------------------------------
    */
    public function addExceleDara ( $res, $detail, $file, $db, $group ){
        // 设置内容样式
        $styleDataArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN, // 边框的样式
                ],
            ],
            'alignment' => [
                // 水平居中
                'horizontal' => Alignment::HORIZONTAL_CENTER,
                // 垂直居中
                'vertical' => Alignment::VERTICAL_CENTER,
                // 自动换行
//                'wrapText' => true
            ],
            'font' => [
                'name' => '微软雅黑',
                'size'=>'12',
                'color' => ['argb' => '000000'],
            ],
        ];
        if (file_exists($file)) {
            $spreadsheet = IOFactory::load($file);
        } else {
            $spreadsheet = new Spreadsheet();
        }
        $sheet = $spreadsheet->getActiveSheet();
        $highestRow = $sheet->getHighestRow();//获取表格数据行数
//        return $highestRow;
        $num1 = count($db);
        $admindata = Admin::whereRaw("((company_id='".$res['company_id']."' and admin_groupnew=2) or admin_groupnew=3)")
            ->pluck('company_name','id');
        $statusName = ['10'=>'未接单','20'=>'未接单','30'=>'安装中','34'=>'待审核','40'=>'已完成','50'=>'已撤销','55'=>'已撤销（补邮费）'];
        $return = [];
        $title = self::getHeaderTitle();
        foreach( $db as $k => $v ){
            $return[$k]['company_name'] = $admindata[$v['ser_id']];//公司名称
            $return[$k]['order_num'] = $v['order_num'];//订单单号
            $return[$k]['goods_name'] = $v['goods_name'];//商品名称
            $return[$k]['stauas'] = $statusName[$v['stauas']];//订单状态
            $return[$k]['create_time'] = $v['create_time'];//派单时间
            $return[$k]['get_time'] = $v['get_time'];//接单时间
            $return[$k]['feeds_time'] = $v['feeds_time'];//反馈时间
            if($v['get_time'] != '' && $v['get_time'] != '0000-00-00 00:00:00'){
                $return[$k]['jdAgeing'] = DataStatisticsService::Compute_Time($v['jdtime']);//接单时效
                if($v['jdtime']<300){
                    $return[$k]['fiveStandard'] = '达标';//5分钟接单达标
                }else{
                    $return[$k]['fiveStandard'] = '不达标';//5分钟接单达标
                }
                if($v['jdtime']<600){
                    $return[$k]['tenStandard'] = '达标';//10分钟接单达标
                }else{
                    $return[$k]['tenStandard'] = '不达标';//10分钟接单达标
                }
            }else{
                $return[$k]['jdAgeing'] = '';//接单时效
                $return[$k]['fiveStandard'] = '不达标';//5分钟接单达标
                $return[$k]['tenStandard'] = '不达标';//10分钟接单达标
            }

            if($v['feeds_time'] != '' && $v['feeds_time'] != '0000-00-00 00:00:00'){
                $return[$k]['sgAgeing'] = DataStatisticsService::Compute_Time($v['sgtime']);//施工时效
                if($v['sgtime']<43200){
                    $return[$k]['Standard12Hours'] = '达标';//12小时履约达标
                }else{
                    $return[$k]['Standard12Hours'] = '不达标';//12小时履约达标
                }
                if($v['sgtime']<86400){
                    $return[$k]['Standard24Hours'] = '达标';//24小时履约达标
                }else{
                    $return[$k]['Standard24Hours'] = '不达标';//24小时履约达标
                }
                if($v['sgtime']<259200){
                    $return[$k]['Standard72Hours'] = '达标';//72小时履约达标
                }else{
                    $return[$k]['Standard72Hours'] = '不达标';//72小时履约达标
                }
            }else{
                $return[$k]['sgAgeing'] = "";//施工时效
                $return[$k]['Standard12Hours'] = '不达标';//12小时履约达标
                $return[$k]['Standard24Hours'] = '不达标';//24小时履约达标
            }
            $time = explode(' ', $v['create_time'])[1];
            if($time>='08:30:00' && $time<='18:00:00'){
                $return[$k]['takeEffect'] = "是";//是否计入时效考核
            }else{
                $return[$k]['takeEffect'] = "否";//是否计入时效考核
            }
            $return[$k]['shr_sheng'] = $v['shr_sheng'];//省份
            $return[$k]['shr_shi'] = $v['shr_shi'];//城市
            $return[$k]['shr_xian'] = $v['shr_xian'];//区县
            $return[$k]['shr_adress'] = $v['shr_adress'];//详细地址
            $highestRow++;
            foreach( $group as $kg => $vg ){
                if($vg == 'order_num'){
                    $sheet->setCellValue($title[$kg].$highestRow, "\t".$return[$k][$vg]."\t");
                }else{
                    $sheet->setCellValue($title[$kg].$highestRow, $return[$k][$vg]);
                }
                $sheet->getStyle($title[$kg].$highestRow)->applyFromArray($styleDataArray);
//                $sheet->getStyle($title[$kg].$highestRow)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                $sheet->getStyle($title[$kg].$highestRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
            }
        }
        $writer = new Xls($spreadsheet);
        $writer->save($file);
        $el_item = $res['el_item'] + $num1;
        DB::table("excel_list")->where('el_id',$res['el_id'])->update(['el_item'=>$el_item]);
        DB::table("excel_detail")->where("ed_id",$detail['ed_id'])->update(['ed_state'=>2]);

    }
    /**
     * @name 生成表格查询条件
     * @param $db
     * @param $affset
     * @param $limit
     * @return string
     * @author du
     * @date 2021/8/25
     */
    public function creactWhere ($db,$affset,$limit ){
        $db = rtrim($db,' " ');
        $db = $db." limit ".$affset.",".$limit;
        return $db;
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取字段名称
     * @param array $excel_name 订单单号
     * @param string $key 字段key
     * @retrun /multitype:array
     * @author dou 2021/9/14 15:08
     * |---------------------------------------------------------------------------------
     */
    public function getTitleName ( $excel_name = [] , $key ){
        $validation = self::validationKey($key);
        if ( $validation['code'] ){
            if($validation['code'] = 'SetmoneyType'){
                $name = SetmoneyType::where('sety_id',$validation['data'])->value("sety_name");
                if(!$name){
                    $name = '异常';
                }
            }else{
                $name = '异常';
            }
        }else{
            $name = $excel_name[$key]??'异常';
        }
        return $name;
    }
    /**|---------------------------------------------------------------------------------
     * @name 验证标签类参数
     * @param string $key 字段key
     * @retrun /multitype:array
     * @author dou 2021/9/14 15:20
     * |---------------------------------------------------------------------------------
     */
    public function validationKey ( $key ){
        if ( strpos($key,'_titleid') ){
            $data['code'] = 'SetmoneyType';
            $key_length = strlen($key);
            $range_length = strlen('_titleid');
            $key = substr($key,0,$key_length-$range_length);
            $data['data'] = $key;
        }else{
            $data['code'] = false;
        }
        return $data;
    }
    //设置表头列
    public function getHeaderTitle ( ){
        return ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    }
}

