<?php

namespace App\Http\Models\Services;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class ImageUpload extends Model
{
	protected $table = 'shop_image_template';//与模型关联的数据表
    protected $primaryKey = 'shit_id';//主键id
    public $timestamps = false;//该模型是否被自动维护时间戳

    /**
     * [findShopImageTemplate 查询门店图片上传模板]
     * @return [type] [description]
     */
	public function findShopImageTemplate($shop_id)
    {
    	// 查询系统模板、速电模板和门店自定义的模板
    	$find_image_template = ImageUpload::where('shit_delete', 1)
			    			->where(function ($query) use ($shop_id) {
			                    $query->where('shit_shop_id', 0)
			                        ->Orwhere('shit_shop_id', $shop_id);
				            })
					    	->select('shit_id', 'shit_template_type', 'shit_image_type', 'shit_template_set', 'shit_template_name')
					    	->get()->toArray();
    	return $find_image_template;
    }

    /**
     * [findUpdateImageTemplateState 查找并更改图片模板状态]
     * @param  [type] $shit_shop_id       [门店id]
     * @param  [type] $shit_image_type    [	图片类型：1服务单2销售单3换货单4退货单5发货单6结清单7救援单]
     * @return [type]                     [description]
     */
	public function findUpdateImageTemplateState($shit_shop_id, $shit_image_type)
    {
    	// 查询门店自定义的图片类型模板是否已经存在，如果存在将模板改为删除状态
        $shit_id = ImageUpload::where('shit_shop_id', $shit_shop_id)
	        ->where('shit_delete', 1)
	        ->where('shit_template_type', 2)//模板类型：1系统模板2自定义模板3速电模板
	        ->where('shit_image_type', $shit_image_type)
	        ->value('shit_id');
	    if ($shit_id) {
	    	$res = ImageUpload::where('shit_id', $shit_id)->update(['shit_delete'=>2, 'shit_update_time'=>date('Y-m-d H:i:s')]);
	    }else{
	    	$res = true;
	    }
	    return $res;
    }

    /**
     * [getOrderTypeImageTemplate 根据订单类型，获取当前门店的图片上传模板]
     * @param  [type] $shit_shop_id    [门店id]
     * @param  [type] $shit_image_type [图片类型(订单类型)：1服务单2销售单3换货单4退货单5发货单6结清单7救援单]
     * @return [type]                  [description]
     */
    public function getOrderTypeImageTemplate($shit_shop_id, $shit_image_type)
    {
    	// 根据订单类型，获取当前门店的图片上传模板，
    	// 如果当前门店有对应类型的自定义模板就使用自定义模板，如果没有自定义模板使用系统模板
    	$find_image_template = ImageUpload::where(
    				function ($query) use ($shit_image_type) {
    						// 查询系统模板
		                    $query->where('shit_shop_id', 0)
		                        ->where('shit_delete', 1)//是否删除：1正常2删除
		                        ->where('shit_template_type', 1);//模板类型：1系统模板2自定义模板3速电模板
		            })
    			    ->orwhere(function ($query) use ($shit_shop_id, $shit_image_type) {
    			    	// 查询门店订单类型的自定义模板
	                    $query->where('shit_shop_id', $shit_shop_id)
		                    ->where('shit_delete', 1)
	                        ->where('shit_template_type', 2)
	                        ->where('shit_image_type', $shit_image_type);//图片类型：1服务单2销售单3换货单4退货单5发货单6结清单7救援单
		            })
		            ->pluck('shit_id', 'shit_template_type')->toArray();
		// 如果门店有自定义模板，返回自定义模板id
		if (isset($find_image_template[2])) {
			return $find_image_template[2];
		}else{
			// 如果没有自定义模板，返回系统模板id
			return $find_image_template[1];
		}
    }

    /**
     * [achieveUploadImage 完成上传图片]
     * @param  [type]  $find_work   [查询的工单数据]
     * @param  [type]  $user_info   [用户信息]
     * @param  [type]  $wor_id      [工单id]
     * @param  [type]  $upload_file [上传的图片文件]
     * @return [type]               [description]
     */
    public function achieveUploadImage($find_work, $user_info, $wor_id, $upload_file)
    {
        // 根据图片上传模板判断上传图片
        $find_image_template = DB::table('shop_image_template')
                ->where('shit_id', $find_work->wocl_shit_id)
                ->value('shit_template_set');
        $find_image_template = json_decode($find_image_template,true);
        $upload_file = json_decode($upload_file, true);
        if (empty($upload_file)) {
            return ['code'=>500, 'msg'=>'上传图片格式错误！', 'data'=>'{}'];
        }
        if (count($find_image_template) != count($upload_file)) {
            return ['code'=>500, 'msg'=>'不是图片模板格式,请更新APP后上传图片', 'data'=>'{}'];
        }
        
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $imup_data = [];
        foreach ($find_image_template as $key => $value) {
            // 判断必传图片是否上传 must_state 为1是门店设置的必传图片
            if ($value['must_state'] == 1 && empty($upload_file[$key])) {
                return ['code'=>500, 'msg'=>'请上传 '.$value['show_word'].' 图片', 'data'=>'{}'];
            }
            $imup_data[$key]['imup_cid'] = $user_info->adm_cid;
            $imup_data[$key]['imup_shop_id'] = $user_info->adm_shop_id;
            $imup_data[$key]['imup_superior_shop_id'] = $shop_id;
            $imup_data[$key]['imup_ord_id'] = $find_work->wor_order_id;
            $imup_data[$key]['imup_wor_id'] = $wor_id;
            $imup_data[$key]['imup_path'] = '';
            $imup_data[$key]['imup_image_name'] = $value['show_word'];
        }
        foreach ($upload_file as $key => $value) {
            if (!empty($value)) {
                // 判断是否为base64数据
                if (strpos($value['imagesBase64'], 'data:image') === 0) {
                    // 调用全局函数 上传图片
                    $imup_data[$key]['imup_path'] = uploadBase64ImgFolder($shop_id, $value['imagesBase64'], 2);
                } else {
                    // 不是base64数据，就是图片路径,判断图片路径是否存在域名
                    if (stripos($value['imagesBase64'], config('apisystem.server_name')) !== false) {
                        $imup_data[$key]['imup_path'] = substr($value['imagesBase64'], strlen(config('apisystem.server_name')) + 1);
                    } else {
                        $imup_data[$key]['imup_path'] = $value['imagesBase64'];
                    }
                }
            }
        }
        $res = DB::table('image_upload')->insert($imup_data);
        if ($res) {
            return ['code'=>200, 'msg'=>'图片上传成功', 'data'=>'{}'];
        }else{
            return ['code'=>500, 'msg'=>'图片上传失败', 'data'=>'{}'];
        }
    }
}
