<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 || implement"
            >所有规则测试</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.row.caseId - 1)"
              :disabled="!runningStatus || implement"
            >
              {{
                runningStatusArr[scope.row.caseId - 1] === 1
                  ? "执行测试中"
                  : implement
                  ? "执行测试"
                  : "执行测试"
              }}
            </el-button>
            <span v-if="runningStatusArr[scope.row.caseId - 1] === 1">|</span>
            <el-button
              v-if="runningStatusArr[scope.row.caseId - 1] === 1"
              type="text"
              size="small"
              @click="handleUpdateStatus(scope.row, scope.row.caseId - 1)"
              >重置</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import api from "@api/knowledgeTree.js";
import config from "@api/config.js";
import utils from "@api/utils.js";
export default {
  name: "AutoKnowledgeMapRuleTest",
  data() {
    return {
      list: [],
      hospitalData: [],
      hospitalId: "", //选中医院
      runningStatusArr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], //知识图谱规则 测试状态
      implement: false,
    };
  },
  computed: {
    runningStatus() {
      return this.runningStatusArr.every((item) => {
        return item === 0;
      });
    },
  },
  created() {
    this.reminder();
    this._getHospitalInfoCDSS();
    this.zskgetDict();
    // this._getRunningStatus()   // 进入页面立即确认状态
    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.hospitalId = to.params.hospitalId;
      vm._getRunningStatus();
    });
  },
  methods: {
    reminder() {
      api
        .reminder({ caseGroup: 1 })
        .then((res) => {
          if (res.data.code == "0") {
            if (res.data.data) {
              this.$message({
                message: res.data.data,
                type: "error",
              });
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getRunningState() {
      api
        .getRunningState({ caseGroup: 1 })
        .then((res) => {
          if (res.data.code == "0") {
            this.implement = res.data.data;
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    zskgetDict() {
      api
        .zskgetDict()
        .then((res) => {
          if (res.data.code == "0") {
            const data = res.data.data;
            const arr = data["31"];
            localStorage.setItem("zskDicts", JSON.stringify(arr));
          }
        })
        .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(0, 15);
        }
      });
    },
    // 重置状态
    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); // 重新获取列表
            this.getRunningState();
          } else {
            this.$message.error(res.data.msg || "重置失败");
            this.getDataList(this.hospitalId); // 重新获取列表
            this.getRunningState();
          }
          this.runningStatusArr = statusTempArr;
        });
    },

    indexMethod(index) {
      return index + 1;
    },
    // 执行测试
    handleTest(row, index) {
      if (this.implement) {
        this._getRunningStatus();
        return 
      }
      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,
      };

      api.autoRuleTest(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, 0, 0, 0, 0, 0, 0];
      });
    },
    // 所有规则测试
    handleAllTest() {
      if (this.hospitalId === "") {
        this.$message({
          message: "请先选择医院",
          type: "warning",
        });
        return;
      }
      if (this.implement) {
        this._getRunningStatus();
      }
      this.runningStatusArr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
      api.allRuleTest({ hospitalId: this.hospitalId }).then((res) => {
        this.runningStatusArr = [0, 0, 0, 0, 0, 0, 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;
      let localAuto = {
        resultId: row.resultId,
        type,
        hospitalName,
        caseName: row.caseName.replace(/\_/, "-"),
      };
      localStorage.setItem("localAuto", JSON.stringify(localAuto));
      this.$router.push({
        name: "AutoBillCommonTest",
        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.getRecordHopitalList().then((res) => {
        if (res.data.code === "0") {
          this.hospitalData = res.data && res.data.data;
        }
      });
    },

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

    // 获取列表数据
    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.autoGetCaseResultList(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.autoExportExcel({ hospitalId: this.hospitalId }).then((res) => {
            if (res.status === 200) {
              this.$message({ message: "导出成功", type: "success" });
              utils.downloadExportedData(res.data, "规则未使用映射关系.xls");
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>

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