<template>
    <div>
        <crumbs title="规则维护" :minWidth="titleWidth" class="knowledgeTitle">
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="规则名称：">
                    <el-input size="mini" v-model="filter.ruleName" placeholder="输入规则名称"></el-input>
                </el-form-item>
                <el-form-item label="规则类型：">
                    <el-select v-model="filter.type" clearable placeholder="请选择" size="mini">
                        <el-option
                                v-for="item in typeList"
                                :key="item.key"
                                :label="item.name"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="术语名称：">
                    <el-input size="mini" v-model="filter.termName" placeholder="输入术语名称"></el-input>
                </el-form-item>
                <el-form-item label="状态：">
                    <el-select v-model="filter.isState" clearable placeholder="请选择" size="mini">
                        <el-option
                                v-for="item in stateSelect"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button size="mini" @click="filterDatas">确认</el-button>
                </el-form-item>
            </el-form>
            <el-form class="secLine">
                <el-form-item>
                    <el-button size="mini" @click="addRule" type="warning" style="margin:0 10px">+ 新增规则</el-button>
                    <input type="file" name="uploadfile " id="upFile" @change="uploadFile($event)" accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
                    <el-button size="mini" @click="uploadClick">加载词库</el-button>
                </el-form-item>
            </el-form>
        </crumbs>
        <div class="contents knowledgeContents">
            <el-table :data="list"
                      border
                      style="width: 100%">
                <el-table-column
                        type="index"
                        :index="indexMethod"
                        label="编号"
                        width="60">
                </el-table-column>
                <el-table-column
                        prop="ruleName"
                        label="规则名称">
                </el-table-column>
                <el-table-column
                        prop="ruleType"
                        label="规则类型">
                </el-table-column>
                <el-table-column
                        prop="conceptName"
                        label="术语名称">
                </el-table-column>
                <el-table-column
                        prop="libTypeName"
                        label="医学标准术语"
                        width="160">
                </el-table-column>
                <el-table-column
                        prop="hasSubCond"
                        label="有无子条件"
                        width="100">
                    <template slot-scope="scope">
                        {{scope.row.hasSubCond === '0'?'无':'有'}}
                    </template>
                </el-table-column>
                <el-table-column
                        prop="msg"
                        label="附加信息"
                        width="160">
                </el-table-column>
                <el-table-column
                        label="状态">
                    <template slot-scope="scope">
                          <span>
                            {{scope.row.status === '0'?'禁用':'启用'}}
                          </span>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="modifier"
                        label="操作人">
                </el-table-column>
                <el-table-column
                        prop="gmtModified"
                        label="操作时间"
                        width="150">
                </el-table-column>
                <el-table-column
                        label="操作"
                        width="180">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="editData(scope.row)">修改</el-button>
                        <span style="margin:0 3px;">|</span>
                        <el-button type="text" size="small" @click="copyData(scope.row)">复制</el-button>
                        <span style="margin:0 3px;">|</span>
                        <el-button type="text" size="small" :class="scope.row.status === '0'?'':'delete'" @click="showDelDialog(scope.row)">{{scope.row.status === '0'?'启用':'禁用'}}</el-button>
                        <span style="margin:0 3px;">|</span>
                        <el-button type="text" size="small" class="delete" @click="showDelDialog(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination :current-page.sync="currentPage"
                           @current-change="currentChange"
                           background
                           :page-size="pageSize"
                           :page-sizes="pageSizeArr"
                           @size-change="handleSizeChange"
                           :layout="pageLayout"
                           :total="total">
            </el-pagination>
        </div>

    </div>
</template>

<script>
    import api from '@api/knowledgeLib.js';
    import config from '@api/config.js';
    import utils from '@api/utils.js';

    export default {
        name: 'ZskRuleManager',
        data: function () {
            return {
                list: [],
                stateSelect:[
                    {id:'1',name:'启用'},
                    {id:'0',name:'禁用'},
                ],
                searched: false,
                filter:{
                    isState:'',
                    ruleName:'',
                    termName:'',
                    type:'',
                },
                cacheData: {},
                currentPage: 1,
                pageSize: config.pageSize,
                pageSizeArr:config.pageSizeArr,
                pageLayout:config.pageLayout,
                total: 0,
                typeList:[],
                titleWidth:'1070px' //头部最小宽度
            }
        },
        created() {
            const typeList = JSON.parse(localStorage.getItem("knowledgeEnumsData"));
            if(typeList){
                this.typeList = typeList.lexiconRSTypeEnum;
            }
            const that = this;
            //返回时避免参数未赋值就获取列表
            setTimeout(function(){
                that.getDataList();
            });
        },
        watch: {
            'filter': {
                handler: function () {
                    this.searched = false;
                },
                deep: true
            }
        },
        beforeRouteEnter(to, from, next) {
            next(vm => {
                //const pm = to.param;
                Object.assign(vm, to.params);
                vm.inCurrentPage=to.params.currentPage;
            })
        },
        methods: {
            handleSizeChange(val){
                this.pageSize = val;
                this.currentPage = utils.getCurrentPage(this.currentPage, this.total, this.pageSize);
                this.getDataList();
            },
            addRule(){
                const pam = this.searched ? {
                    currentPage: this.currentPage,
                    pageSize:this.pageSize,
                    filter: this.filter
                } : {currentPage: this.currentPage,
                    pageSize:this.pageSize};
                this.$router.push({name: 'AddZskRule', params: pam});
            },
            filterDatas(){
                this.currentPage = 1;
                this.getDataList(1);
            },
            getDataList(flag,isTurnPage) {
                const params = this.getFilterItems(isTurnPage);
                this.searched = true;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });loading.close()
                /*api.getRulesList(params).then((res) => {

                    if (res.data.code == '0') {*/
                const data={pages:1,size: 10,total: 1,records:[{id:'0',gmtModified:'5001-220',modifier:'32',conceptName:'单独',description:"ee",ruleType:'1',hasSubCond:'1',status:'1',msg:'ff'}]};
                        //const data = res.data.data;
                        for(let j = 0;j < data.records.length;j++){
                            data.records[j].condition = (data.records[j].isDeleted == '1'?'启用':'禁用')
                        }
                        this.list = data.records;
                        if(!flag){//搜索时不缓存
                            this.cacheData[params.current] = data.records;
                        }else{
                            this.cacheData = {}
                        }
                        this.total = data.total;
                        if(this.inCurrentPage!==undefined){
                            this.currentPage=this.inCurrentPage;
                            this.inCurrentPage = undefined;
                        }
                /*    }
                }).catch((error) => {
                    loading.close()
                    console.log(error);
                });*/
            },
            getFilterItems(isTurnPage) {
                //翻页时筛选条件没点确定则清空
                if(isTurnPage&&!this.searched){
                    this.clearFilter();
                };
                const param = {
                    current: this.inCurrentPage||this.currentPage,
                    size: this.pageSize,
                    relationId: this.filter.type,
                    startName: this.filter.ruleName.trim(),
                    endName: this.filter.termName.trim(),
                    isDeleted:this.filter.isState
                };
                return param;
            },
            indexMethod(index) {
                return ((this.currentPage - 1) * this.pageSize) + index + 1;
            },
            currentChange(next) {
                this.currentPage = next;
                /*if (this.cacheData[next]) {       //如果已请求过该页数据，则使用缓存不重复请求
                  this.list = this.cacheData[next];
                } else {*/
                this.getDataList(1,true);
                //}
            },
            warning(msg,type){
                this.$message({
                    showClose: true,
                    message:msg,
                    type:type||'warning'
                })
            },
            showConfirmDialog(msg,resolve){
                this.$alert(msg, '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                }).then(() => {
                    resolve();
                }).catch(() => {});
            },
            copyData(){

            },
            editData(){

            },
            showDelDialog(item){
                const params = {
                    id:item.id,
                    isDeleted:item.isDeleted === 'N'?'Y':'N'
                }
                let warningTxt = item.isDeleted === 'N'?'是否删除该关系？可能对现有系统造成影响':'是否重新启用该条数据？'
                this.showConfirmDialog(warningTxt,()=>{
                    api.delKnowledgeRelation(params).then((res)=>{
                        if(res.data.code=='0'){
                            if(!this.searched){
                                //未点确认时清空搜索条件
                                this.clearFilter();
                            }
                            if(item.isDeleted !== 'N'){       //恢复成功后跳转到筛选条件的首页
                                this.currentPage = 1;
                            } else {
                                if (this.filter.isState!==''&&this.list.length === 1){
                                    //有启用状态筛选条件且当前页只有最后一条数据删除时，删除成功后跳转到前一页
                                    this.currentPage = this.currentPage===1?1:this.currentPage-1;
                                }
                            }
                            this.warning(res.data.msg||'操作成功','success');
                            this.getDataList();
                        }else{
                            this.warning(res.data.msg);
                        }
                    }).catch((error)=>{
                        this.warning(error);
                    })
                });
            },
            clearFilter(){
                this.filter={
                    isState:'',
                    startName:'',
                    endName:'',
                    type:'',
                };
            },
            uploadClick(){
                let inp = document.getElementById("upFile");
                inp.click();
            },
            uploadFile(e){
                let fileInfo = e.target.files[0];
                e.preventDefault();
                let formData = new FormData();
                formData.append('uploadfile', fileInfo);
                const header = {
                    headers:{
                        'Content-Type': 'multipart/form-data'
                    }
                }
                api.RelationUpload(formData,header).then((res)=>{
                    if(res.data.code==0){
                        this.$message({
                            message: '上传成功',
                            type: 'success',
                        });
                        this.getDataList()
                    }else{
                        this.$alert(res.data.msg,'错误信息',{
                            dangerouslyUseHTMLString: true,
                            confirmButtonText: '确定',
                            callback: action => {
                                /*this.$message({
                                  type: 'info',
                                  message: `action: ${ action }`
                                });*/
                            }
                        });
                    }
                })
                this.getDataList();
                //解决上传相同文件不触发change
                let inp = document.getElementById("upFile");
                inp.value = "";

            }
        }
    }
</script>

<style lang="less" scoped>
    @import "../../less/admin.less";
    /deep/ .container.knowledgeTitle {
        height: 80px;
    }
    /deep/ .contents.knowledgeContents {
        padding: 104px 20px 0;
    }
    /deep/ .secLine.el-form {
        float: right;
        display: block;
        position: relative;
        top: -5px;
    }
    .delete{
        color: red;
    }
    .review{
        color: #22ccc8;
    }
    .el-table .cell{
        overflow: hidden;
        white-space: nowrap;
    }
    #upFile{
        display: none !important;
    }
</style>