<template>
  <div class="main-contain">
    <div class="position">
      <bread-crumb :crumbs="crumbs"></bread-crumb>
    </div>
    <div class="app-container">
      <el-tabs
        v-model="tabActiveName"
        @tab-click="handleTabClick"
        style="margin-bottom:10px"
      >
        <el-tab-pane label="指标控制" name="control"></el-tab-pane>
        <el-tab-pane label="指标查询" name="query"></el-tab-pane>
      </el-tabs>

      <div class="cell clearfix">
        <label class="title"> <span class="name">日期查询</span> : </label>
        <el-date-picker
          v-model="listQuery.start_time"
          prefix-icon="el-icon-date"
          @change="changeTime"
          :editable="false"
          style="width: 196px;"
          type="date"
          placeholder="选择日期时间"
          align="right"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
        <span class>-</span>
        <el-date-picker
          v-model="listQuery.end_time"
          prefix-icon="el-icon-date"
          @change="changeEndTime"
          :editable="false"
          style="width: 196px;"
          type="date"
          placeholder="选择日期时间"
          align="right"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </div>
      <div class="cell clearfix">
        <label class="title"> <span class="name">透析龄</span> : </label>
        <div class="time">
          <ul class>
            <li
              :class="item.value == dialysisAge ? 'active' : ''"
              @click="selectdialysisAges(item.value)"
              v-for="item in dialysisAgeOptions"
              :key="item.value"
            >
              {{ item.label }}
            </li>
          </ul>
        </div>
      </div>
      <div class="cell clearfix">
        <label class="title"> <span class="name">转归状态</span> : </label>
        <div class="time">
          <ul class>
            <li
              :class="item.lapseto == lapsetoType ? 'active' : ''"
              @click="selectLapseTo(item.lapseto)"
              v-for="item in lapsetoState"
              :key="item.value"
            >
              {{ item.label }}
            </li>
          </ul>
        </div>
      </div>

      <div class="cell clearfix">
        <!-- <label class="title">
          <span class="name">检验项目</span> :
        </label>
        <el-select v-model="listQuery.project_id" placeholder="请选择" @change="changeModel()">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="item in projectOptions" :key="item.project_id" :label="item.project_name" :value="item.project_id"></el-option>
        </el-select>
        &nbsp;&nbsp;&nbsp;&nbsp; -->
        <label class="title"> <span class="name">监测指标</span> : </label>
        <el-select
          v-model="listQuery.item_id"
          placeholder="请选择"
          @change="changeItem()"
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="item in itemOptions"
            :key="item.id"
            :label="item.item_name"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>

      <div class="cqd-dataTitle">统计图</div>
      <el-row :gutter="32">
        <el-col :xs="24" :sm="24" :lg="24">
          <div class="chart-wrapper">
            <pie-chart title="" :options="CompletionOptions" />
          </div>
        </el-col>
      </el-row>

      <div style="height:20px">&nbsp;</div>
      <div class="cqd-dataTitle">统计表</div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        id="oictable"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-top: 10px;"
        :row-style="{ color: '#303133' }"
        :header-cell-style="{
          backgroundColor: 'rgb(245, 247, 250)',
          color: '#606266'
        }"
      >
        <el-table-column
          fixed
          label="透析号"
          width="80"
          property="patient_id"
          align="center"
        >
          <template slot-scope="scope"
            ><span>{{
              getPatientDialysisNo(scope.row.patient_id)
            }}</span></template
          >
        </el-table-column>
        <el-table-column
          fixed
          label="姓名"
          width="100"
          property="patient_id"
          align="center"
        >
          <template slot-scope="scope"
            ><span>{{ getPatientName(scope.row.patient_id) }}</span></template
          >
        </el-table-column>
        <el-table-column
          fixed
          label="检查日期"
          width="100"
          property="inspect_date"
          align="center"
        >
          <template slot-scope="scope"
            ><span>{{
              getTime(scope.row.inspect_date, "{y}{m}{d}")
            }}</span></template
          >
        </el-table-column>

        <el-table-column
          :label="reference.item_name + '//' + reference.unit"
          :min-width="itemWight(reference, index)"
          align="center"
          v-for="(reference, index) in activeReferences"
          :key="index"
          :render-header="renderheader"
        >
          <template slot-scope="scope"
            ><span>{{
              getItemVulue(reference.project_id, reference.id, scope.row)
            }}</span></template
          >
        </el-table-column>
      </el-table>

      <!-- <pagi-nation title="分页"></pagi-nation> -->

      <el-pagination
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.pate"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        background
        style="margin-top:20px;"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { GetOICData } from "@/api/qcd";
import PieChart from "../components/PieChart";
import { uParseTime } from "@/utils/tools";
import BreadCrumb from "@/xt_pages/components/bread-crumb";
export default {
  name: "dialysisTotal",
  data() {
    return {
      crumbs: [
        { path: false, name: "质控管理" },
        { path: false, name: "结果指标" },
        { path: false, name: "指标控制" }
      ],
      tabActiveName: "control",
      total: 0,
      projectOptions: {},
      itemOptions: [],
      itemOptionsMap: { 17: 1, 35: 1, 36: 1, 37: 1, 49: 1, 46: 1, 48: 1 },
      patientMap: {},
      CompletionOptions: {
        legend: [],
        series: []
      },
      listQuery: {
        start_time: "",
        end_time: "",
        page: 1,
        limit: 10,
        lapseto: 0,
        project_id: "",
        item_id: "",
        dialysis_age: 0
      },
      tableData: [],
      references: [],
      lapsetoType: 0,
      lapsetoState: [
        { value: 0, label: "全部", source: 0, lapseto: 0 },
        { value: 1, label: "转出", source: 0, lapseto: 2 },
        { value: 2, label: "留治", source: 0, lapseto: 1 }
      ],
      dialysisAge: 0,
      dialysisAgeOptions: [
        { value: 0, label: "全部" },
        { value: 1, label: "大于三个月" },
        { value: 2, label: "小于三个月" }
      ]
    };
  },
  created() {
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth() + 1;
    var nowDay = nowDate.getDate();
    this.listQuery.end_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    nowDate.setMonth(nowDate.getMonth() - 3);
    nowYear = nowDate.getFullYear();
    nowMonth = nowDate.getMonth() + 1;
    nowDay = nowDate.getDate();
    this.listQuery.start_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    this.getList();
  },
  methods: {
    itemWight(reference, index) {
      var width = 70;
      switch (index) {
        case 0:
          width = 110;
          break;
        case 1:
        case 3:
          width = 100;
          break;
        case 2:
          width = 160;
          break;

        default:
          break;
      }
      return width;
      // if(typeof(reference.item_name) !='undefined') {
      //   console.log("reference.item_name.length * 20", reference.item_name.length * 20);
      //   return reference.item_name.length * 20;

      // } else {
      //   return 80;
      // }
    },
    getList() {
      GetOICData(this.listQuery).then(response => {
        if (response.data.state == 0) {
          this.$message.error(response.data.msg);
          return false;
        } else {
          this.tableData = [];
          this.total = response.data.data.total;
          var unfinishedcount = response.data.data.unfinishedcount;
          var finishedcount = this.total - unfinishedcount;
          this.CompletionOptions = {
            legend: [],
            series: []
          };
          this.CompletionOptions.legend.push("达标人次");
          this.CompletionOptions.series.push({
            value: finishedcount,
            name: "达标人次"
          });
          this.CompletionOptions.legend.push("未达标人次");
          this.CompletionOptions.series.push({
            value: unfinishedcount,
            name: "未达标人次"
          });

          var references = response.data.data.references;
          this.references = response.data.data.references;

          this.itemOptions = [];
          for (const index in references) {
            if (references[index].id in this.itemOptionsMap) {
              this.itemOptions.push(references[index]);
            }
          }
          // this.projectOptions = {};
          // for (const index in references) {
          //   if (!(references[index].project_id in this.projectOptions)) {
          //     this.$set(this.projectOptions, references[index].project_id, {project_id:references[index].project_id, project_name:references[index].project_name});
          //   }
          //   if (!('children' in this.projectOptions[references[index].project_id])) {
          //       this.projectOptions[references[index].project_id]['children'] = [];
          //   }
          //   this.projectOptions[references[index].project_id]['children'].push(references[index]);
          // }

          var patients = response.data.data.patients;
          for (const index in patients) {
            if (patients[index].id in this.patientMap) {
              continue;
            }
            this.$set(this.patientMap, patients[index].id, patients[index]);
          }

          var temInspections = {};
          var inspections = response.data.data.inspections;

          for (const index in inspections) {
            var key =
              inspections[index].inspect_date +
              "_" +
              inspections[index].patient_id;
            if (!(key in temInspections)) {
              temInspections[key] = {
                patient_id: inspections[index].patient_id,
                inspect_date: inspections[index].inspect_date,
                items: {}
              };
            }
            var itemKey =
              inspections[index].project_id + "_" + inspections[index].item_id;

            temInspections[key].items[itemKey] = inspections[index];
          }
          for (const key in temInspections) {
            this.tableData.push(temInspections[key]);
          }
        }
      });
    },
    changeTime(val) {
      var time =
        this.getTimestamp(val) - this.getTimestamp(this.listQuery.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.start_time = "";
      } else {
        this.getList();
      }
    },
    changeEndTime(val) {
      var time =
        this.getTimestamp(val) - this.getTimestamp(this.listQuery.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.end_time = "";
      } else {
        this.getList();
      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    selectLapseTo(lapseto) {
      this.lapsetoType = lapseto;
      this.listQuery.lapseto = lapseto;
      this.getList();
    },
    selectdialysisAges(type) {
      this.dialysisAge = type;
      this.listQuery.dialysis_age = type;
      this.getList();
    },
    changeModel() {
      this.listQuery.item_id = "";
      if (this.listQuery.project_id == "") {
        this.itemOptions = [];
      } else {
        this.itemOptions = this.projectOptions[
          this.listQuery.project_id
        ].children;
      }

      this.getList();
    },
    changeItem() {
      this.getList();
    },

    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    getTime(value, temp) {
      if (value != undefined) {
        return uParseTime(value, temp);
      }
      return "";
    },
    getProjectName(id) {
      return id in this.projectOptions
        ? this.projectOptions[id].project_name
        : "";
    },
    getPatientName(id) {
      return id in this.patientMap ? this.patientMap[id].name : "";
    },
    getPatientDialysisNo(id) {
      return id in this.patientMap ? this.patientMap[id].dialysis_no : "";
    },
    getItemVulue(project_id, item_id, row) {
      var key = project_id + "_" + item_id;
      return typeof row.items !== "undefined" && key in row.items
        ? row.items[key].inspect_value
        : "";
    },
    showTableColumn(reference) {
      if (this.listQuery.project_id == "") {
        return true;
      } else if (this.listQuery.item_id == "") {
        if (reference.project_id == this.listQuery.project_id) {
          return true;
        } else {
          return false;
        }
      } else {
        if (reference.id == this.listQuery.item_id) {
          return true;
        } else {
          return false;
        }
      }
    },
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("//")[0]),
        h("br"),
        h("span", {}, column.label.split("//")[1])
      ]);
    },
    handleTabClick(tab, event) {
      if (this.tabActiveName == "query") {
        this.$router.push({ path: "/qcd/outcomeIndicators/query" });
      }
    }
  },
  computed: {
    activeReferences: function() {
      var references = [];
      for (const index in this.references) {
        if (
          this.listQuery.item_id == "" &&
          this.references[index].id in this.itemOptionsMap
        ) {
          references.push(this.references[index]);
        } else if (this.references[index].id == this.listQuery.item_id) {
          references.push(this.references[index]);
        }
        // if (this.listQuery.project_id == '' || (this.listQuery.item_id == '' && this.references[index].project_id == this.listQuery.project_id) || this.references[index].id == this.listQuery.item_id) {
        //   references.push(this.references[index]);
        // }
      }
      return references;
    }
  },
  components: {
    PieChart,
    BreadCrumb
  }
};
</script>
<style>
#oictable ::-webkit-scrollbar {
  height: 15px;
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
  //   margin: 20px;
  font-size: 15px;
  .filter-container {
    padding-bottom: 5px;
  }
  .cqd-dataTitle {
    color: #303133;
    font-size: 14px;
    border-bottom: 2px #e4e7ed solid;
    height: 36px;
    line-height: 36px;
    margin: 0 0 25px 0;
    position: relative;
  }
  .cqd-dataTitle::before {
    position: absolute;
    left: 0;
    bottom: -2px;
    content: "";
    width: 42px;
    height: 2px;
    background: #409eff;
  }
  .search-component {
    width: 500px;
    .searchBox {
      width: 300px;
      height: 36px;
      line-height: 36px;
      padding-left: 15px;
      border: 1px #dcdfe6 solid;
      border-right: none;
      outline: none;
      float: left;
      border-radius: 6px 0 0 6px;
      font-size: 14px;
      color: #333;
      background: #fff;
      box-shadow: 3px 3px 4px rgba(135, 135, 135, 0.05);
    }
    .searchBtn {
      background-color: #409eff;
      color: #fff;
      font-size: 15px;
      text-align: center;
      height: 36px;
      line-height: 36px;
      float: left;
      outline: none;
      width: 70px;
      border: none;
      border-radius: 0 6px 6px 0;
      font-family: "Microsoft Yahei";
      cursor: pointer;
    }
  }
  .amount {
    font-weight: normal;
    padding: 10px 0 0 0;
    color: #606266;
    font-size: 14px;
    span {
      color: #ef2525;
      font-family: "Arial";
      padding: 0 2px;
    }
  }
}
</style>

<style>
.el-table td,
.el-table th.is-leaf,
.el-table--border,
.el-table--group {
  border-color: #d0d3da;
}
.el-table--border::after,
.el-table--group::after,
.el-table::before {
  background-color: #d0d3da;
}
</style>
