<template>
  <div>
    <crumbs title="调用记录" style="min-width: 980px" class="knowledgeTitle">
      <el-button size="mini" type="primary" @click="getInterface" class="btn"
        >各科室接口调用统计</el-button
      >
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="接收时间: ">
          &nbsp;&nbsp;
          <el-date-picker
            v-model="filter.recepDate"
            type="datetimerange"
            align="right"
            size="small"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 320px"
            :class="filter.recepDate === null ? 'active' : ''"
            :default-time="['00:00:00', '23:59:59']"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="响应时间: "
          >&nbsp;&nbsp;
          <el-date-picker
            v-model="filter.resDate"
            type="datetimerange"
            align="right"
            size="small"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 320px"
            :default-time="['00:00:00', '23:59:59']"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
            unlink-panels
          >
          </el-date-picker>
          
        </el-form-item>
        <!-- <el-form-item label="状态：">
          <el-select
            v-model="filter.successFlag"
            clearable
            placeholder="请选择"
            size="mini"
          >
            <el-option
              v-for="item in stateSelect"
              :key="item.successFlag"
              :label="item.name"
              :value="item.successFlag"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="院区：" prop="subHospitalName">
          <el-input
            size="mini"
            v-model="filter.subHospitalName"
            placeholder="输入规则名称"
            clearable
          ></el-input>
        </el-form-item> -->
        <!-- <el-form-item>
          <el-button size="mini" @click="filterDatas">确认</el-button>
        </el-form-item> -->
      </el-form>
      <el-form class="secLine" :inline="true">
        <el-form-item label="患者标识：" prop="patientId">
            <el-input
              size="mini"
              v-model="filter.patientId"
              placeholder="请输入患者标识"
              clearable
              maxlength="50"
            ></el-input>
          </el-form-item>
        <el-form-item label="科室：" prop="deptName">
          <el-input
            size="mini"
            v-model="filter.deptName"
            placeholder="请输入科室"
            clearable
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="服务名：" prop="sceneName">
          <el-input
            size="mini"
            v-model="filter.sceneName"
            placeholder="请输入服务名"
            clearable
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select
            v-model="filter.successFlag"
            clearable
            placeholder="请选择"
            size="mini"
          >
            <el-option
              v-for="item in stateSelect"
              :key="item.successFlag"
              :label="item.name"
              :value="item.successFlag"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子院区：" prop="subHospitalName">
          <el-input
            size="mini"
            v-model="filter.subHospitalName"
            placeholder="请输入子院区"
            clearable
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" @click="filterDatas">检索</el-button>
        </el-form-item>
      </el-form>
    </crumbs>

    <div class="contents knowledgeContents">
      <el-table :data="list" border style="width: 100%" size="mini">
        <!-- <el-table-column type="index" :index="indexMethod" label="编号" width="60"></el-table-column> -->
        <el-table-column label="患者标识" align="center" width="200">
          <template slot-scope="scope">
            <!--<el-tooltip
              v-if="scope.row.parDescription.length>8"
              class="item"
              effect="dark"
              :content="scope.row.parDescription"
              placement="top"
            >
              <span>{{scope.row.parDescription.slice(0,8)+'...'}}</span>
            </el-tooltip>-->
            <span>{{
              scope.row.patientId === null ? "-" : scope.row.patientId
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="科室" align="center">
          <template slot-scope="scope">{{
            scope.row.deptName || "-"
          }}</template>
        </el-table-column>
        <el-table-column label="服务名" align="center">
          <template slot-scope="scope">{{ scope.row.sceneName }}</template>
        </el-table-column>
        <el-table-column
          prop="parConceptName"
          label="请求内容"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="reqData(scope.row)"
              >详情</el-button
            >
            <!--<el-tooltip
              v-if="scope.row.parConceptName.length>8"
              class="item"
              effect="dark"
              :content="scope.row.parConceptName"
              placement="top"
            >
              <span>{{scope.row.parConceptName.slice(0,8)+'...'}}</span>
            </el-tooltip>-->
            <!-- <span>{{scope.row.parConceptName}}</span> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="parLibTypeName"
          label="响应内容"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="respData(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="gmtReq"
          label="接收时间"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="gmtResp"
          label="响应时间"
          align="center"
        ></el-table-column>
        <!-- <el-table-column prop="modifierName" label="操作人">
          <template slot-scope="scope">
            <el-tooltip
              v-if="scope.row.modifierName&&scope.row.modifierName.length>8"
              class="item"
              effect="dark"
              :content="scope.row.modifierName"
              placement="top"
            >
              <span>{{(scope.row.modifierName||'').slice(0,8)+'...'}}</span>
            </el-tooltip>
            <span
              v-if="scope.row.modifierName&&scope.row.modifierName.length<9"
            >{{scope.row.modifierName}}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="execTime"
          label="耗时（ms）"
          align="center"
          width="100"
        ></el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <span>
              {{ scope.row.successFlag === 1 ? "成功" : "失败" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="subHospitalName"
          label="子院区"
          align="center"
          width="180"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>
              {{
                scope.row.subHospitalName === null
                  ? "-"
                  : scope.row.subHospitalName
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="subHospitalCode"
          label="子院区编码"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <span>
              {{
                scope.row.subHospitalCode === null
                  ? "-"
                  : scope.row.subHospitalCode
              }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <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>
      <!-- 请求弹出框 -->
      <el-dialog title="请求日志信息" :visible.sync="reqVisible" width="660px">
        <div class="request-item">
          {{ params }}
        </div>
      </el-dialog>

      <!-- 响应内容弹出框 -->
      <el-dialog title="响应日志信息" :visible.sync="respVisible" width="660px">
        <div class="request-item">{{ result }}</div>
      </el-dialog>

      <el-dialog
        @close="closeInterface"
        title="各科室接口调用统计"
        :visible.sync="dialogTableVisible"
        width="660px"
      >
        <div class="Interface">
          <el-form :inline="true">
            <el-form-item label="日期：">
              <el-date-picker
                v-model="time"
                type="daterange"
                align="right"
                size="small"
                start-placeholder="输入起始日期"
                end-placeholder="输入结束日期"
                style="width: 250px"
                :default-time="['00:00:00', '23:59:59']"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button size="mini" @click="getSure">检索</el-button>
            </el-form-item>
          </el-form>
          <el-table
            :data="gridData"
            border
            size="mini"
            style="width: 100%"
            height="400px"
          >
            <el-table-column property="deptName" label="科室">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.deptName || "-" }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              property="sums"
              label="接口调用总次数"
            ></el-table-column>
          </el-table>
        </div>
        <div class="foot">
          <el-button size="mini" type="primary" @click="closeInterface"
            >关闭</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import api from "@api/knowledgeLib.js";
import config from "@api/config.js";
import utils from "@api/utils.js";

export default {
  name: "ZskRuleManager",
  data: function () {
    return {
      list: [],
      value2: "",
      stateSelect: [
        { successFlag: "", name: "全部" },
        { successFlag: 1, name: "成功" },
        { successFlag: 0, name: "失败" },
      ],
      ruleTypeList: [],
      searched: false,
      filter: {
        successFlag: "",
        patientId: "",
        sceneName: "",
        deptName: "", //科室
        subHospitalName: "", // 子院区
        recepDate: null, // 接收日期
        resDate: null, // 响应日期
      },
      cacheData: {},
      currentPage: 1,
      pageSize: config.pageSize,
      pageSizeArr: config.pageSizeArr,
      pageLayout: config.pageLayout,
      total: 0,
      titleWidth: "970px", //头部最小宽度
      reqVisible: false,
      respVisible: false,
      params: "",
      result: "",
      gmtReq: "",
      dialogTableVisible: false,
      time: null,
      gridData: [],
    };
  },
  created() {
    let that = this;
    //返回时避免参数未赋值就获取列表
    setTimeout(function () {
      that.getDataList();
    });
  },
  computed: {
    //   pickerOptions: {
    //       disabledDate(time) {
    //         return time.getTime() > Date.now()
    //     }
    // }
  },
  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: {
    // 请求内容展示
    reqData(row) {
      console.log("请求内容：", row);
      this.reqVisible = true;
      this.params = row.params;
      console.log("请求内容：", this.params);
    },

    // 响应内容展示
    respData(row) {
      console.log("响应内容：", row);
      this.respVisible = true;
      this.result = row.result;
    },

    statusTrans(type) {
      const obj = this.ruleTypeList.find((it) => it.type === type);
      return obj && obj.name;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = utils.getCurrentPage(
        this.currentPage,
        this.total,
        this.pageSize
      );
      this.getDataList();
    },

    filterDatas() {
      this.currentPage = 1;
      this.getDataList(1);
    },
    //各科室接口调用统计
    getInterface() {
      this.dialogTableVisible = true;
      this.getSure();
    },
    closeInterface() {
      this.dialogTableVisible = false;
      this.time = null;
      this.gridData = [];
    },
    getSure() {
      let params = {
        startGmtReq: this.time ? this.time[0] : "",
        endGmtReq: this.time ? this.time[1] : "",
      };
      api
        .getStatistByDept(params)
        .then((res) => {
          if (res.data.code == "0") {
            this.gridData = res.data.data;
          } else {
            this.warning(res.data.msg || "获取列表数据失败");
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getDataList(flag, isTurnPage) {
      const params = 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
        .getCallRecord(params)
        .then((res) => {
          loading.close();
          if (res.data.code == "0") {
            const data = res.data.data;
            console.log("data???", data);
            for (let j = 0; j < data.records.length; j++) {
              data.records[j].successFlag == "1" ? "成功" : "失败";
            }
            this.list = data.records;
            console.log("调用接口数据：", this.list);
            if (!flag) {
              //搜索时不缓存
              this.cacheData[params.current] = data.records;
            } else {
              this.cacheData = {};
            }
            this.total = data.total;
            console.log("total????", this.total);
            if (this.inCurrentPage !== undefined) {
              this.currentPage = this.inCurrentPage;
              this.inCurrentPage = undefined;
            }
          } else {
            this.warning(res.data.msg || "获取列表数据失败");
          }
        })
        .catch((error) => {
          loading.close();
          console.log(error);
        });
    },
    getFilterItems(isTurnPage) {
      //翻页时筛选条件没点确定则清空
      if (isTurnPage && !this.searched) {
        this.clearFilter();
      }

      //  接收时间 开始时间补0  结束时间补59
      let startGmtReq, endGmtReq, startGmtResp, endGmtResp;
      if (this.filter.recepDate) {
        console.log(this.filter.recepDate[0].split(" "));
        if (
          this.filter.recepDate[0].split(0, 9) ===
          this.filter.recepDate[1].split(0, 9)
        ) {
          if (this.filter.recepDate[0]) {
            startGmtReq = this.filter.recepDate[0] + ":00";
            endGmtReq = this.filter.recepDate[1] + ":59";
          }
        } else {
          startGmtReq = this.filter.recepDate[0] + ":00";
          endGmtReq = this.filter.recepDate[1] + ":59";
        }
      }

      //  响应时间 开始时间补0  结束时间补59
      if (this.filter.resDate) {
        if (
          this.filter.resDate[0].split(0, 9) ===
          this.filter.resDate[1].split(0, 9)
        ) {
          if (this.filter.resDate[0]) {
            startGmtResp = this.filter.resDate[0] + ":00";
            endGmtResp = this.filter.resDate[1] + ":59";
          }
        } else {
          startGmtResp = this.filter.resDate[0] + ":00";
          endGmtResp = this.filter.resDate[1] + ":59";
        }
      }

      const param = {
        current: this.inCurrentPage || this.currentPage,
        size: this.pageSize,
        patientId: this.filter.patientId.trim(), // 患者标识
        sceneName: this.filter.sceneName.trim(), // 服务名
        deptName: this.filter.deptName.trim(), // 服务名
        successFlag: this.filter.successFlag,
        startGmtReq: startGmtReq,
        endGmtReq: endGmtReq,
        startGmtResp: startGmtResp,
        endGmtResp: endGmtResp,
        subHospitalName: this.filter.subHospitalName.trim(), // 子院区
      };
      return param;
    },
    indexMethod(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    currentChange(next) {
      this.currentPage = next;
      /*if (this.cacheData[next]) {       //如果已请求过该页数据，则使用缓存不重复请求
                  this.list = this.cacheData[next];
                } else {*/
      this.getDataList(1, true);
      //}
    },
    warning(msg, type) {
      this.$message({
        showClose: true,
        message: msg,
        type: type || "warning",
      });
    },
    showConfirmDialog(msg, resolve) {
      this.$alert(msg, "提示", {
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          resolve();
        })
        .catch(() => {});
    },
    showDelDialog(row, isDelete) {
      const params = {
        id: row.parId,
      };
      const txt = row.parStatus === 0 ? "重新启用" : "禁用";
      const warningTxt = isDelete
        ? "是否删除该规则？可能对现有系统造成影响"
        : "是否" + txt + "该条数据？";
      const handleFn = isDelete
        ? api.deleteRule
        : row.parStatus === 0
        ? api.saveRuleApply
        : api.deleteRuleApply;
      this.showConfirmDialog(warningTxt, () => {
        handleFn(params)
          .then((res) => {
            if (res.data.code == "0") {
              if (!this.searched) {
                //未点确认时清空搜索条件
                this.clearFilter();
              }
              if (isDelete) {
                //恢复成功后跳转到筛选条件的首页
                this.currentPage = 1;
              } else {
                if (this.filter.parStatus !== "" && this.list.length === 1) {
                  //有启用状态筛选条件且当前页只有最后一条数据删除时，删除成功后跳转到前一页
                  this.currentPage =
                    this.currentPage === 1 ? 1 : this.currentPage - 1;
                }
              }
              this.warning(res.data.msg || "操作成功", "success");
              this.getDataList();
            } else {
              this.warning(res.data.msg);
            }
          })
          .catch((error) => {
            this.warning(error);
          });
      });
    },
    clearFilter() {
      this.filter = {
        successFlag: "",
        patientId: "",
        sceneName: "",
        subHospitalName: "",
        recepDate: "", // 接收日期
        resDate: "", // 响应日期
      };
    },
    update() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      api
        .zskUpdateAll()
        .then((res) => {
          loading.close();
          if (res.data.code == "0") {
            this.warning("更新成功", "success");
            this.getDataList();
          } else {
            this.warning(res.data.msg || "更新失败，请重试");
          }
        })
        .catch((error) => {
          loading.close();
          this.warning("更新失败，请重试");
        });
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../less/admin.less";
/deep/ .container.knowledgeTitle {
  height: 80px;
}
/deep/ .contents.knowledgeContents {
  padding: 104px 20px 0;
}
/deep/ .secLine.el-form {
  float: right;
  display: block;
  position: relative;
  top: -5px;
}
.delete {
  color: red;
}
.review {
  color: #22ccc8;
}
.el-table .cell {
  overflow: hidden;
  white-space: nowrap;
}
#upFile {
  display: none !important;
}
.unvailable {
  color: #fe7d3d;
  &:hover {
    color: #f19061;
  }
}

.demo-form-inline {
  display: flex;
  justify-content: flex-end;
  .el-form-item:nth-child(1) {
    margin-right: 10px;
  }
  .el-input--mini {
    /deep/.el-input__inner {
      width: 100%;
    }
  }
}

.el-date-editor {
  .el-input {
    width: 150px !important;
  }
}

.secLine.el-form {
  position: relative;
  top: -10px;
  color: #ff0000;
}

.code-name {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

/deep/.el-dialog {
  width: 700px !important;
}

/deep/.el-dialog__body {
  overflow-y: auto;
  height: 505px;
  width: 700px;
  padding: 20px 0 30px;
}

.request-item {
  padding: 0 20px;
}

.el-time-panel__footer {
  /deep/.confirm {
    color: #48c5d7 !important;
  }
}

.active {
  color: #ff0000;
}
.btn {
  position: absolute;
  left: 31px;
  top: 50px;
}
.Interface {
  padding: 0 24px;
  .el-table {
    min-width: 100% !important;
  }
}
.foot {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
/deep/.el-input--mini .el-input__inner{
  width: 95px;
}
</style>