<template>
<div>
    <div class="ui container" id="header">
                <el-row style="margin-top:15px;">
                    <el-table
                        ref="table"
                        :data="tableData"
                        style="min-width: 100%"
                        row-key="ID"
                        lazy
                        :load="load"
                        :tree-props="{children: 'Children', hasChildren: 'hasChildren'}"
                        :header-cell-style="tableHeaderStyle"
                    >
                        <el-table-column
                            prop="Name"
                            label="模型名称"
                            align="left"
                            min-width="18%"
                            >
                            <template slot-scope="scope">
                                <div class="expand-icon" v-if="scope.row.hasChildren===false">
                                    <i class="el-icon-arrow-right"></i>
                                </div>
                                <!-- <i class="el-icon-time"></i> -->
                                <a class="text-over" :href="showinfoHref+scope.row.Name" :title="scope.row.Name">{{ scope.row.Name }}</a>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="Version"
                            label="版本"
                            align="center"
                            min-width="6.5%"
                            >
                            <template slot-scope="scope">
                                <span class="text-over" :title="scope.row.Version">{{ scope.row.Version}}</span>
                            </template>
                        </el-table-column>
                        
                        <el-table-column
                            prop="VersionCount"
                            label="版本数"
                            align="center"
                            min-width="7.5%"
                            >
                            <template slot-scope="scope">
                                <span class="text-over" :title="scope.row.VersionCount">{{ scope.row.VersionCount}}</span>
                            </template>
                        </el-table-column>

                        <el-table-column
                            prop="Size"
                            label="模型大小"
                            align="center"
                            min-width="10.5%"
                            >
                            <template slot-scope="scope">
                                <span class="text-over">{{ renderSize(scope.row.Size)}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="EngineName"
                            label="AI引擎"
                            align="center"
                            min-width="8.5%"
                            >
                            <template slot-scope="scope">
                                <span class="text-over">{{ scope.row.EngineName}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="ComputeResource"
                            label="计算资源"
                            align="center"
                            min-width="10.5%"
                            >
                            <template slot-scope="scope">
                                <span class="text-over">{{ scope.row.ComputeResource}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="CreatedUnix"
                            label="创建时间"
                            align="center"
                            min-width="13.75%"
                            >
                            <template slot-scope="scope">
                                {{transTime(scope.row.CreatedUnix)}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="UserName"
                            label="创建者"
                            align="center"
                            min-width="6.75%"
                            >
                            <template slot-scope="scope">
                                <a :href="!scope.row.UserName? '#':'/'+scope.row.UserName" :title="scope.row.UserName||defaultAvatarName">
                                    <img class="ui avatar image" :src="scope.row.UserRelAvatarLink||defaultAvatar">
                                </a>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" min-width="18%" align="center">
                            <template slot-scope="scope">
                                <div class="space-around">
                                    <a :style="{visibility:!scope.row.Children ? 'visible':'hidden'}" :class="{'disabled':!scope.row.IsCanOper}" @click="showcreateVue(scope.row.Name,scope.row.Version,scope.row.Label)">创建新版本</a>
                                    <a :href="loadhref+scope.row.ID" :class="{'disabled':!scope.row.IsCanOper}">下载</a>
                                    <a :class="{'disabled':!scope.row.IsCanOper}" @click="deleteModel(scope.row.ID,scope.row.cName)">删除</a>
                                </div>
                                
                            </template>
                        </el-table-column>
                    </el-table>
                </el-row>
                <div class="ui container" style="margin-top:50px;text-align:center">
                        <el-pagination
                            background
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="currentPage"
                            :page-sizes="[5,10,15]"
                            :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="totalNum">
                        </el-pagination>
                </div>
  </div>
</div>

  
</template>

<script>

const {_AppSubUrl, _StaticUrlPrefix, csrf} = window.config;

export default {
  components: {
    
  },
  data() {
    return {
        
      currentPage:1,
      pageSize:10,
      totalNum:0,
      params:{page:0,pageSize:10},
      tableData: [],
      url:'',
      isLoading:true,
      loadNodeMap:new Map(),
      submitId:{},
      defaultAvatar:'/user/avatar/Ghost/-1',
      defaultAvatarName:'Ghost',
      data:''
    };
  },
  methods: {
    load(tree, treeNode, resolve) {    
        try{
            this.loadNodeMap.set(tree.cName, {tree,treeNode,resolve})
            this.$axios.get(this.url+'show_model_child_api',{params:{
                name:tree.cName
            }}).then((res)=>{
                let TrainTaskInfo
                let tableData 
                tableData= res.data
                for(let i=0;i<tableData.length;i++){
                    TrainTaskInfo = JSON.parse(tableData[i].TrainTaskInfo)
                    tableData[i].EngineName = TrainTaskInfo.EngineName.split('-')[0]
                    tableData[i].ComputeResource = TrainTaskInfo.ComputeResource
                    tableData[i].cName=tableData[i].Name
                    tableData[i].Name=''
                    tableData[i].VersionCount = ''
                    tableData[i].Children = true
                }
                resolve(tableData||[])
            })
        }
        catch(e){
            this.loading = false;
        }        
    },
    tableHeaderStyle({row,column,rowIndex,columnIndex}){
        if(rowIndex===0){
            return 'background:#f5f5f6;color:#606266'
        }
    },
    handleSizeChange(val){
        this.params.pageSize = val
        this.getModelList()
    },
    handleCurrentChange(val){
        this.params.page = val
        this.getModelList()
    },
    showcreateVue(name,version,label){
        $('.ui.modal.second')
        .modal({
            centered: false,
            onShow:function(){
                $('#model_header').text("创建模型新版本")
                $('input[name="Name"]').addClass('model_disabled')
                $('input[name="Name"]').attr('readonly','readonly')
                $('input[name="Version"]').addClass('model_disabled')
                $('.ui.dimmer').css({"background-color":"rgb(136, 136, 136,0.7)"})
                $("#job-name").empty()
                $('#name').val(name)
                $('#label').val(label)
                let version_string = versionAdd(version)
                $('#version').val(version_string)
                loadTrainList()
            },
            onHide:function(){
                document.getElementById("formId").reset();
                $('input[name="Name"]').removeClass('model_disabled')
                $('input[name="Name"]').removeAttr('readonly')
                $('#choice_model').dropdown('clear')
                $('#choice_version').dropdown('clear')
                $('.ui.dimmer').css({"background-color":""})
                $('.ui.error.message').text()
                $('.ui.error.message').css('display','none')
            }
        })
        .modal('show')
    },
    check(){
        let jobid = document.getElementById("JobId").value
        let versionname = document.getElementById("VersionName").value
        let name= document.getElementById("name").value
        let version= document.getElementById("version").value
        if(jobid==""){
            $(".required.ten.wide.field").addClass("error")
            return false
        }else{
            $(".required.ten.wide.field").removeClass("error")
        }
        if(versionname==""){
            $(".required.six.widde.field").addClass("error")
            return false
        }else{
            $(".required.six.widde.field").removeClass("error")
        }
        if(name==""){
            $("#modelname").addClass("error")
            return false
        }else{
            $("#modelname").removeClass("error")
        }
        if(versionname==""){
            $("#verionname").addClass("error")
            return false
        }else{
            $("#verionname").removeClass("error")
        }
        return true
    },
    submit(){
        let context = this
        let flag= this.check()
        if(flag){
            let cName =  $("input[name='Name']").val()
            let version = $("input[name='Version']").val()
            let data = $("#formId").serialize()
            let url_href = version === '0.0.1' ? context.url_create_newModel : context.url_create_newVersion
            $("#mask").css({"display":"block","z-index":"9999"})
            $.ajax({
                url:url_href,
                type:'POST',
                data:data,
                success:function(res){
                    // context.loadrefresh1(row)
                    context.getModelList()
                    $('.ui.modal.second').modal('hide')
                },
                error: function(xhr){
                // 隐藏 loading
                // 只有请求不正常（状态码不为200）才会执行
                    $('.ui.error.message').text(xhr.responseText)
                    $('.ui.error.message').css('display','block')
                },
                complete:function(xhr){
                    $("#mask").css({"display":"none","z-index":"1"})
                }
            })
        }else{
            return false
        }
    },
    loadrefresh(row){
        const store = this.$refs.table.store
        if(!this.loadNodeMap.get(row.cName)){
            const parent = store.states.data
            const index = parent.findIndex(child => child.ID == row.ID)
            this.getModelList()
        }else{
            let {tree,treeNode,resolve} = this.loadNodeMap.get(row.cName)
            const keys = Object.keys(store.states.lazyTreeNodeMap);
            if(keys.includes(row.ID)){
                this.getModelList()
            }else{
                let parentRow = store.states.data.find(child => child.cName == row.cName);
                let childrenIndex = store.states.lazyTreeNodeMap[parentRow.ID].findIndex(child => child.ID == row.ID)
                parentRow.VersionCount = parentRow.VersionCount-1
                const parent = store.states.lazyTreeNodeMap[parentRow.ID]
                if(parent.length===1){
                    this.getModelList()
                }else{
                    parent.splice(childrenIndex, 1);
                }
            }
        }
        
    },
    deleteModel(id,name){
        let row={cName:name,ID:id}
        let _this = this
        let flag=1
        $('.ui.basic.modal.first')
        .modal({
            onDeny: function() {
                flag = false
            },
            onApprove: function() {
                _this.$axios.delete(_this.url+'delete_model',{
                params:{
                    ID:id
                }}).then((res)=>{
                    _this.loadrefresh(row)
                    // _this.getModelList()
                })
                flag = true
            },
            onHidden: function() {
                if (flag == false) {
                    $('.alert').html('您已取消操作').removeClass('alert-success').addClass('alert-danger').show().delay(1500).fadeOut();
                }else{
                    $('.alert').html('删除成功').removeClass('alert-danger').addClass('alert-success').show().delay(1500).fadeOut();
                }
            }
        })
        .modal('show')
    },
    getModelList(){
        try {
            this.$refs.table.store.states.lazyTreeNodeMap = {}
            this.$axios.get(location.href+'_api',{
                params:this.params
            }).then((res)=>{
                $(".ui.grid").removeAttr("style")
                $("#loadContainer").removeClass("loader")
                let TrainTaskInfo
                this.tableData = res.data.data
                for(let i=0;i<this.tableData.length;i++){
                    TrainTaskInfo = JSON.parse(this.tableData[i].TrainTaskInfo)
                    this.tableData[i].cName=this.tableData[i].Name
                    this.tableData[i].EngineName = TrainTaskInfo.EngineName.split('-')[0]
                    this.tableData[i].ComputeResource = TrainTaskInfo.ComputeResource
                    this.tableData[i].hasChildren = res.data.data[i].VersionCount===1 ? false : true
                }
                this.totalNum = res.data.count
            })
        }catch (e) {
            console.log(e)
        }
        
    },
 
  },
  computed:{
    loadhref(){
        return this.url+'downloadall?ID='
    },
    showinfoHref(){
        return this.url + 'show_model_info?name='
    },
    transTime(){
        return function(time){
            let date = new Date(time * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            let Y = date.getFullYear() + '-';
            let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1):date.getMonth()+1) + '-';
            let D = (date.getDate()< 10 ? '0'+date.getDate():date.getDate())+ ' ';
            let h = (date.getHours() < 10 ? '0'+date.getHours():date.getHours())+ ':';
            let m = (date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes()) + ':';
            let s = date.getSeconds() < 10 ? '0'+date.getSeconds():date.getSeconds();
            return Y+M+D+h+m+s;
        }
    },
    renderSize(){
        return function(value){
            if(null==value||value==''){
                return "0 Bytes";
            }
            var unitArr = new Array("Bytes","KB","MB","GB","TB","PB","EB","ZB","YB");
            var index=0;
            var srcsize = parseFloat(value);
            index=Math.floor(Math.log(srcsize)/Math.log(1024));
            var size =srcsize/Math.pow(1024,index);
            size=size.toFixed(2);//保留的小数位数
            return size+unitArr[index];
        }
    }
  },
  mounted() {
    this.submitId = document.getElementById("submitId")
    this.getModelList()
    this.url = location.href.split('show_model')[0]
    this.submitId.addEventListener("click", this.submit)
    this.url_create_newVersion = this.url + 'create_model'
    this.url_create_newModel = this.url + 'create_new_model'
  },

  beforeDestroy() {  // 实例销毁之前对点击事件进行解绑
    this.submitId.removeEventListener('click', this.submit);
  }
};
</script>

<style scoped>






/deep/ .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #5bb973;
  color: #FFF;
}
/deep/ .el-pagination.is-background .el-pager li.active {
  color: #fff;
  cursor: default;
}
/deep/ .el-pagination.is-background .el-pager li:hover {
  color: #5bb973;
}
/deep/ .el-pagination.is-background .el-pager li:not(.disabled):hover {
  color: #5bb973;
}
/deep/ .el-pagination.is-background .el-pager li:not(.disabled).active:hover {
  background-color: #5bb973;
  color: #FFF;
}

/deep/ .el-pager li.active {
  color: #08C0B9;
  cursor: default;
}
/deep/ .el-pagination .el-pager li:hover {
  color: #08C0B9;
}
/deep/ .el-pagination .el-pager li:not(.disabled):hover {
  color: #08C0B9;
}

.text-over{
    overflow: hidden;
    text-overflow: ellipsis;
    vertical-align: middle;
    white-space: nowrap;
}
.el-icon-arrow-right{
    font-family: element-icons!important;
    speak: none;
    font-style: normal;
    font-weight: 400;
    font-feature-settings: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;
    vertical-align: middle;
    display: inline-block;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    border: 1px solid #D4D4D5;
    border-radius: 50%;
    color: #D4D4D5;
    margin-right: 4px;
}
.el-icon-arrow-right::before{
    content: "\e6e0";
}
.expand-icon{
    display: inline-block;
    width: 20px;
    line-height: 20px;
    height: 20px;
    text-align: center;
    margin-right: 3px;
    font-size: 12px;
}
/deep/ .el-table_1_column_1.is-left  .cell {padding-right: 0px !important;white-space: nowrap;}
/deep/ .el-table__expand-icon .el-icon-arrow-right{
    font-family: element-icons!important;
    speak: none;
    font-style: normal;
    font-weight: 400;
    font-feature-settings: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;
    vertical-align: middle;
    display: inline-block;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    border: 1px solid #3291F8;
    border-radius: 50%;
    color: #3291F8;
    margin-right: 4px;
}
.space-around{
    display: flex;
    justify-content: space-around;
}
.disabled {
    cursor: default;
    pointer-events: none;
    color: rgba(0,0,0,.6) !important;
    opacity: .45 !important;
}

</style>