<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>
    </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="totleNum"
          label="医院术语总条数"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="未映射到标准术语条数">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="goToInnerPage(scope.row, 'noMap')"
              :disabled="runningStatusArr[scope.$index] === 1"
              >{{ scope.row.unMappingNum }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="缺少静态知识术语条数">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="goToInnerPage(scope.row, 'lessStatic')"
              :disabled="runningStatusArr[scope.$index] === 1"
              >{{ scope.row.withoutKnowledgeNum }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <input
              type="file"
              name="uploadfile "
              id="upFile"
              @change="uploadFile($event)"
            />
            <el-button
              type="text"
              size="small"
              :disabled="!runningStatus || implement"
              @click="handleTest(scope.row, scope.$index)"
              >{{
                runningStatusArr[scope.$index] === 1
                  ? '执行测试中...'
                  :implement?'执行测试'
                  : '执行测试'
              }}</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: '', //选中医院
      type: '',
      caseId: '',
      runningStatusArr: [0, 0, 0, 0, 0],
      statusIndex: '',
      implement: false
    };
  },
  computed: {
    runningStatus() {
      return this.runningStatusArr.every((item) => {
        return item === 0;
      });
    },
  },
  created() {
    this._getHospitalInfoCDSS();
    this.timer = setInterval(this._getRunningStatus, 20 * 1000);
    this.timer = setInterval(this.getRunningState, 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._getRunningStatus();
    });
  },
  methods: {
    getRunningState() {
      api
        .getRunningState({ caseGroup: 1 })
        .then(res => {
          if (res.data.code == '0') {
            this.implement = res.data.data
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    _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(9, 14);
        }
      });
    },
    indexMethod(index) {
      return index + 1;
    },
    // 获取医院信息
    _getHospitalInfoCDSS() {
      api.getHospitalInfo().then((res) => {
        if (res.data.code === '0') {
          this.hospitalData = res.data && res.data.data;
        }
      });
    },
    handleType(caseName) {
      switch (caseName) {
        case '诊断':
          return 1;
        case '检验':
          return 2;
        case '检查':
          return 3;
        case '药品':
          return 4;
        case '手术/操作':
          return 5;
        default:
          return null;
      }
    },
    // 重置状态
    handleUpdateStatus(row, index) {
      const { caseId } = row;
      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); // 重新获取列表
            this.getRunningState()
          } else {
            this.$message.error(res.data.msg || '重置失败');
            this.getDataList(this.hospitalId); // 重新获取列表
            this.getRunningState()
          }
          this.runningStatusArr = [0, 0, 0, 0, 0];
        });
    },

    // 执行测试
    handleTest(row, index) {
      let inp = document.getElementById('upFile');
      inp.click();
      const { caseName, caseId } = row;
      this.type = this.handleType(caseName); //术语类型（1：诊断、2：检验、3：检查、4：药品、5：手术/操作）
      this.caseId = caseId; //测试用例id
      this.statusIndex = index;
    },

    // 导入数据
    uploadFile(e) {
      if (this.statusIndex !== '') {
        this.runningStatusArr = this.runningStatusArr.map((item, idx) => {
          if (idx === this.statusIndex) {
            return 1;
          } else {
            return 0;
          }
        });
      }
      let fileInfo = e.target.files[0];
      e.preventDefault();
      let formData = new FormData();
      formData.append('file', fileInfo);
      formData.append('hospitalId', this.hospitalId);
      formData.append('type', this.type);
      formData.append('caseId', this.caseId);
      const header = {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      };
      api.staticKnowledgeTest(formData, header).then((res) => {
        if (res.data.code === '00000001') {
          this.$message.error(res.data.msg || '数据存在异常');
          this.getDataList(this.hospitalId); // 重新获取列表
        } else 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 = [0, 0, 0, 0, 0];
      });
      //解决上传相同文件不触发change
      let inp = document.getElementById('upFile');
      inp.value = '';
    },

    // 跳转至未映射到标准术语条数页面 / 缺少静态知识术语条数
    goToInnerPage(row, type) {
      let hospital = this.hospitalData.find(
        (item) => item.id === this.hospitalId
      );
      let hospitalName = hospital.name;
      this.$router.push({
        name: 'LessStaticOrNoMap',
        params: {
          data: { ...row },
          hospitalId: this.hospitalId,
          hospitalName,
          type,
        },
      });
    },

    // 选中医院
    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.getStaticCaseResultList(params).then((res) => {
        loading.close();
        if (res.data.code === '0') {
          this.list = res.data && res.data.data;
        }
      });
    },
  },
};
</script>

<style lang="less" scored>
@import '../../../less/admin.less';
#upFile {
  display: none !important;
}
</style>