<?php
/**
 * @desc: 删除文章附件(包括不限于:上传图片,附件)
 * @Author: Dr.Xing <ezfwork@foxmail.com>
 * @Since: 2018/1/28 10:27
 */

namespace seven\behavior;

use app\admin\model\Archives;
use think\Model;

class ArchiveDel
{
    public function run(&$params)
    {
        if ($params instanceof Archives){
            $pk = $params->getPk();
            $attachments = [];
            array_push($attachments, $params['cover']);
            //读取模型字段
            $extra = model('PostsModelx')->get(['name'=>$params['type']]);
            if(isset($extra['extra']) && !empty($extra['extra'])) {
                //读取模型数据
                $archive_model = model('extra' . $params['type'])->get(['item_id' => $params[$pk]]);
                foreach (json_decode($extra['extra'],true) as $k=>$v)
                {
                    if(!isset($archive_model[$v['field']]) ||
                        (isset($archive_model[$v['field']]) && empty($archive_model[$v['field']]))) {
                        continue;
                    }
                    if($v['type']=='image'){
                        array_push($attachments, $archive_model[$v['field']]);
                    }
                    elseif($v['type']=='images'){
                        $arr = explode(",", $archive_model[$v['field']]);
                        $attachments= array_merge($attachments, $arr);
                    }
                    elseif(in_array($v['type'], ['file','files'])){
                        $arr= json_decode($archive_model[$v['field']],true);
                        foreach($arr as $key=>$val){
                            array_push($attachments, $val['url']);
                        }
                    }
                }
            }
            model('extra' . $params['type'])->where(['item_id' => $params[$pk]])->delete();

            //打上可删除标识
            foreach ($attachments as $k => $v){
                if(!empty($v)){
                    model('Attachment')->where('url', $v)->update(['canDelete'=>1]);
                }
            }
        }
    }

}