<?php

namespace App\Services\Business;
use App\Http\Models\Api\Common;
use App\Models\SetmoneyType;
use App\Services\CommonService;
use BlueCity\Core\Service\Service;
use DB;
use Chumper\Zipper\Zipper;

class ExceloutService extends Service
{
    /**
     * 获取用户可导出字段
     * @param  $shop_id   int     门店id
     * @param  adex_role_id   int     角色id
     * @param  $con   string  当前访问控制器名称
     * @return array
     */
    public function gainFields($shop_id,$id,$con)
    {
        $adg_data = DB::table('admin_excel')->where(['adex_shop_id'=>$shop_id,'adex_role_id'=>$id,'adex_action'=>$con])->value('adex_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,$mp_id=0){
        $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_template_id'] = $mp_id;
        $el['el_allnum'] = $allnum;
        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.".csv";
                    }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' => '', 'msg' => '操作失败204', 'code' => 204]);
                    }
                }
            }
            DB::commit();//提交
            return response()->json(['data' => $ed_elid, 'msg' => '操作成功1', 'code' => 200]);
        }else{
            DB::rollback();//回滚
            return response()->json(['data' => '', 'msg' => '操作失败203', 'code' => 203]);
        }
    }


    /**
     * @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(['code' => 203, 'msg' => '重新压缩','data'=>'']);
            exit;
        }
        $reduce_path = $this->baseurl().$reduce_path;
        return response()->json(['data' =>$reduce_path, 'msg' => '压缩地址', 'code' => 202]);

    }


    /**
     * @name 生成表格查询条件
     * @param $db
     * @param $affset
     * @param $limit
     * @return string
     * @author du
     * @date 2021/8/25
     */
    public static function creactWhere ($db,$affset,$limit ){
        $db = rtrim($db,' " ');
        $db = $db." limit ".$affset.",".$limit;
        return $db;
    }

    //替换表格中的特殊字符
    public static 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 static function getDatas($con,$res,$detail, $user_info){
        $admin = DB::table('admin_shop_role')
            ->where(['adm_id'=>$res['el_adminid']])
            ->where(['shop_id'=>$user_info->adm_shop_id])
            ->select('shop_id as adm_shop_id','role_id as adm_role')->first();
        $adg_data = DB::table('admin_excel')->where(['adex_shop_id'=>$admin->adm_shop_id,'adex_role_id'=>$admin->adm_role,'adex_action'=>$con])->value('adex_data');
        $adg_data = json_decode($adg_data,true);
        if (!Empty($adg_data)){
            $excel_person = DB::table('admin_excel_person')
                ->where('amp_shop_id',$admin->adm_shop_id)
                ->where('amp_admin_id',$res['el_adminid'])
                ->where('amp_id',$res['el_template_id'])->value('amp_data');
            if($excel_person){
                $excel_person = json_decode($excel_person,true);
                $adg_data = array_column($adg_data, 'field_value');
                $flag=2;
                foreach ($excel_person as $k => $v) {
                    if(in_array($v['field_value'], $adg_data)) {
                        $flag=1;
                        $field_value[] = $v['field_value'];
                        $excel_name[$v['field_value']] = $v['field_name'];
                    }
                }
                if($flag==2){
                    return false;
                }
            }else {
                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;
        $files = './'.$res['el_path']."/".$detail['ed_excelname'];
        $file = $res['el_path']."/".$detail['ed_excelname'];
        if (!file_exists($files)) {
            foreach( $group as $kg => $vg ){
                $num = array_search($vg,$group);
                //echo $num;
                $find_fileds[] = self::getTitleName($excel_name, $vg);
            }
//            $strexport = implode("\t",array_values($find_fileds))."\r";
//            $strexport = iconv("UTF-8", "GB2312//IGNORE", $strexport);
//            file_put_contents($file, $strexport);
            $files = fopen($files, 'w');
            $header = $find_fileds;
            fputcsv($files, $header);
            fclose($files);
            unset($strexport);
        }
        $db = self::creactWhere($res['el_sql'],$detail['ed_offset'],$detail['ed_limit']);
        $db = ltrim($db,' " ');
        $db = DB::select($db);
        $db = CommonService::dataToArray($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 static 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 static 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;
    }

}
