<template>
  <div>
    <div v-loading="loading">
      <div class="screening">
        <!--<div @click="reloads()">刷新</div>-->
        <ul>
          <li
            v-for="(item, i) in menuList"
            :class="select_index == i ? 'active' : ''"
            @click="menuTabClick(i)"
            :key="i"
          >
            {{ item.label + (item.count > 0 ? "(" + item.count + ")" : "") }}
          </li>

          <el-popover
            v-model="zone_options_visible"
            placement="bottom"
            trigger="click"
          >
            <li slot="reference">
              {{ zone_options[zone_selected].text
              }}<span class="iconfont">&#xe74a;</span>
            </li>
            <div class="popover-demo-content">
              <ul>
                <li
                  v-for="(option, index) in zone_options"
                  :key="index"
                  @click="handleZoneChange(index,option)"
                  :class="zone_selected == index ? 'tick' : ''"
                >
                  {{ option.text }}
                </li>
              </ul>
            </div>
          </el-popover>

          <el-popover
            v-model="time_options_visible"
            placement="bottom"
            trigger="click"
          >
            <li slot="reference">
              {{ time_options[time_selected].text
              }}<span class="iconfont">&#xe74a;</span>
            </li>
            <div class="popover-demo-content">
              <ul>
                <li
                  v-for="(option, index) in time_options"
                  :key="index"
                  @click="handleTimeChange(index)"
                  :class="time_selected == index ? 'tick' : ''"
                >
                  {{ option.text }}
                </li>
              </ul>
            </div>
          </el-popover>
        </ul>
      </div>
      <div class="stateBox ">
        <!-- <patient-box class="clearfix" :patients="filtedScheduals "></patient-box> -->
        <div v-for="(item, index) in filtedScheduals" :key="index">
          <h2 class="title">{{ item.zone_name }}</h2>
          <patient-box
            class="clearfix"
            :patients="item.scheduals"
          ></patient-box>
        </div>
        <div class="NoData" v-if="filtedScheduals.length == 0 && networkStates">
          <img
            style="margin-top: 50px; margin-bottom: 50px"
            src="@/assets/login/data.jpg"
            alt=""
          />
        </div>

        <div
          class="NoData"
          v-if="!networkStates"
          style="display: block;text-align: center;"
        >
          <!--<img style="margin-top: 50px; margin-bottom: 50px" src="@/assets/login/no_network.jpg" alt="">-->
          <p style="margin-top: 100px;font-size: 18px">
            网络异常，请点击重新加载
          </p>
          <van-button
            slot="button"
            size="normal"
            type="info"
            style="display:block;margin:0 auto"
            @click="reloads()"
            >重新加载
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import PatientBox from "./PatientBox";
import { getWaitingScheduals } from "@/api/dialysis";
import { parseTime } from "@/utils";
import { Popover } from "vux";
import { Toast } from "vant";

import {
  getSelectedAreaDataConfigList,
  getSelectedTimesDataConfigList,
  setSelectedAreaDataConfigList,
  setSelectedTimesDataConfigList,
  setWaitTypeSelectedConfig,
  getWaitTypeSelectedConfig
} from "@/utils/data_config";

export default {
  name: "WaitingArea",
  components: {
    PatientBox,
    Popover
  },
  inject: ["reload"],
  data() {
    return {
      loading: false,
      menuList: [
        { value: "1", label: "全部", count: 0 },
        { value: "3", label: "待开处方", count: 0 },
        { value: "2", label: "待透前称量", count: 0 }
      ],

      select_index: 0,
      zone_selected: 0,
      time_selected: 0,
      cur_zone_selected: 0,
      networkStates: true,
      scheduals: [],

      zone_options: [{ value: 0, text: "全部分区" }],
      zone_scheduals: [],

      time_options: [
        { value: 0, text: "全部班" },
        { value: 1, text: "上午" },
        { value: 2, text: "下午" },
        { value: 3, text: "晚上" }
      ],

      zone_options_visible: false,
      time_options_visible: false
    };
  },
  props: {
    search_keyword: {
      type: String
    }
  },
  computed: {
    filtedScheduals: function() {

      var search_keyword = this.search_keyword;
      if (this.search_keyword.length > 0) {
        var scheduals = [];
        for (let index = 0; index < this.scheduals.length; index++) {
          const schedual = this.scheduals[index];
          if (
            schedual.patient.name.indexOf(search_keyword) != -1 ||
            schedual.patient.dialysis_no.indexOf(search_keyword) != -1
          ) {
            scheduals.push(schedual);
          }
        }
        return this.processScheduals(scheduals);
      }
      //
      if (this.zone_selected != 0) {

        // var zone_name = this.zone_options[this.zone_selected].text
        // for (let index = 0; index < this.zone_scheduals.length; index++) {
        //   const zone_scheduals = this.zone_scheduals[index]
        //   if (zone_scheduals.zone_name == zone_name) {
        //     return [zone_scheduals]
        //   }
        // }
        var zone_name = this.zone_options[this.zone_selected].text
        var schedules = [];
        var filtedSchedules = [];
        for (let o_i = 0; o_i < this.zone_scheduals.length; o_i++) {
          const scheduleInfo = this.zone_scheduals[o_i];
          var originSchedules = scheduleInfo.scheduals;
          
          for (let s_i = 0; s_i < originSchedules.length; s_i++) {
            const schedule = originSchedules[s_i];
            if(this.zone_selected == 0){
              if (this.time_selected == 0 || schedule.schedule_type == this.time_selected) {
                filtedSchedules.push(schedule);
              }
            }else{
              if ((zone_name.length > 0 && zone_name == schedule.device_number.zone.name)) {
                if (this.time_selected == 0 || schedule.schedule_type == this.time_selected) {
                  filtedSchedules.push(schedule);
                }
              }
            }
          }
          // if (filtedSchedules.length > 0) {
          //   schedules.push({
          //     zone_name: scheduleInfo.zone_name,
          //     scheduals: filtedSchedules
          //   });
          // }
        }
        console.log(filtedSchedules)
        return this.processScheduals(filtedSchedules);
      }

      if (this.time_selected != 0) {
        var zone_name = this.zone_options[this.zone_selected].text
        var schedules = [];
        var filtedSchedules = [];
        for (let o_i = 0; o_i < this.zone_scheduals.length; o_i++) {
          const scheduleInfo = this.zone_scheduals[o_i];
          var originSchedules = scheduleInfo.scheduals;
          
          for (let s_i = 0; s_i < originSchedules.length; s_i++) {
            const schedule = originSchedules[s_i];
            if(this.zone_selected == 0){
              if (this.time_selected == 0 || schedule.schedule_type == this.time_selected) {
                filtedSchedules.push(schedule);
              }

            }else{
              if ((zone_name.length > 0 && zone_name == schedule.device_number.zone.name)) {
                if (this.time_selected == 0 || schedule.schedule_type == this.time_selected) {
                  filtedSchedules.push(schedule);
                }
              }
            }
          }
          // if (filtedSchedules.length > 0) {
          //   schedules.push({
          //     zone_name: scheduleInfo.zone_name,
          //     scheduals: filtedSchedules
          //   });
          // }
        }
        console.log(filtedSchedules)
        return this.processScheduals(filtedSchedules);
      }

      var zone_selected = this.zone_selected;
      var timetype_selected = this.time_selected;
      var assessment_before_dislysis_count = 0;
      var prescription_count = 0;
      if (zone_selected != 0 || timetype_selected != 0) {
        var zone_name = zone_selected == 0 ? "" : this.zone_options[zone_selected].text;
        var schedules = [];
        var filtedSchedules = [];
        for (let o_i = 0; o_i < this.zone_scheduals.length; o_i++) {
          const scheduleInfo = this.zone_scheduals[o_i];
          var originSchedules = scheduleInfo.scheduals;
          
          for (let s_i = 0; s_i < originSchedules.length; s_i++) {
            const schedule = originSchedules[s_i];
            if ( zone_name.length == 0 || (zone_name.length > 0 && zone_name == schedule.device_number.zone.name)) {
              if ( timetype_selected == 0 ||  schedule.schedule_type == timetype_selected ) {
                filtedSchedules.push(schedule);
              }
            }
          }
          // if (filtedSchedules.length > 0) {
          //   schedules.push({
          //     zone_name: scheduleInfo.zone_name,
          //     scheduals: filtedSchedules
          //   });
          // }
        }

        console.log(filtedSchedules)
        return this.processScheduals(filtedSchedules);

        if (this.select_index == 2) {
          var scheduals = [];
          for (let index = 0; index < this.scheduals.length; index++) {
            const schedual = this.scheduals[index];
            if (schedual.assessment_before_dislysis == null || schedual.assessment_before_dislysis.weight_before == 0) {
              if(this.cur_zone_selected > 0 && schedual.device_number.zone.id != this.cur_zone_selected) {
                continue
              }
              if(timetype_selected > 0 && schedual.schedule_type != timetype_selected) {
                continue
              }
              scheduals.push(schedual);
            }
          }
          return this.processScheduals(scheduals);
          // return scheduals;
        } else if (this.select_index == 1) {
          var scheduals = [];
          for (let index = 0; index < this.scheduals.length; index++) {
            const schedual = this.scheduals[index];
            if (schedual.prescription == null || schedual.prescription.creater == 0) {
              if(this.cur_zone_selected > 0 && schedual.device_number.zone.id != this.cur_zone_selected) {
                continue
              }
              if(timetype_selected > 0 && schedual.schedule_type != timetype_selected) {
                continue
              }
              scheduals.push(schedual);
            }
          }
          // return scheduals;
          return this.processScheduals(scheduals);
        } else {
          // return this.zone_scheduals;
          var scheduals = [];
          for (let index = 0; index < this.scheduals.length; index++) {
            const schedual = this.scheduals[index];
            if (schedual.dialysis_order == null) {
              if(this.cur_zone_selected > 0 && schedual.device_number.zone.id != this.cur_zone_selected) {
                continue
              }
              if(timetype_selected > 0 && schedual.schedule_type != timetype_selected) {
                continue
              }
              scheduals.push(schedual);
            }
          }
          // return scheduals;
          return this.processScheduals(scheduals);
        }
      }

      if (this.select_index == 2) {
        var scheduals = [];
        for (let index = 0; index < this.scheduals.length; index++) {
          const schedual = this.scheduals[index];
          if (schedual.assessment_before_dislysis == null || schedual.assessment_before_dislysis.weight_before == 0) {
            scheduals.push(schedual);
          }
        }
        return this.processScheduals(scheduals);
        // return scheduals;
      } else if (this.select_index == 1) {
        var scheduals = [];
        for (let index = 0; index < this.scheduals.length; index++) {
          const schedual = this.scheduals[index];
          if (schedual.prescription == null || schedual.prescription.creater == 0) {
            scheduals.push(schedual);
          }
        }
        // return scheduals;
        return this.processScheduals(scheduals);
      } else {
        // return this.zone_scheduals;
        var scheduals = [];
        for (let index = 0; index < this.scheduals.length; index++) {
          const schedual = this.scheduals[index];
          if (schedual.dialysis_order == null) {
            scheduals.push(schedual);
          }
        }
        // return scheduals;
        return this.processScheduals(scheduals);
      }
    }
  },
  created() {
    var area = getSelectedAreaDataConfigList();
    var time = getSelectedTimesDataConfigList();
    var type = getWaitTypeSelectedConfig();

    if (area != null) {
      this.zone_options_visible = false;
      this.zone_selected = parseInt(area);
      this.select_index = -1;
    }

    if (time != null) {
      this.time_selected = parseInt(time);
      this.select_index = -1;
      this.time_options_visible = false;
    }
    if (type != null) {
      this.select_index = parseInt(type);
    }
   
    var storedata = this.$store.getters.waitscheduals
    var scheduals = storedata.waitscheduals
    if (Object.keys(storedata).length > 0) {
      var totalCount = scheduals.length;
      var prescription_count = 0;
      var assessment_before_dislysis_count = 0;
      for (let index = 0; index < scheduals.length; index++) {
        const schedual = scheduals[index];
        if (schedual.assessment_before_dislysis == null) {
          assessment_before_dislysis_count += 1;
        }
        if (schedual.prescription == null) {
          prescription_count += 1;
        }
      }
      this.menuList[2].count = assessment_before_dislysis_count;
      this.menuList[1].count = prescription_count;
      this.scheduals = scheduals;

      this.zone_options = this.makeZones(scheduals);
      this.zone_scheduals = this.processScheduals(scheduals);
    } else {
      this.requestScheduals();
    }
  },
  mounted() {
    this.timer = window.setInterval(() => {
      setTimeout(this.requestScheduals(), 0);
    }, 30000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
    this.$once('hook:beforeDestroy', () => {
      clearInterval(this.timer);
    })
  },
  methods: {
    processScheduals: function(scheduals) {
      var zoneMap = {};
      var schedualMap = {};
      var assessment_before_dislysis_count = 0;
      var prescription_count = 0;
      for (let index = 0; index < scheduals.length; index++) {
        const schedual = scheduals[index];
        if (schedualMap[schedual.device_number.zone.id] == null) {
          schedualMap[schedual.device_number.zone.id] = [];
        }
        if (this.select_index == 1) {
            if(schedual.prescription == null || schedual.prescription.creater == 0){
            schedualMap[schedual.device_number.zone.id].push(schedual);
            prescription_count++
          }
        } else if (this.select_index == 2){
            if(schedual.assessment_before_dislysis == null || schedual.assessment_before_dislysis.weight_before == 0){
            schedualMap[schedual.device_number.zone.id].push(schedual);
            assessment_before_dislysis_count++
          }
        } else {
          if(schedual.dialysis_order == null){
            schedualMap[schedual.device_number.zone.id].push(schedual);
          }
        }
        if (zoneMap[schedual.device_number.zone.id] == null) {
          zoneMap[schedual.device_number.zone.id] = schedual.device_number.zone;
        }
      }

      if (this.select_index == 1) {
        this.menuList[1].count = prescription_count;
      }
      if (this.select_index == 2) {
        this.menuList[2].count = assessment_before_dislysis_count;
      }


      var zones = [];
      // zones.push({ value: 0, text: "全部分区" })
      for (var zoneId in zoneMap) {
        zones.push({ id: zoneMap[zoneId].id, name: zoneMap[zoneId].name });
      }

      zones = zones.sort(function(a, b) {
        return a.id > b.id;
      });
      // this.zones = zones

      var zone_scheduals = [];
      for (let index = 0; index < zones.length; index++) {
        const zone = zones[index];
        var scheduals = schedualMap[zone.id];
        zone_scheduals.push({
          zone_id: zone.id,
          zone_name: zone.name,

          scheduals: scheduals
        });
      }
      // this.zone_scheduals = zone_scheduals;
      return zone_scheduals;
    },
    reloads: function() {
      this.reload();
    },
    handleAllChange: function(tabIndex) {
      this.select_index = tabIndex;
      this.zone_selected = 0;
      this.time_selected = 0;
    },
    menuTabClick: function(tabIndex) {
      this.select_index = tabIndex;
      this.zone_selected = 0;
      this.time_selected = 0;
      setSelectedAreaDataConfigList(this.zone_selected);
      setSelectedTimesDataConfigList(this.time_selected);
      setWaitTypeSelectedConfig(tabIndex);
    },
    handleZoneChange: function(index,zone) {
      this.zone_options_visible = false;
      this.zone_selected = index;
      this.cur_zone_selected = zone.value
      // this.select_index = -1;
      setSelectedAreaDataConfigList(index.toString());
    },
    handleTimeChange: function(index) {
      this.time_selected = index;
      // this.select_index = -1;
      this.time_options_visible = false;
      setSelectedTimesDataConfigList(index.toString());
    },

    requestScheduals() {
      // this.loading = true;
      var date = parseTime(Date.parse(new Date()), "{y}-{m}-{d}");
      getWaitingScheduals({ date: date })
        .then(rs => {
          var resp = rs.data;
          if (resp.state == 1) {
            this.loading = false;

            var scheduals = resp.data.scheduals;
            this.$store.dispatch("SetWaitScheduals",{waitscheduals:scheduals})
            var totalCount = scheduals.length;
            var prescription_count = 0;
            var assessment_before_dislysis_count = 0;
            for (let index = 0; index < scheduals.length; index++) {
              const schedual = scheduals[index];
              if (schedual.assessment_before_dislysis == null) {
                assessment_before_dislysis_count += 1;
              }
              if (schedual.prescription == null) {
                prescription_count += 1;
              }
            }
            this.menuList[2].count = assessment_before_dislysis_count;
            this.menuList[1].count = prescription_count;
            this.scheduals = scheduals;

            this.zone_options = this.makeZones(scheduals);
            this.zone_scheduals = this.processScheduals(scheduals);
          } else {
            this.loading = false;

            this.$toast({
              message: resp.msg
            });
          }
        })
        .catch(error => {
          this.loading = false;

          //超时之后在这里捕抓错误信息.
          if (error.response) {
            this.networkStates = false;
          } else if (error.request) {
            this.networkStates = false;
            // if(error.request.readyState == 4 && error.request.status == 0){
            //   //我在这里重新请求
            //   this.networkStates = false
            // }
          } else {
            this.networkStates = false;
          }
        });
    },
    makeZones: function(scheduals) {
      var zoneMap = {};
      for (let index = 0; index < scheduals.length; index++) {
        const schedual = scheduals[index];
        if (zoneMap[schedual.device_number.zone.id] == null) {
          zoneMap[schedual.device_number.zone.id] = schedual.device_number.zone;
        }
      }

      var zones = [];
      zones.push({ value: 0, text: "全部分区" });

      for (var zoneId in zoneMap) {
        zones.push({ value: zoneMap[zoneId].id, text: zoneMap[zoneId].name });
      }

      // zones = zones.sort(function (a, b) {
      //   return a.value > b.value
      // })
      return zones;
    }
  }
};
</script>

<style style="stylesheet/scss" lang="scss" scoped>
.screening {
  border-bottom: 1px #e5e5e5 solid;
  position: fixed;
  top: 63px;
  right: 0;
  z-index: 66;
  left: 1.58rem;
  background: #fff;
  @media only screen and (max-width: 812px) {
    top: 50px !important;
  }
  ul {
    @include display-flex;
    @include align-items-center;
    @include text-align;
    @include justify-content-between;
    width: 60%;
    margin: 0 auto;
    font-size: 0.32rem;
    color: $title-color;
    li {
      padding: 0.3rem 0;
      .iconfont {
        font-size: 0.32rem;
        margin-left: 0.1rem;
      }
    }
    .active {
      position: relative;
      &::before {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 2px;
        background: $main-color;
        // border-bottom: 0.04rem $main-color solid;
        content: "";
      }
    }
  }
}
.stateBox {
  // padding: 0.5rem 0 0 0.6rem;
  .title {
    font-size: 0.34rem;
    color: #34495e;
    font-weight: 600;
    height: 1rem;
    line-height: 1rem;
    display: inline-block;
  }
}
.shadow {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 998;
  background-color: #000;
  opacity: 0.6;
  display: none;
}
</style>
