<?php

namespace App\Services;
use App\Models\SetmoneyType;
use BlueCity\Core\Service\Service;
use DB;
use Chumper\Zipper\Zipper;
use Excel;

class ExceloutService extends Service
{
    /**
     * 获取用户可导出字段
     * @param  $id    int     当前用户id
     * @param  $con   string  当前访问控制器名称
     * @return array
     */
    public function gainFields($id,$con)
    {
        $adg_data = DB::table('admin_excel')->where(['adg_admin'=>$id,'adg_action'=>$con])->value('adg_data');
        $adg_data = json_decode($adg_data,true);
        $field_value = [];
        $field_data = [];
        if(!empty($adg_data))
        {
            foreach ($adg_data as $key => $value) {
                $field_value[] = $value['field_value'];
                $field_name[] = $value['field_name'];
            }
            $field_value = implode(",", $field_value);
            $field_data['field_value'] = $field_value;//字段值
            $field_data['field_name'] = $field_name;//字段名
        }
        return $field_data;
    }

    /**
     * @name 创建导出计划
     * @param $list
     * @param $sql
     * @param $limit
     * @param $el_action
     * @param $el_dataname
     * @param $el_adminid
     * @param $el_adminname
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2021/8/23
     */
    public function createPlan($list,$sql,$limit,$el_action,$el_dataname,$el_adminid,$el_adminname,$company_id=''){
        $allnum = count($list);
        $el['el_action'] = $el_action;//'Car';
        $el['el_dataname'] = $el_dataname;//'车型数据';
        $el['el_adminid'] = $el_adminid;//'225';
        $el['el_adminname'] = $el_adminname;//'研发';
        $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'] = $sql;
        $el['el_allnum'] = $allnum;
        $el['company_id'] = $company_id;
        DB::beginTransaction(); //开启事务
        $ed_elid = DB::table("excel_list")->insertGetId($el);
        if($ed_elid){
            $num = 0;
            $nums = 0;
            $tablename = '';
            //$limit=500;
            foreach($list as $k => $v ){
                if($k%$limit==0){
                    $num++;
                    if($num=='1'){
                        $nums++;
                        $tablename = uniqid()."_".$nums.".xls";
                    }if($num=='16'){
                        $num = 0;
                    }
                    $poss['ed_elid'] = $ed_elid;
                    $poss['ed_offset'] = $k;
                    $poss['ed_limit'] = $limit;
                    $poss['ed_excelname'] = $tablename;
                    $res = DB::table("excel_detail")->insert($poss);
                    if(!$res){
                        DB::rollback();//回滚
                        return response()->json(['Data' => '', 'ErrorMessage' => '操作失败204', 'ErrorCode' => 4]);
                    }
                }
            }
            DB::commit();//提交
            return response()->json(['Data' => $ed_elid, 'ErrorMessage' => '操作成功1', 'ErrorCode' => 1]);
        }else{
            DB::rollback();//回滚
            return response()->json(['Data' => '', 'ErrorMessage' => '操作失败203', 'ErrorCode' => 3]);
        }
    }


    /**
     * @name 压缩
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     * @author du
     * @date 2021/8/25
     */
    public function execZip($id){

        $path = DB::table('excel_list')->where('el_id',$id)->where('el_state',2)->value('el_path');

        $zipper = new Zipper();

        $arr = glob(public_path($path));   //$public_path  被压缩的文件名

        $reduce_path = $path.'.zip';

        $zip = new \ZipArchive();

        $zipStatus = $zip->open($reduce_path);

        if ($zipStatus !== true) {

            $zipper->make(public_path($reduce_path))->add($arr)->close();  //public_path($reduce_path)  压缩之后 */

            return response()->json(['ErrorCode' => 3, 'ErrorMessage' => '重新压缩','Data'=>'']);
            exit;
        }
        $reduce_path = $this->baseurl().$reduce_path;
        return response()->json(['Data' =>$reduce_path, 'ErrorMessage' => '压缩地址', 'ErrorCode' => 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;
    }

    //替换表格中的特殊字符
    public function replaceData ($str){
        foreach( $str as $k => $v ){
            $v=str_replace(" 	","",$v);
            $v=str_replace("	","",$v);
            $v=str_replace("\n","",$v);
            $v=str_replace("\r","",$v);
            $str[$k]=$v;
        }
        return $str;
    }

    /**
     * @name 获取数据
     * @param $con
     * @param $res
     * @param $detail
     * @return array|false
     * @author du
     * @date 2021/8/25
     */
    public function getDatas($con,$res,$detail){
        $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'];
            }
        }else{
            return false;
        }
        $group = $field_value;
        $file = $res['el_path']."/".$detail['ed_excelname'];
        if (!file_exists($file)) {
            foreach( $group as $kg => $vg ){
                $num = array_search($vg,$group);
                //echo $num;
                $find_fileds[] = self::getTitleName($excel_name, $vg);
            }
//            dump($find_fileds);
            $strexport = implode("\t",array_values($find_fileds))."\r";
            $strexport = iconv("UTF-8", "GB2312//IGNORE", $strexport);
            file_put_contents($file, $strexport);
//            dump($strexport);
            unset($strexport);
        }
        $db = $this->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 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;
    }

    /**
     * 获取导出SQL数据
     * @param $sqls
     * @return mixed
     * @author du
     * @date 2021/8/26
     */
    public function getSqls($sqls){
        $bindings = $sqls['bindings'];//sql参数
        $sqls = $sqls['query'];//sql语句
        //正则替换
        foreach ($bindings as $replace) {
            $length = explode('T',$replace);
            if(count($length)=='2'){
                if(strlen($length[0])=='10' && strlen($length[1])=='13'){
                    $replace = $length[0]." ".substr($length[1],0,8);
                    $replace = date('Y-m-d H:i:s',strtotime("+8 hours",strtotime($replace)));
                }
            }
            $value = is_numeric($replace) ? $replace : "'" . $replace . "'";
            $sqls = preg_replace('/\?/', $value, $sqls, 1);
        }
        $sqls = explode(' limit ', $sqls)[0];
        $list = DB::select($sqls);
        $data['sqls'] = $sqls;
        $data['list'] = $list;
        return $data;
    }

}
