<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\User;
use PhpOffice\PhpWord\TemplateProcessor;

class Contract extends Model
{
    protected static $config = [];
    public static function getSet(){
        
        if(empty(self::$config)){
            $set = Db::name("bbfx_contract_set")->where(['uniacid'=>UNIACID])->find();
            self::$config = $set;
        }
        else{
            $set = self::$config;
        }
        
        return $set;
    }
    
    public static function createUserGoodsContract($order_id){
        $set = self::getSet();
        if($set['status'] != 1){
            return false;
        }
        
        $goods = Db::name("bbfx_goods")->alias("g")->join("bbfx_order_goods og","g.id=og.goods_id","LEFT")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.status'=>['>',0],'o.id'=>$order_id,'g.is_contract'=>1])->field("g.*,og.total,og.price as order_price,og.id as og_id,og.order_id,o.user_id")->find();
        if(empty($goods)){
            return false;
        }
        
        $contract_ids = iunserializer($goods['contract']);
        if(empty($contract_ids)){
            return false;
        }
        
        $record = Db::name("bbfx_contract_record")->where(['uniacid'=>UNIACID,'og_id'=>$goods['og_id']])->find();
        if(!empty($record)){
            return false;
        }
        
        // $contract_list = Db::name("bbfx_contract")->where(['uniacid'=>UNIACID,'id'=>['in',$contract]])->select();
        // if(empty($contract_list)){
        //     return false;
        // }
        $path = ROOT_PATH . "public";
        
        foreach ($contract_ids as $key => $val){
            
            $contract = Db::name("bbfx_contract")->where(['id'=>$val])->find();
            
            $templateProcessor = new TemplateProcessor($path.$contract['content']);
            
            $templateProcessor->setValue('goods_name',$goods['title']);
            $templateProcessor->setValue('goods_num',$goods['total']);
            $templateProcessor->setValue('goods_price',$goods['order_price']);
            $ext = ".doc";
            if(strstr($contract['content'], '.docx')){
                $ext = ".docx";
            }
            
            $contract_word = '/contract/'.random(32).$ext;
            $templateProcessor->saveAs($path.$contract_word);
            
            $data = array(
                "uniacid"=>UNIACID,
                "user_id"=>$goods['user_id'],
                "name"=>$contract['name'],
                "pid"=>$contract['id'],
                "type"=>$contract['type'],
                "signing_type"=>$contract['signing_type'],
                "og_id"=>$goods['og_id'],
                "content"=>$contract_word,
                "createtime"=>time()
            );
            
            Db::name("bbfx_contract_record")->insert($data);
        }
    }
    
    public static function signContract($id,$sign_img){
        $record = Db::name("bbfx_contract_record")->where(["id"=>$id,'type'=>1])->find();
        if(empty($record)){
            return __json(0,"合同不存在");
        }
        if($record['status'] == 1){
            return __json(0,"已签署过该合同");
        }
        
        $path = ROOT_PATH . "public";
        

        if(strstr($sign_img,'http')){
            $domain = $_SERVER['HTTP_HOST'];
            $arr = explode('/uploads/',$sign_img);
            
            if(!strstr($sign_img,$domain)){
                saveFile($sign_img,$path."/uploads/".$arr[1]);
            }
            
            $sign_img = "/uploads/".$arr[1];
        }
        
        
        if(!file_exists($path.$sign_img)){
            $url = cdnurl($sign_img);
            $localPath = $path.$sign_img;
            
            // 获取图片内容
            $imageContent = file_get_contents($url);
             
            // 检查是否成功获取图片内容
            if ($imageContent !== false) {
                // 保存图片到本地
                $res = file_put_contents($localPath, $imageContent);
                // print_r($res);die;
            } else {
                return __json(0,"已签署过该合同");
            }
        }
        
        
        try {
            Db::startTrans();
            $res = Db::name("bbfx_contract_record")->where(['id'=>$record['id']])->update(['status'=>1]);
            if(empty($res)){
                throw new \Exception("已签署过该合同");
            }
            
            $contract_word = $record['content'];
            
            $templateProcessor = new TemplateProcessor($path.$contract_word);
            $templateProcessor->setValue('ht_time',date("Y年m月d日"));
            $templateProcessor->setImageValue("Image",['path'=>$path.$sign_img,'width'=>'160','height'=>'100']);
            $templateProcessor->saveAs($path.$contract_word);
            
            Db::name("bbfx_contract_record")->where(['id'=>$record['id']])->update(['signingtime'=>time(),'signing_image'=>$sign_img]);
            
            /*
            $record_onk = Db::name("bbfx_contract_record")->where(['uniacid'=>UNIACID,'type'=>1,'og_id'=>$record['og_id'],'status'=>0])->find();
            if(empty($record_onk)){
                $order_goods = Db::name("bbfx_order_goods")->where(['uniacid'=>UNIACID,'id'=>$record['og_id']])->select();
                foreach ($order_goods as $key => $val){
                    
                }
            }
            */
            
            Db::commit();
        } 
        catch (\Exception $e) {
            Db::rollback();
            return __json(0,$e->getMessage());
        }
        
        return __json(1,"签署成功");
    }
}