<template>
    <div>
        <crumbs title="模板维护" style="min-width: 980px">
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="模板类型：">
                    <el-select size="mini" v-model="filter.templateType" placeholder="模板类型" clearable>
                        <el-option v-for="item in AdscriptionsType" :label="item.name" :value="item.key" :key="item.key" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="归属：">
                    <el-select size="mini" v-model="filter.tagAdscription" placeholder="归属" clearable>
                        <el-option 
                          v-for="item in Adscriptions" 
                          :label="item.name" 
                          :value="item.val" 
                          :key="item.val" 
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="属于：">
                    <el-select size="mini" v-model="filter.ownTo" placeholder="属于" clearable>
                        <el-option v-if="!!item.name" v-for="item in AdscriptionsOwnTo" :label="item.name" :value="item.conceptId" :key="item.conceptId" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button size="mini" @click="filterDatas">确认</el-button>
                    <el-button size="mini" type="warning" @click="addIndeptTag">添加模板</el-button>
                </el-form-item>
            </el-form>
        </crumbs>
        <div class="contents">
            <el-table
                    :data="list"
                    border
                    style="width: 100%">
                <el-table-column
                        type="index"
                        :index = 'indexMethod'
                        label="编号"
                        :resizable = "false"
                        width="60">
                </el-table-column>
                <el-table-column
                        :resizable = "false"
                        prop="gmtModified"
                        label="操作时间"
                        width="180">
                </el-table-column>
                <el-table-column
                        :resizable = "false"
                        prop="name"
                        label="模板名称">
                </el-table-column>
                <el-table-column
                        :resizable = "false"
                        prop="moduleTypeName"
                        label="模板类型">
                </el-table-column>
                <el-table-column
                        :resizable = "false"
                        prop="relationName"
                        label="属于">
                </el-table-column>
                <el-table-column
                        :resizable = "false"
                        prop="ascriptionName"
                        label="归属">
                </el-table-column>
                <el-table-column
                        :resizable = "false"
                        prop="userName"
                        label="操作人">
                </el-table-column>
                <el-table-column
                        :resizable = "false"
                        prop="operate"
                        label="操作">
                    <template slot-scope="scope">
                        <el-button  @click="modifyIndeptTag(scope.row)" type="text" size="small">修改</el-button>
                        <span style="margin:0 3px;">|</span>
                        <el-button @click="showDelDialog(scope.row.id,scope.row.type)" class="delete" type="text" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <div class="pagination">
            <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/icss.js';
  import config from '@api/config.js';
  import utils from '@api/utils.js';

  export default {
    name: 'TemplateMaintenance',
    data: function() {
      return {
        list: [],
        Adscriptions: [],
        tmpAdscriptions: [],
        AdscriptionsType:[],
        AdscriptionsOwnTo:[],
        searched: false,
        filter: {
          templateType: '', //模板类型
          ownTo: '', //属于科室、慢病
          tagAdscription: '', //标签归属
        },
        currentPage: 1,
        pageSize: config.pageSize,
        pageSizeArr:config.pageSizeArr,
        pageLayout:config.pageLayout,
        total: 0,
        deptAndDisInfo:{},
      }
    },
    created() {
      this.getDropList().then(() => {
        this.getDataList()
      })
      this.getSubTemplate()
    },
    computed:{
      tmpType(){
        return this.filter.templateType
      }
    },
    watch: {
      'filter': {
        handler: function () {
          this.searched = false;
        },
        deep: true
      },
      tmpType(newVal, preVal){
        this.filter.tagAdscription = ''
        //根据类型不同删选归属
        if((newVal+'') && (newVal == 0 || newVal == 1)){
          this.Adscriptions = this.tmpAdscriptions.filter((item) => {
            if(item.val != 4 && item.val != 5 && item.val != 6){
              return item
            }
          })
        }else if(newVal == 2){
          this.Adscriptions = this.tmpAdscriptions.filter((item) => {
            if(item.val != 1 && item.val != 31 && item.val != 22 && item.val != 322){
              return item
            }
          })
        }else{
          this.Adscriptions = this.tmpAdscriptions
        }
        if((newVal+'') != preVal){

          if(newVal == 1){
            this.AdscriptionsOwnTo = this.deptAndDisInfo.deptDTOS;
            this.filter.ownTo = ''
          }else if(newVal == 2){
            this.AdscriptionsOwnTo = this.deptAndDisInfo.disDTOS;
            this.filter.ownTo = ''
          }else{
            this.AdscriptionsOwnTo = []
            this.filter.ownTo = ''
          }
        }
      }
    },
    beforeRouteEnter(to, from, next) {
      next(vm => {
        //const pm = to.param;
        const flt = to.params.filter;
        vm.currentPage = to.params.currentPage||1;
        vm.pageSize = to.params.pageSize || config.pageSize;
        vm.deptAndDisInfo = JSON.parse(localStorage.getItem('deptDis')||null);
        if(flt){
          vm.filter.templateType = flt.templateType;
          setTimeout(function(){
            vm.filter.tagAdscription = flt.tagAdscription;
              vm.filter.ownTo = flt.ownTo;
            });
        }
        vm.inCurrentPage=to.params.currentPage;
      })
    },
    methods: {
      handleSizeChange(val){
        this.pageSize = val;
        this.currentPage = utils.getCurrentPage(this.currentPage, this.total, this.pageSize);
        this.getDataList();
      },
      getSubTemplate() {
        api.getAllDeptAndDisInfo({}).then((res) => {
          if (res.data.code === '0') {//获取科室和疾病所有信息
            let result = res.data.data
            this.deptAndDisInfo = result
            localStorage.setItem('deptDis',JSON.stringify(result))
          }
        })
      },
      getDropList() {
        let templateType = localStorage.getItem('icssEnumsData') ? JSON.parse(localStorage.getItem('icssEnumsData')).moduleInfoTypeEnum : []
        this.AdscriptionsType = templateType
        return api.getDropList().then((res) =>{
          if(res.data.code === '0') {
            this.Adscriptions = res.data.data[4];
            this.tmpAdscriptions = res.data.data[4];
            localStorage.setItem('typeLis',JSON.stringify(res.data.data[4]))
          }
        })
      },
      getDataList(isTurnPage) {
        const param = 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)'
        });
        api.getModuleInfoList(param).then((res) => {
           loading.close()
          if(res.data.code == 0){
            const list = res.data.data.records;
            for (var i = 0; i < list.length; i++) {
              for (var z =  0; z < this.Adscriptions.length; z++) {
                if(list[i].type === this.Adscriptions[z].val) {
                  list[i].typeCn = this.Adscriptions[z].name
                }
              }
            }
            this.list = list;
            this.total = res.data.data.total;
            if(this.inCurrentPage!==undefined){
              this.currentPage=this.inCurrentPage;
              this.inCurrentPage = undefined;
            }
          }
        })
      },
      filterDatas() {
        this.currentPage = 1;
        this.getDataList();
      },
      addIndeptTag() {
        const pam = this.searched ? {
          currentPage: this.currentPage,
          pageSize:this.pageSize,
          filter: this.filter
        } : {currentPage: this.currentPage,
          pageSize:this.pageSize};
        this.$router.push({name: 'TemplateMaintenanceWrap', params: pam})
      },
      modifyIndeptTag(row) {
        // api.detailsTag({ids:row.id}).then((res) => {
        //   if (res.data.code === '0') {//获取科室和疾病所有信息
        //     let result = res.data.data
        //     console.log(result)
        //   }
        // })
        Promise.all([
          api.getModuleInfoOne({moduleId:row.id}),
          api.getModuleDetailInfo({moduleId:row.id,type:row.type})
        ]).then((data)=>{
          let data0 = data[0].data;
          let data1 = data[1].data;
          let allData = {},topMsg={},rightMsg={};
          if(data0.code == 0){
            topMsg = Object.assign({},data0.data);
          }
          if(data1.code == 0){
            rightMsg = Object.assign({},data1);
          }
          allData = Object.assign({}, topMsg, rightMsg);
          const pam = this.searched ? {
            currentPage: this.currentPage,
            filter: this.filter
          } : {currentPage: this.currentPage};
          this.$router.push({
            name: 'TemplateMaintenanceWrap',
            params: Object.assign(pam, {isEdit: true, data: allData})
          });
        })
      },
      currentChange(next) {
        this.currentPage = next;
        this.getDataList(true);
      },
      getFilterItems(isTurnPage) {
        //翻页时筛选条件没点确定则清空
        if(isTurnPage&&!this.searched){
          this.filter={
            templateType: '', //模板类型
            ownTo: '', //属于科室、慢病
            tagAdscription: '', //标签归属
          };
        };
        const param = {
          current: this.inCurrentPage||this.currentPage,
          size: this.pageSize,
          type: this.filter.tagAdscription,
          moduleType:this.filter.templateType,
          relationId:this.filter.ownTo
        };
        return param;
      },
      indexMethod(index) {
        return ((this.currentPage - 1) * this.pageSize) + index + 1;
      },
      warning(msg,type){
        this.$message({
          showClose: true,
          message:msg,
          type:type||'warning'
        })
      },
      showConfirmDialog(msg,resolve){
        this.$alert(msg, '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          resolve();
        }).catch(() => {});
      },
      clearfilter(){
        this.filter={
          templateType: '', //模板类型
          ownTo: '', //属于科室、慢病
          tagAdscription: '', //标签归属
        };
      },
      showDelDialog(id,type){
        this.showConfirmDialog('是否删除该标签？',()=>{
          api.delTemplate({ids:id,type:type}).then((res)=>{
            if(res.data.code=='0'){
              if(!this.searched){
                //未点确认时清空搜索条件
                this.clearfilter();
              }
              if(this.list.length==1){
                //当前在最后一页且只有一条数据时，删除后跳到前一页
                this.currentPage = this.currentPage===1?1:this.currentPage-1;
              }
              this.getDataList();
              this.warning(res.data.msg || '操作成功','success');
            }else{
              this.warning(res.data.msg);
            }
          }).catch((error)=>{
            this.warning(error);
          })
        });
      }
    }
  }
</script>


<style lang="less">
    .delete{
        color: red
    }
    .delete:hover {
        color: red;
    }
</style>