<template>
  <div>
    <crumbs title="量表结构维护" style="min-width: 980px">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="量表名称：">
          <el-input size="mini" v-model="filter.tagSysName" placeholder="量表名称" clearable></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-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="80"></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 label="状态">
          <template slot-scope="scope">
            <span
              :class="scope.row.isDeleted == 'N'?'':'delete'"
            >{{scope.row.isDeleted == 'N'?'启用中':'已删除'}}</span>
          </template>
        </el-table-column>
        <el-table-column :resizable="false" prop="modifier" label="操作人"></el-table-column>
        <el-table-column :resizable="false" label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.isDeleted != 'N'"
              @click="modifyIndeptTag(scope.row)"
            >修改</el-button>
            <span style="margin:0 3px;">|</span>
            <el-button
              type="text"
              size="small"
              :class="scope.row.isDeleted == 'N'?'delete':'review'"
              @click="showDelDialog(scope.row)"
            >{{scope.row.isDeleted == 'N'?'删除':'恢复'}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination pagepage">
      <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: [],
      stateSelect: [
        { id: 'N', name: '启用中' },
        { id: 'Y', name: '已删除' }
      ],

      tagTypes: [],
      AdscriptionsType: [],
      AdscriptionsOwnTo: [],
      tagTypesList: [],
      searched: false,
      filter: {
        isState: '',
        tagType: [], //标签类型
        tagSysName: '' //标签系统名称
      },
      currentPage: 1,
      pageSize: config.pageSize,
      pageSizeArr: config.pageSizeArr,
      pageLayout: config.pageLayout,
      total: 0
    };
  },
  created() {
    this.getDropList().then(() => {
      this.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();
    },
    getDropList() {
      let templateType = localStorage.getItem('icssEnumsData')
        ? JSON.parse(localStorage.getItem('icssEnumsData')).moduleInfoTypeEnum
        : [];
      this.AdscriptionsType = templateType;
      return api.getknowledgeList().then(res => {
        if (res.data.code === '0') {
          localStorage.setItem(
            'DiseaseManage',
            JSON.stringify(res.data.data[1])
          );
          // this.tagTypes =  res.data.data[6];
          // for (var i = 0; i < this.tagTypes.length; i++) {
          //   this.tagTypesList.push(this.tagTypes[i].val)
          // }
        }
      });
    },
    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.scaleContentStructure(param).then(res => {
        loading.close();
        const list = res.data.data.records;
        // for (var i = 0; i < list.length; i++) {
        //   for (var j =  0; j < this.tagTypes.length; j++) {
        //     if(list[i].tagType === this.tagTypes[j].val) {
        //       list[i].tagTypeCn = this.tagTypes[j].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: 'ChronicDiseaseAdd', params: pam });
    },
    modifyIndeptTag(row) {
      api.rebuildOrUpdate({ conceptId: row.conceptId }).then(res => {
        const { code, data, msg } = res.data;
        if (code == '0') {
          const pam = this.searched
            ? {
                currentPage: this.currentPage,
                pageSize: this.pageSize,
                filter: this.filter
              }
            : { currentPage: this.currentPage, pageSize: this.pageSize };
          this.$router.push({
            name: 'ChronicDiseaseAdd',
            params: Object.assign(pam, { isEdit: true, data: data, row: row })
          });
        } else {
          this.$message({
            message: msg,
            type: 'warning'
          });
        }
      });
    },
    currentChange(next) {
      this.currentPage = next;
      this.getDataList(true);
    },
    getFilterItems(isTurnPage) {
      //翻页时筛选条件没点确定则清空
      if (isTurnPage && !this.searched) {
        this.clearFilter();
      }
      const param = {
        current: this.inCurrentPage || this.currentPage,
        size: this.pageSize,
        name: this.filter.tagSysName.trim(),
        status: this.filter.isState
      };
      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 = {
        isState: '',
        tagType: [], //标签类型
        tagSysName: '' //标签系统名称
      };
    },
    showDelDialog(item) {
      let tmpArr = [];
      tmpArr.push(item.conceptId);
      const param = {
        ids: tmpArr,
        status: item.isDeleted === 'N' ? 'Y' : 'N'
      };
      let waringTxt =
        item.isDeleted === 'N'
          ? '是否删除该标准术语？'
          : '是否重新启用该条数据？';
      this.showConfirmDialog(waringTxt, () => {
        api
          .deleteScale(param)
          .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 {
              if (err.code === '900010001') {
                return false;
              }
              this.warning(res.data.msg);
            }
          })
          .catch(error => {
            if (error.code === '900010001') {
              return false;
            }
            this.warning(error);
          });
      });
    }
  }
};
</script>


<style lang="less">
.delete {
  color: red;
}
.cell .el-button.delete:active {
  color: red !important;
}
.delete:hover {
  color: red;
}
</style>