<template>
    <div>
        <crumbs title="质控类型维护">
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="所属医院：">
                    <el-select size="mini" v-model="filter.hospitalId" placeholder="所属医院" clearable>
                        <el-option v-for="item in hisTypes" :label="item.name" :value="item.val" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="质控类型：">
                    <el-input size="mini" v-model="filter.name" placeholder="请输入质控类型"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button size="mini" @click="filterDatas">确认</el-button>
                    <el-button size="mini" type="warning" @click="addBaseField">添加质控类型</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="编号"
                        width="60">
                </el-table-column>
                <el-table-column
                        prop="id"
                        width="100"
                        label="质控ID">
                </el-table-column>
                <el-table-column
                        prop="gmtModified"
                        label="所属医院"
                        :formatter="hisFormatter"
                        :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column
                        prop="name"
                        label="质控类型">
                </el-table-column>
                <!-- <el-table-column :resizable="false" prop="operate" label="默认标准模版">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.defaultModule"
                      :active-value="1"
                      :inactive-value="0"
                      active-color="#4BC4D7"
                      inactive-color="#BBBBBB"
                      @change="handleTemChange(scope.row)"
                    ></el-switch>
                  </template>
                </el-table-column> -->
                <el-table-column
                        label="操作" width="150">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="ifUnbindDialog(scope.row, 'modify')">修改</el-button>
                        <span style="margin:0 3px;">|</span>
                        <el-button type="text" size="small" @click="toEditField(scope.row, 'copy')">复制</el-button>
                        <span style="margin:0 3px;">|</span>
                        <el-button type="text" size="small" class="delete" @click="ifUnbindDialog(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-if="total>pageSize"
                           :current-page.sync="currentPage"
                           @current-change="currentChange"
                           background
                           :page-size="pageSize"
                           layout="total,prev, pager, next, jumper"
                           :total="total">
            </el-pagination>
        </div>

    </div>
</template>

<script>
  import api from '@api/qualityControl.js';

  export default {
    name: 'QCTypeMang',
    data: function () {
      return {
        list: [],
        tagType:[1],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        searched:false,
        hisTypes:[],
        filter: {
          hospitalId:'',
          name: ''
        }
      }
    },
    created() {
      const _this=this;
      setTimeout(function() {
        _this.getAllTypes()
      },100);
    },
    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: {
      // 默认标准模版切换
      handleTemChange(row) {
        // console.log(row, 'row');
        let params = {
          defaultModule: row.defaultModule,
          defineType: 0,
          hospitalId: row.hospitalId,
          id: row.id,
          modeId: row.modeId,
          name: row.name
        };

        api.ControModuleInfo(params).then(res => {
          // console.log(res.data);
          if (res.data.code === '-1') {
            // 互斥
            this.$alert('默认标准类型已存在，是否替换？', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
              .then(() => {
                params = { ...params, defineType: 1 };
                api.ControModuleInfo(params).then(res => {
                  // console.log(res,'互斥再次请求的接口返回');
                  this.getDataList();
                });
              })
              .catch(() => {
                this.getDataList();
              });
          } else if (res.data.code === '0') {
            // 不互斥
            this.getDataList();
          }
        });      
      },
      hisFormatter(item){
        const field = this.hisTypes.filter((it)=>it.val==item.hospitalId);
        return field[0]?field[0].name:'';
      },
      getAllTypes(){
        /*if(localStorage.getItem("qcHospitalTypes")){
          this.hisTypes = JSON.parse(localStorage.getItem("qcHospitalTypes"));
          this.getDataList();
          return ;
        }*/
        //获取枚举信息
        api.getQcTypes().then((res)=>{
          if(res.data.code==="0"){
            const data = res.data.data;
            //localStorage.setItem("qcHospitalTypes",JSON.stringify(data[13]));
            this.hisTypes =data[13];
            this.getDataList();
          }else{
            this.warning("获取枚举信息失败");
          }
        });
      },
      addBaseField(){
        const pam = this.searched ? {
          currentPage: this.currentPage,
          filter: this.filter
        } : {currentPage: this.currentPage};
        this.$router.push({name: 'AddQcType', params: pam});
      },
      toEditField(row,type){
        api.getQcTypeDetail({hospitalId:row.hospitalId,id:row.id}).then((res)=>{
          const {code,data,msg} = res.data;
          if(code=='0'){
            const item = Object.assign({},row,data);
            const pam = this.searched ? {
              currentPage: this.currentPage,
              filter: this.filter
            } : {currentPage: this.currentPage};
            if(type == 'modify') {
              this.$router.push({name: 'AddQcType', params: Object.assign(pam, {isEdit: true, info: item})});
            } else if( type == 'copy') {
              this.$router.push({name: 'AddQcType', params: Object.assign(pam, {isCopy: true, info: item})});
            } else {
              return
            }
          }else{
            this.$message({
              message: msg,
              type: 'warning'
            });
          }
        });
        // this.$router.push({
        //   name:'FieldMatch',
        //   params: {info:row}
        // })
      },
      filterDatas(){
        this.currentPage = 1;
        this.getDataList();
      },
      getDataList() {
        const param = this.getFilterItems();
        this.searched = true;
        api.getQcTypeList(param).then((res) => {
          if (res.data.code == '0') {
            const data = res.data.data;
            this.list = data.records;
            this.total = data.total;
          }
        }).catch((error) => {
          console.log(error);
        });
      },
      getFilterItems() {
        const param = Object.assign({
          current: this.currentPage,
          size: this.pageSize
        },this.filter);
        return param;
      },
      indexMethod(index) {
        return ((this.currentPage - 1) * this.pageSize) + index + 1;
      },
      currentChange(next) {
        this.currentPage = next;
        this.getDataList();
      },
      warning(msg,type){
        this.$message({
          showClose: true,
          message:msg,
          type:type||'warning'
        })
      },
      showConfirmDialog(msg,resolve,okText){
        this.$confirm(msg, '提示', {
          confirmButtonText: okText||'确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resolve();
        }).catch(() => {});
      },
      ifUnbindDialog(data,type){
        api.ifNeedUnbind({id:data.id,hospitalId:data.hospitalId,cancel:null}).then((res)=>{
        const {code,msg} = res.data;
          if(code==='00000005'){
            this.showConfirmDialog(msg,()=>{
              this.unbindQcType(data,type);
            },'解绑');
          }else{
            if(type==='modify'){
              this.toEditField(data,type);     //编辑
            }else{
              this.showDelDialog(data);     //删除
            }
          }
        }).catch((error)=>{
          this.warning(error);
        })
      },
      unbindQcType(data,type){
        api.ifNeedUnbind({id:data.id,hospitalId:data.hospitalId,cancel:1}).then((res)=>{
          if(res.data.code=='0'){
            this.warning(res.data.msg||'解绑成功','success');
            if(type==='modify'){
              this.toEditField(data,type);     //编辑
            }else{
              this.showDelDialog(data);     //删除
            }
          }else{
            this.warning(res.data.msg);
          }
        }).catch((error)=>{
          this.warning(error);
        })
      },
      showDelDialog(row){
        this.showConfirmDialog('是否删除该质控类型？',()=>{
          api.delQcType({ids:[row.id]}).then((res)=>{
            if(res.data.code=='0'){
              this.warning(res.data.msg||'操作成功','success');
              this.getDataList();
            }else{
              this.warning(res.data.msg);
            }
          }).catch((error)=>{
            this.warning(error);
          })
        });
      }
    }
  }
</script>

<style lang="less">
    @import "../../less/admin.less";
    .delete{
        color: red !important;
    }
    .el-message-box__btns .el-button--default span{
        color: @adminBase;
    }
    .el-message-box__btns .el-button--primary span{
        color: #fff;
    }
</style>