<template>
  <div class="toolbar" v-if="items.length>0">
    <template v-for="item in items" >
      <div class="toolbar-item" v-if="item.type!=='break'" v-show="item.visible!==false&&item.type!=='hidden'"
           :class="getStyle(item,false)">
        <template v-if="item.type==='search'">
            <el-button :type="$core.adapterType(item)"  :name="item.code" :size="$store.state.settings.Size"
                       :title="$_i18n(item.remark||item.name)" :icon="getStyle(item||'icon-search')"
                       @click="handleClick($event,item)" :loading="queryParams.loading===true" >
              {{$_i18n(item.name)}}
            </el-button>
        </template>
        <!--打开表单-->
        <template v-else-if="item.type==='form'">
            <el-button :type="$core.adapterType(item)"  :name="item.code" :size="$store.state.settings.Size"
                       :title="$_i18n(item.remark||item.name)" :icon="getStyle(item)"
                       @click="handleClick($event,item)">
              {{$_i18n(item.name)}}
            </el-button>
        </template>
        <template v-else-if="item.type==='save'||item.type==='saveRel'||
                item.type==='webpage'||item.type==='list'||item.type==='jsonupdate'||item.type==='print'
                ||item.type==='close'||item.type==='oa'">
            <el-button :type="$core.adapterType(item)"  :name="item.code" :size="$store.state.settings.Size"
                       :title="$_i18n(item.remark||item.name)" :icon="getStyle(item)"
                       @click="handleClick($event,item)">
              {{$_i18n(item.name)}}
            </el-button>
        </template>
        <template v-else-if="item.type==='text'||item.type==='hidden'">
            <span>{{$_i18n(item.name)}}</span>
            <el-input :name="item.code"  v-model="queryParams[item.code]" :size="$store.state.settings.Size"
                      :title="$_i18n(item.remark||item.name)"  :placeholder="$_i18n(item.remark||item.name)"
                      @keyup.enter.native="search" :disabled="item.readonly===false" clearable
                      @change="changed($event,item)" :class="getStyle(item)"/>
        </template>
        <template v-else-if="item.type==='date'||item.type==='datetime'">
            <span>{{$_i18n(item.name)}}</span>
            <el-date-picker :value-format="item.formatString" :format="item.formatString" :size="$store.state.settings.Size"
                            v-model="queryParams[item.code]" :type="item.type" :name="item.code" :ref="item.code"
                            :placeholder="$_i18n(item.remark||item.name)" :editable="false"
                            :clearable="(item.linkageRule&&item.linkageRule.clearable)||false"
                            :picker-options="{shortcuts:[{text:'当前时间',onClick(picker){picker.$emit('pick',new Date());}}]}"
                            @change="changed($event,item)" :class="getStyle(item)">
            </el-date-picker>
        </template>
        <template v-else-if="item.type==='select'||item.type==='dropdownchecklist'||item.type==='autocomplete'||item.type==='autocomplete_remote'">
          <span>{{$_i18n(item.name)}}</span>
          <el-select v-model="queryParams[item.code]" placeholder="请选择" value-key="id" :ref="item.code"
                     :filterable="item.type==='autocomplete'" :default-first-option="item.type==='autocomplete'"
                     :multiple="item.type==='dropdownchecklist'" :disabled="item.readonly===false"
                     :clearable="item.type!=='select'" :size="$store.state.settings.Size" :loading="item.loading"
                     :remote="(item.type==='autocomplete'&&item.linkageRule&&item.linkageRule.remote)||item.type==='autocomplete_remote'"
                     :remote-method="($event)=>handleRemote($event,item)" @change="changed($event,item)"
                     :class="getStyle(item)" @clear="($event)=>handelClear($event,item)">
            <el-option v-for="dataItem in item.options" :key="dataItem.id"  :label="dataItem.name" :value="dataItem.id">
            </el-option>
          </el-select>
        </template>
          <!--树选择-->
          <template v-else-if="item.type==='selectTree'">
              <SelectTree v-model="queryParams[item.code]" :placeholder="placeholderAdapter(item)"
                          :ref="item.code" :title="setControlTitle(item)" :size="$store.state.settings.Size"
                          :show-checkbox="item.linkageRule&&item.linkageRule.showCheckbox"
                          :leafOnly="item.linkageRule&&item.linkageRule.leafOnly"
                          :filterable="item.linkageRule&&item.linkageRule.showFilter"
                          :checkStrictly="item.linkageRule&&item.linkageRule.checkStrictly"
                          :highlight-current="item.linkageRule&&item.linkageRule.highlightCurrent"
                          :default-expand-all="item.linkageRule&&item.linkageRule.expandAll"
                          :disabled="checkDisable(item)" @change="changed($event,item)"
                          clearable  :class="item.style"  :treeProps="item.linkageRule.props"
                          :options="item.options">
              </SelectTree>
          </template>
        <template v-else-if="item.type==='link'">
          <LinkButton :href="item.href||'javascript:void(0);'" :type="$core.adapterType(item)" target="_blank"
                      :ref="item.code" @click="handleClick($event,item)" :size="$store.state.settings.Size"
                      :title="$_i18n(item.remark||item.name)"
                   :underline="false" :icon="getStyle(item)" :disabled="item.readonly===false">
            {{$_i18n(item.name)}}</LinkButton>
        </template>
        <template v-else-if="item.type==='label'">
          <span>{{$_i18n(item.name)}}</span>
        </template>
        <template v-else-if="item.type==='upload'">
            <el-upload :action="adapterUrl(item.actionUrl,queryParams,false,true)" :data="item.linkageRule.data"
                       :accept="item.linkageRule.accept" :limit="item.linkageRule.limit"
                       :on-change="(...event)=>handleFileChanged(event[0],event[1],item)"
                       :before-upload="($event)=>beforeUpload($event,item)" list-type="text"
                       :on-exceed="(...event)=>handleExceed(event[0],event[1],item)"
                       :on-success="(...event)=>handleUploadSuccess(event[0],event[1],event[2],item)"
                       :on-error="(...event)=>handleUploadError(event[0],event[1],event[2],item)"
                       :title="$_i18n(item.remark||item.name)" :show-file-list="false">
                <el-button type="primary" slot="trigger"  :size="$store.state.settings.Size"
                           :icon="getStyle(item)"> {{$_i18n(item.name)}}</el-button>
<!--                <div slot="tip" class="el-upload__tip" >{{item.remark||item.linkageRule.desc}}</div>-->
            </el-upload>
        </template>
        <template v-else-if="item.type==='plugin'">
          <el-button :type="$core.adapterType(item)"  :name="item.code" :size="$store.state.settings.Size"
                       :title="$_i18n(item.remark||item.name)" :icon="getStyle(item)"
                       @click="handleClick($event,item)" :loading="queryParams.loading===true" >
              {{$_i18n(item.name)}}
            </el-button>
        </template>
        <template v-else>
          未定义-请联系产品研发==>{{item.type}}
        </template>
      </div>
      <br v-else :class="[item.type]"  />
    </template>
      <span class="msg"></span>
  </div>
</template>
<script>
   import LinkButton from '../LinkButton';
   import SelectTree from '../SelectTree';
   import common from "./common";
    /**事件
     * ready 当工具栏加载完成触发
     * completed 当工具栏加载完成并完成渲染时触发
     * query 当工具栏点击查询时触发
     */
    export default {
        name: 'CustomToolbar',
        mixins: [common],//监听外部框架的大小改变事件
        props: {
            fid:{
                type:String,
                default:""
            },queryParams:{
                type:Object,
                default:{}
            }
        },
        components:{
            LinkButton,SelectTree
        },
        watch:{
            items:function(){
                this.$nextTick(()=>{
                    this.resize();//触发布局大小改变事件
                    this.completed();//触发加载完成事件
                })
            }
        },data() {
            return {
                loaded:false,
                items:[],
                toolbars:{}
            }
        },methods: {
            async updateTools(newTools,view={}){
                this.items=[];
                let removeIndex=[];
                for(let i=newTools.length-1;i>=0;i--) {
                    let item=newTools[i];
                    if (this.toolbars[item.code] != null) {//如果已经存在，则融入,此功能用于替换默认的按钮
                        let temp = newTools[this.toolbars[item.code]];//如果发现系统预装或编码重复
                        this.$core.merge(true,item,temp);//支持全部融合
                        removeIndex.push(this.toolbars[item.code]);//为了兼容同时多个
                    }
                    this.toolbars[item.code] = i;
                }
                if(removeIndex.length>0) {//为了兼容同时多个
                    for (let i = newTools.length - 1; i >= 0; i--) {
                       let ind= removeIndex.find((index)=>index===i);
                       if(ind>=0) {
                           newTools.splice(ind, 1);
                       }
                    }
                }
                for(let i in newTools){
                    let item=newTools[i];
                    item.linkageRule=this.$core.merge({},item.linkageRule);//修正因为没有配置联动规则，产生的错误
                    if(item.actionUrl){//尝试先从地址协议上获取配置规则
                       let params=this.$core.getParams(item.actionUrl);
                       let  rule={};
                       let keys= ["supportNullSelect","triggers","bigdata","chooseShow"];
                       for(let i in keys){
                           let key=keys[i];
                           if(params[key]){
                               switch (key) {
                                   case "triggers":
                                       rule[key] = params[key].split(",");
                                       break;
                                   case "bigdata":
                                       let names=params[key].split(",");
                                       rule[key]={};
                                       for(let index in names){
                                           if(names[index])
                                               rule[key][names[index]] = "{"+names[index]+"}";
                                       }
                                       break;
                                   default:
                                       rule[key]=this.$core.adapterData(params[key]);
                                       break;
                               }
                               delete params[key];
                           }
                       }
                       if(Object.getOwnPropertyNames(rule).length>0) {
                           item.linkageRule=this.$core.merge(rule,item.linkageRule);//融合参数支持
                           item.actionUrl = this.$core.replaceQueryString(this.$core.getPageAddress(item.actionUrl), params, false, true);//裁剪掉相关参数
                       }
                    }
                    switch (item.type) {
                        case "date":
                        case "datetime":
                            if(item.actionUrl){
                                await this.$async({url:item.actionUrl.urlFormat(this.queryParams)}).then(async (res)=>{
                                    this.$set(this.queryParams,item.code,new Date(res.data[0].searchtime).format(item.formatString))
                                    if(this.queryParams[item.code]!=null){
                                        this.changed(this.queryParams[item.code],item);
                                    }
                                });
                            }
                            break;
                        case "select"://下拉
                        case "dropdownchecklist"://多选下拉
                        case "autocomplete"://自动完成
                        case "selectTree"://树选择
                            // item.linkageRule=this.$core.merge({remote:false},item.linkageRule);
                            if(item.actionUrl) {
                                item.triggerHandler=async (toolbarItem,val)=>
                                {
                                    this.$set(toolbarItem, "options", []);
                                    if(this.loaded){
                                        this.$set(this.queryParams, toolbarItem.code, val);
                                    }
                                    let url=toolbarItem.actionUrl.urlFormat(this.queryParams,false,true);
                                    await this.$async({url: url}).then(async (res) => {
                                        this.updateSelect(url,toolbarItem,res.data)
                                    });
                                }
                                await item.triggerHandler(item);
                            }
                            break;
                        case "jsonupdate":
                            switch (item.code) {//部分按钮需要从全局参数中获取干预
                                case "del":
                                    if(view["phy_del"]===true){
                                        item.linkageRule.params.phy_del=true;
                                    }
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case "upload":
                            item.linkageRule.data= this.$core.extend({toolCode:item.code,fid:this.fid,
                                token:this.$store.state.user.token,
                                app_id:this.$store.state.app.appid,
                                access_token:this.$store.state.app.access_token
                            },item.linkageRule.data);
                            break;
                        default:
                            break;
                    }
                    this.items.push(item);
                }
                //如果需要隐藏部分按钮功能
                if(this.queryParams.hide){
                    let buttons=this.queryParams.hide.split(",");
                    for(let i in buttons){
                        if(buttons[i]){
                            let item= this.items.find((item)=>{
                                if(item.code===buttons[i])
                                return true;
                            });
                            if(item){
                                item.visible=false;
                            }
                        }
                    }
                }
                this.loaded=true;
                this.$emit("ready",this.queryParams,view,this.items);
            },getStyle(item,isControl=true){
                if(item.style) {
                    let styles = item.style.split(" ");
                    if (isControl) {
                        let iconfonts = styles.filter((s) => s.indexOf("icon") === 0);
                        if (iconfonts.length > 0) {
                            iconfonts.unshift("iconfont-toolbar")
                            iconfonts.unshift("iconfont");
                            return iconfonts.join(" ");
                        }
                        iconfonts = styles.filter((s) => s.indexOf("wid") === 0);
                        if(iconfonts===""){ //修正空样式错误
                            return null;
                        }
                        return iconfonts;
                        // return "iconfont iconfont-toolbar " + style;
                    } else {
                        let normalStyle = styles.filter((s) => s.indexOf("icon") !== 0 && s.indexOf("wid") !== 0)
                        normalStyle.unshift(item.type);
                        if(normalStyle===""){//修正空样式错误
                            return null;
                        }
                        return normalStyle;
                    }
                }
            },completed(){
                this.$emit("completed");
            },resize(){
                this.$emit("resize");
            },search(){
              this.$core.debug().log("search",this,this.toolbars);
              if(this.toolbars.search!=null||this.toolbars.refresh!=null){
                 this.handleClick(null,this.items[this.toolbars.search??this.toolbars.refresh]);
              }
            },handleClick(event,item){
                this.$emit("click",event,item);//一般来说，需要回主页面采集信息，再提交的，则触发此事件
            },async changed(data,item){
                if(item&&item.linkageRule){
                    let dataObj={};
                    if(item.options){//说明是下拉类的数据
                        for(let i in item.options){
                            if(item.options[i].id===data){
                                dataObj=item.options[i];
                                break;
                            }
                        }
                    }else{
                        dataObj[item.code]=data;
                    }
                    let rule=item.linkageRule;
                    if(rule.datas){ //触发需要改变的值
                        for(let key in item&&rule.datas){
                           this.$set(this.queryParams,key,rule.datas[key].urlFormat(dataObj,true,true));
                        }
                    }
                    //触发需要改变的控件,需要判断控件是否已经加载
                    //工具栏没有加载完成时，加载过程逻辑会自动执行对应最新数据获取
                    //工具栏加载完成时，需要手动触发对应的控件进行重新加载
                    if(this.loaded&&rule.triggers) {
                        for(let i in rule.triggers){
                            let toolbarItem=this.items[this.toolbars[rule.triggers[i]]];
                            if(toolbarItem) {
                                if (toolbarItem.triggerHandler)
                                    await toolbarItem.triggerHandler(toolbarItem);
                                else {
                                    this.$nextTick(() => {
                                        this.handleClick(null,toolbarItem);
                                    })
                                }
                            }
                        }
                    }
                }
                // this.$core.debug().log("收到事件",this.queryParams,data,item);
            },handelClear(e,item){
                if (item.type==='autocomplete_remote')
                    this.handleRemote(e,item);
                else
                    this.changed(e,item);
            },
            handleRemote(query,item) {
                this.$set(item, "loading", true);
                if (item.timeoutHandler) {
                    clearTimeout(item.timeoutHandler);
                    item.timeoutHandler = null;
                }
                item.timeoutHandler = setTimeout(() => {
                    let options = this.$core.extend({}, this.queryParams, {q: query});
                    let url = item.actionUrl.urlFormat(options, false, true);
                    this.$http({url: url}).then(async (res) => {
                        item.loading = false;
                        this.updateSelect(url,item,res.data)
                    });
                }, 300);//延迟300毫秒，在快速输入时，减少交互
            },updateSelect(url,item,data){
                for(let i in data){//针对部分数据可能是json的适配
                    for(let key in data[i]){
                        data[i][key]=this.$core.adapterData(data[i][key]);
                    }
                }
                item.options = data;
                if(item.linkageRule&&item.linkageRule.supportNullSelect===true){
                    item.options.unshift({id:null,name:"请选择"});
                }
                if(item.options.length>0){
                    if (this.queryParams[item.code] != null) {
                        this.changed(this.queryParams[item.code], item);
                    }else{//多选和模糊搜索，需要用户自己选择
                        if(item.type==="select"){//如果下拉没有默认数据，则自动选择第一个
                            this.$set(this.queryParams,item.code,item.options[0].id);
                            this.changed(this.queryParams[item.code], item);
                        }
                    }
                }else{
                    this.changed(null, item);
                }
            },handleFileChanged(file,fileList,item){
              this.$core.debug().log("选择的文件",file,fileList,item);
              return true;
            },beforeUpload(file, item) {
                if (file) {
                    if (file.size > (item.linkageRule.maxSize||1024*1024*10)) {//10m
                        this.$core.debug().log("上传的文件超过限制大小",file.size);
                        this.$_page_message({code:1,msg:item.linkageRule.desc||'上传的文件超过限制大小'});
                        return false;
                    }
                    return true;
                }
                return false;
            }, handleExceed(files, fileList, item) {
                this.$_page_message({code:1,
                    msg:`当前限制只能上传${item.linkageRule.limit||1}个文件，本次选择了${files.length}个文件，已上传${fileList.length}个文件`});
            },handleUploadSuccess(response, file, fileList, item) {
                if(response.code===0) {
                    this.$emit("click",null,{type:"search"});//模拟点击
                }else{
                }
                this.$_page_message(response);
            }, handleUploadError(response, file, fileList, item) {
                this.$core.debug().log("上传失败，如果需要处理，请优化", response, file, fileList, item, this.form[item.code]);
            }
        }
    }
</script>
