<template>
  <div>
    <crumbs title="知识图谱规则测试" class="topBack">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label class="selectMedicine" style="marginbottom: -1px">
          <el-select size="mini" v-model="hospitalId" placeholder="选择医院" @change="handleChange">
            <el-option
              v-for="item in hospitalData"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="marginbottom: 0px">
          <el-button size="mini" @click="exportData">导出图谱中规则未涉及到的医院术语</el-button>
        </el-form-item>
        <el-form-item style="marginbottom: 0px">
          <el-button size="mini" @click="handleAllTest" :disabled="!runningStatus">所有规则测试</el-button>
        </el-form-item>
      </el-form>
    </crumbs>
    <div style="margin: 60px 20px 0">
      <el-table :data="list" border>
        <el-table-column :resizable="false" type="index" :index="indexMethod" label="编号" width="80"></el-table-column>
        <el-table-column :resizable="false" prop="caseName" label="规则类型" show-overflow-tooltip></el-table-column>
        <el-table-column :resizable="false" prop="gmtModified" label="测试时间"></el-table-column>

        <el-table-column :resizable="false" prop="ruleNum" label="总条数" show-overflow-tooltip></el-table-column>
        <el-table-column label="成功条数">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="goToFailedOrSuccessPage(scope.row, 'success')"
              :disabled="runningStatusArr[scope.$index] === 1"
            >{{ scope.row.ruleSuccessNum }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="失败条数">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="goToFailedOrSuccessPage(scope.row, 'failed')"
              :disabled="runningStatusArr[scope.$index] === 1"
            >{{ scope.row.ruleFailedNum }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleTest(scope.row, scope.$index)"
              :disabled="!runningStatus"
            >
              {{
              runningStatusArr[scope.$index] === 1
              ? '执行测试中...'
              : '执行测试'
              }}
            </el-button>
            <span v-if="runningStatusArr[scope.$index] === 1">|</span>
            <el-button
              v-if="runningStatusArr[scope.$index] === 1"
              type="text"
              size="small"
              @click="handleUpdateStatus(scope.row, scope.$index)"
            >重置</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import api from '@api/cdss.js';
import config from '@api/config.js';
import utils from '@api/utils.js';
export default {
  name: 'KnowledgeMapRuleTest',
  data() {
    return {
      list: [],
      hospitalData: [],
      hospitalId: '', //选中医院
      runningStatusArr: [0, 0, 0, 0, 0, 0, 0, 0, 0] //知识图谱规则 测试状态
    };
  },
  computed: {
    runningStatus() {
      return this.runningStatusArr.every(item => {
        return item === 0;
      });
    }
  },
  created() {
    this._getHospitalInfoCDSS();
    // this._getRunningStatus()   // 进入页面立即确认状态
    this.timer = setInterval(this._getRunningStatus, 20 * 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      Object.assign(vm, to.params);
      if (Object.keys(to.params).length === 0) return;
      vm.getDataList(to.params.hospitalId);
      // vm.hospitalId = to.params.hospitalId;
      vm._getRunningStatus();
    });
  },
  methods: {
    _getRunningStatus() {
      const { hospitalId } = this;
      if (this.hospitalId === '') return;
      api.getRunningStatusByHospitalId({ hospitalId }).then(res => {
        if (res.data.code === '0' && res.data.data) {
          this.runningStatusArr = Object.values(res.data.data).slice(0, 9);
        }
      });
    },
    // 重置状态
    handleUpdateStatus(row, index) {
      const { caseId } = row;
      // console.log(index,'index');
      let statusTempArr = [...this.runningStatusArr];
      statusTempArr[index] = 0;
      api
        .updateRunningStatus({
          hospitalId: this.hospitalId,
          caseId,
          status: 0
        })
        .then(res => {
          if (res.data.code === '0' && res.data.data) {
            this.$message({
              message: '重置成功',
              type: 'success'
            });
            this.getDataList(this.hospitalId); // 重新获取列表
          } else {
            this.$message.error(res.data.msg || '重置失败');
            this.getDataList(this.hospitalId); // 重新获取列表
          }
          this.runningStatusArr = statusTempArr;
        });
    },

    indexMethod(index) {
      return index + 1;
    },
    // 执行测试
    handleTest(row, index) {
      this.runningStatusArr = this.runningStatusArr.map((item, idx) => {
        if (idx === index) {
          return 1;
        } else {
          return 0;
        }
      });
      const { caseName, caseId } = row;
      let params = {
        caseId,
        hospitalId: this.hospitalId
      };
      let requestAjax;
      let billType; // 开单合理性规则类型  1  通用  2 输血
      let criticalType; //危急值测试规则类型（1：检验，2：检查）
      let highriskType; //高危测试规则类型（1：药品，2：手术）
      let otherType; // 其他提醒测试规则类型（1：化验，2：辅检，3：输血）
      if (caseName === '开单合理性提醒_通用规则') {
        billType = 1;
        params = { ...params, billType };
        requestAjax = 'billRuleTest';
      } else if (caseName === '开单类型提醒_输血规则') {
        billType = 2;
        params = { ...params, billType };
        requestAjax = 'billRuleTest';
      } else if (caseName === '危机值提醒_实验室检查规则') {
        criticalType = 1;
        params = { ...params, criticalType };
        requestAjax = 'criticalRuleTest';
      } else if (caseName === '危机值提醒_辅助检查规则') {
        criticalType = 2;
        params = { ...params, criticalType };
        requestAjax = 'criticalRuleTest';
      } else if (caseName === '高风险提醒_高危药品规则') {
        highriskType = 1;
        params = { ...params, highriskType };
        requestAjax = 'highRiskRuleTest';
      } else if (caseName === '高风险提醒_高危手术规则') {
        highriskType = 2;
        params = { ...params, highriskType };
        requestAjax = 'highRiskRuleTest';
      } else if (caseName === '其他提醒_化验规则') {
        otherType = 1;
        params = { ...params, otherType };
        requestAjax = 'otherRuleTest';
      } else if (caseName === '其他提醒_输血规则') {
        otherType = 3;
        params = { ...params, otherType };
        requestAjax = 'otherRuleTest';
      } else if (caseName === '其他提醒_辅检规则') {
        otherType = 2;
        params = { ...params, otherType };
        requestAjax = 'otherRuleTest';
      }

      api[requestAjax](params).then(res => {
        if (res.data.code === '0' && res.data.data) {
          this.getDataList(this.hospitalId);
          this.$message({
            message: '测试成功',
            type: 'success'
          });
        } else {
          this.$message.error('测试失败');
          this.getDataList(this.hospitalId);
        }
        this.runningStatusArr = [0, 0, 0, 0, 0, 0, 0, 0, 0];
      });
    },
    // 所有规则测试
    handleAllTest() {
      if (this.hospitalId === '') {
        this.$message({
          message: '请先选择医院',
          type: 'warning'
        });
        return;
      }
      this.runningStatusArr = [1, 1, 1, 1, 1, 1, 1, 1, 1];
      api.ruleAllTest({ hospitalId: this.hospitalId }).then(res => {
        this.runningStatusArr = [0, 0, 0, 0, 0, 0, 0, 0, 0];
        if (res.data.code === '0' && res.data.data) {
          this.getDataList(this.hospitalId);
          this.$message({
            message: '所有规则测试成功',
            type: 'success'
          });
        } else {
          this.$message.error('所有规则测试失败');
          this.getDataList(this.hospitalId);
        }
      });
    },

    // 跳转至失败/成功条数页面
    goToFailedOrSuccessPage(row, type) {
      const page = this.handleGoPage(row.caseName);
      let hospital = this.hospitalData.find(
        item => item.id === this.hospitalId
      );
      let hospitalName = hospital.name;
      this.$router.push({
        name: page,
        params: {
          data: { ...row },
          type,
          hospitalId: this.hospitalId,
          hospitalName
        }
      });
    },
    // 处理跳转到的页面
    handleGoPage(caseName) {
      switch (caseName) {
        case '开单合理性提醒_通用规则':
          return 'BillCommonTest';
        case '开单类型提醒_输血规则':
          return 'BillFusionTest';
        case '危机值提醒_实验室检查规则':
          return 'CriticalLabTest';
        case '危机值提醒_辅助检查规则':
          return 'CriticalAuxTest';
        case '高风险提醒_高危药品规则':
          return 'HighRiskDrugTest';
        case '高风险提醒_高危手术规则':
          return 'HighRiskOperationTest';
        case '其他提醒_化验规则':
          return 'OtherAssayRuleTest';
        case '其他提醒_输血规则':
          return 'OtherFusionRuleTest';
        case '其他提醒_辅检规则':
          return 'OtherAuxRuleTest';
        default:
          return null;
      }
    },

    // 获取医院信息
    _getHospitalInfoCDSS() {
      api.getHospitalInfo().then(res => {
        if (res.data.code === '0') {
          this.hospitalData = res.data && res.data.data;
        }
      });
    },

    // 选中医院
    handleChange(val) {
      if (val === '') return;
      this.getDataList(val);
      this._getRunningStatus(); // 选中后立即请求状态
    },

    // 获取列表数据
    getDataList(id) {
      const params = {
        hospitalId: id
      };
      this.searched = true;
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      api.getCaseResultList(params).then(res => {
        loading.close();
        if (res.data.code === '0') {
          this.list = res.data && res.data.data;
        }
      });
    },
    // 导出
    exportData() {
      if (this.hospitalId === '') {
        this.$message({
          message: '请先选择医院',
          type: 'warning'
        });
        return;
      }
      this.$alert('确定要导出规则未使用映射关系吗？', '', {
        confirmButtonText: '确定',
        title: '提示',
        type: 'warning'
      })
        .then(() => {
          api.exportRuleExcel({ hospitalId: this.hospitalId }).then(res => {
            if (res.status === 200) {
              this.$message({ message: '导出成功', type: 'success' });
              utils.downloadExportedData(res.data, '规则未使用映射关系.xls');
            }
          });
        })
        .catch(() => {});
    }
  }
};
</script>

<style lang="less" scored>
@import '../../../less/admin.less';
</style>