<template>
  <div class="fastProvince">
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <div style="text-align: center">
        <p>您选择的区域酷医云暂未对接，请联系酷医云客服，我们将免费为您实现对接</p>
        <img style="width: 150px;height: 150px" src="../../../assets/home/kuyi_wechat.jpg"/>
        <p>服务热线</p>
        <p style="font-size: 16px">18682078150</p>
      </div>


      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>

    <div class="cell clearfix">
      <el-form :model="form" ref="ruleForm" label-width="40px" class="demo-ruleForm" style="text-align: center">
        <el-form-item label="地区">
          <el-select v-model="form.province" clearable filterable placeholder="请选择" @change="changeProvince" style="width:150px;">
            <el-option
              v-for="item in provinces"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="cell clearfix" style="margin-bottom:0px;">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label>
          <el-input v-model.trim="listQuery.search" placeholder="姓名/透析号" style="width:120px"></el-input>
          <el-button type="primary" style="padding: 10px 6px;" @click="onSearch" icon="el-icon-search">搜索</el-button>
        </el-form-item>
      </el-form>
      <div class="time" style="margin-left:40px;">
        <ul class="newUl">
          <li
            :class="item.state == wayType ? 'active' : ''"
            @click="chooseWay(item.state)"
            v-for="item in way"
            :key="item.value"
          >{{ item.label }}</li>
        </ul>
      </div>
    </div>
    
    <div style="flex:1">
      <el-container class="newContainer">
        <div style="width:270px">
            <div class="tableTitle">患者列表</div>
            <div class="cell clearfix" style="margin-bottom:10px;">
            <el-date-picker v-model="selected_date" prefix-icon="el-icon-date" @change="handleScheduleDateChange" :editable="false" :clearable="false" style="width: 130px;margin-right:10px;" type="date" placeholder="选择日期时间" align="right" ></el-date-picker>
            <el-input size="small" style="width:80px;" v-model.trim="search_input" class="filter-item"/>
            <el-button size="small" class="filter-item" type="primary" @click="searchAction">搜索</el-button>
          </div>
          <div class="cell clearfix" style="margin-bottom:10px;">
            <el-select v-model="patientStateVal" placeholder="全部患者状态" style="width:130px;margin-right:10px;" @change="handleStateChange">
              <el-option
                v-for="item in patient_state"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select v-model="treatStateVal" placeholder="全部治疗状态" style="width:130px;margin-right:10px;" @change="handleTreatChange">
              <el-option
                v-for="item in treat_state"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="cell clearfix" style="margin-bottom:10px;">
            <el-select v-model="scheduleStateVal" placeholder="班次" style="width:130px;margin-right:10px;" @change="handletimeType">
              <el-option
                v-for="item in schedule_options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select v-model="zoneVal" placeholder="分区" style="width:130px;margin-right:10px;" @change="handleZoneChange">
              <el-option
                v-for="item in zone_options"
                :key="item.id"
                :label="item.text"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div style="padding-right:20px;">
            <el-table
              ref="tab"
              @row-click="changePatient"
              highlight-current-row
              :data="tableData"
              height="500"
              border
              style="width: 100%">
              <el-table-column
                prop="date"
                label="患者"
                >
                <template slot-scope="scope">
                  {{ scope.row.patient.name }}
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="状态"
                >
                <template slot-scope="scope">
                  <div style="display:flex;align-items:center;justify-content:space-around;">
                    <span class="tip1" v-if="scope.row.prescription == null || scope.row.prescription.creater == 0">
                      待开处方
                    </span>
                    <span class="tip2" v-if="scope.row.assessment_before_dislysis == null || scope.row.assessment_before_dislysis.weight_before == ''">
                      待称重
                    </span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <basic-info v-if="wayType == 0"></basic-info>
        <treat-info v-if="wayType == 1"></treat-info>
        <dialysis-params v-if="wayType == 2"></dialysis-params>
        <dialysis-summary v-if="wayType == 3"></dialysis-summary>
        <rescue-record v-if="wayType == 4"></rescue-record>
      </el-container>
    </div>
    

  </div>
</template>

<script>
  import { GetDistrictsByUpid } from '@/api/district'
  import { getIsDocking } from '@/api/config'
  import basicInfo from "../fast/basicInfo"
  import treatInfo from "../fast/treatInfo"
  import dialysisParams from "../fast/dialysisParams"
  import dialysisSummary from "../fast/dialysisSummary"
  import rescueRecord from "../fast/rescueRecord"

  import {
  getDialysisRecordInitData,
  getDialysisSchedules
} from "@/api/dialysis_record";
import { parseTime } from "@/utils";

  export default {
    name: 'FastProvince',
    components:{
      basicInfo,
      treatInfo,
      dialysisParams,
      dialysisSummary,
      rescueRecord
    },
    data() {
      return {
        signAndWeighBoxPatients: 'sign-and-weigh-box-patients',
        start_time: '',
        dialogVisible: false,
        end_time: '',
        provinces: [],
        citys:[],
        form: {
          province: '',
          city: ''
        },
        listQuery: {
          start_time: "",
          end_time: "",
          page: 1,
          limit: 10
        },
        way: [
          { value: 0, label: "基本信息", state: 0 },
          { value: 1, label: "治疗信息", state: 1 },
          { value: 2, label: "透析参数", state: 2 },
          { value: 3, label: "治疗小结", state: 3 },
          { value: 4, label: "抢救记录", state: 4 },
        ],
        wayType: 0,

        //
        tableData: [],
        selected_date: new Date(),
        // search_input 和 search_keyword，使输入关键字时不会经常刷新 filtedSchedules
        search_keyword: '', // 确定用于搜索的关键字
        search_input: '', // 输入中的关键字
        patient_state:[
            {value: 0,label: '全部'},
            {value: 1,label: '已签到'},
            {value: 2,label: '未签到'},
            {value: 3,label: '已上机'},
            {value: 4,label: '已下机'},
        ],
        patientStateVal: 0,
        treat_state:[
            {value: 0,label: '全部'},
            {value: 1,label: '待开处方'},
            {value: 2,label: '待开小结'},
        ],
        treatStateVal: 0,
        schedule_options:[
            {value: 0,label: '全部'},
            {value: 1,label: '上午'},
            {value: 2,label: '下午'},
            {value: 3,label: '晚上'},
        ],
        scheduleStateVal: 0,
        zone_options:[
            { id: 0, text: '全部' }
        ],
        zoneVal:0,

      }
    }, 
    computed:{
        filtedSchedules: function() {
            var search_keyword = this.search_keyword
            if (search_keyword.length > 0) {
                var schedules = []
                for (let o_i = 0; o_i < this.zone_schedules.length; o_i++) {
                const scheduleInfo = this.zone_schedules[o_i]
                var originSchedules = scheduleInfo.schedules
                if (originSchedules.length == 0) {
                    continue
                }
                var filtedSchedules = []
                for (let s_i = 0; s_i < originSchedules.length; s_i++) {
                    const schedule = originSchedules[s_i]
                    if (schedule.patient.name.indexOf(search_keyword) != -1) {
                    filtedSchedules.push(schedule)
                    // break
                    }
                }
                if (filtedSchedules.length > 0) {
                    schedules.push({ zone_id: scheduleInfo.zone_id, zone_name: scheduleInfo.zone_name, schedules: filtedSchedules })
                }
                }
                return schedules
            }
        }
    },
    created() {
      this.getDistricts()
      var province = sessionStorage.getItem('province')
      if (province == null) {
        this.form.province = ''
      } else {
        this.form.province = parseInt(province)
      }

      this.getInitData();

    }, methods: {
      getDistricts: function() {
        GetDistrictsByUpid({ id: 0 }).then(response => {
          var res = response.data
          if (res.state === 1) {
            this.provinces = res.data.citys
          }
        }).catch(e => {

        })

      }, changeProvince(id) {
        getIsDocking({ config_type: 2, province: id, city: 0 }).then(response => {
          var res = response.data
          if (res.state == 1) {
            if (res.data.is_docking == 2) {
              this.$message.error('该地区尚未对接,请联系客服')
              this.dialogVisible = true
              this.form.province = ''

            } else {
              this.form.province = id
              this.dialogVisible = false
              sessionStorage.setItem('province', id)
            }
          } else {
            this.$message.error(res.msg)
          }
        }).catch(e => {
        })
      },
      chooseWay(way) {
        this.wayType = way;
      },
      //日期
        handleScheduleDateChange: function() {
            this.treatStateVal = 0
            this.patientStateVal = 0
            this.zoneVal = 0
            this.scheduleStateVal = 0
            this.search_keyword = this.search_input = ''
            // this.$store.dispatch("SaveDialysisAreaSelectIndexs", {
            //   zone: this.zone_selected,
            //   schedule_type: this.schedule_type_selected,
            //   schedule_date: this.selected_date,
            // })
            this.requestDialysisSchedules()
        },
        //初始化数据
        getInitData: function() {
            getDialysisRecordInitData().then(rs => {
                var resp = rs.data
                if (resp.state == 1) {
                var zones = resp.data.zones
                var schedules = resp.data.schedules
                var zone_options = [{ id: 0, text: '全部' }]
                for (let z_i = 0; z_i < zones.length; z_i++) {
                    const zone = zones[z_i]
                    zone_options.push({ id: zone.id, text: zone.name })
                }
                this.zone_options = zone_options
                this.zone_schedules = this.processedDialysisSchedules(schedules, this.zone_options)
                this.arr = this.processedDialysisSchedules(schedules, this.zone_options)
                this.getData()
                } else {
                this.$message.error(resp.msg)
                }
            })
        },
        // 班次
        handletimeType: function(index) {
            this.scheduleStateVal = index
            // this.$store.dispatch('SetScheduleTypeSelected', { schedule_type_selected: index })
            this.search_keyword = this.search_input = ''
            this.getData()
        },
        //分区
        handleZoneChange: function(index) {
            this.zoneVal = index
            // this.$store.dispatch('SetZoneSelected', { zone_selected: index })
            this.search_keyword = this.search_input = ''
            this.getData()
        },
        //患者状态
        handleStateChange: function(index) {
            this.patientStateVal = index
            // this.$store.dispatch('SetPatientStateSelected', { patient_state_selected: index })
            this.search_keyword = this.search_input = ''
            this.getData()
        },
        handleTreatChange: function(index) {
            this.treatStateVal = index
            // this.$store.dispatch('SetTreatStateSelected', { treat_state_selected: index })
            this.search_keyword = this.search_input = ''
            this.getData()
        },
        processedDialysisSchedules: function(schedules, zone_options) {
            var zoneMap = {}
            var scheduleMap = {}
            for (let z_i = 0; z_i < zone_options.length; z_i++) {
                const zone = zone_options[z_i]
                if (zone.id == 0) {
                continue
                }
                scheduleMap[zone.id] = []
            }
            for (let index = 0; index < schedules.length; index++) {
                const schedule = schedules[index]
                scheduleMap[schedule.device_number.zone.id].push(schedule)
            }
            var zone_schedules = []
            for (let index = 0; index < zone_options.length; index++) {
                const zone = zone_options[index]
                if (zone.id == 0) {
                continue
                }
                var schedules = scheduleMap[zone.id]
                zone_schedules.push({ zone_id: zone.id, zone_name: zone.text, schedules: schedules })
            }
            return zone_schedules
        },
        searchAction: function() {
            this.search_keyword = this.search_input
            this.scheduleStateVal = 0
            this.zoneVal = 0
            this.treatStateVal = 0
            this.patientStateVal = 0
            if(this.search_input != ''){
                let arr = []
                this.filtedSchedules.map(item => {
                arr.push(...item.schedules)
                })
                if(this.activeName == "first"){
                this.tableData = arr
                }else if(this.activeName == "second"){
                this.tableData1 = arr
                }
                
            }else{
                this.getData()
            }
        },
        requestDialysisSchedules: function() {
            var ymd = parseTime(this.selected_date, '{y}-{m}-{d}')
            getDialysisSchedules(ymd).then(rs => {
                var resp = rs.data
                if (resp.state == 1) {
                var schedules = resp.data.schedules
                this.zone_schedules = this.processedDialysisSchedules(schedules, this.zone_options)
                let newArr = []
                this.zone_schedules.map(item => {
                    newArr.push(...item.schedules)
                })
                this.tableData = newArr
                } else {
                this.$message.error(resp.msg)
                }
            })
        },
        changePatient(schedual){
            //   console.log(schedual)
            //   this.patient_id = schedual.patient_id;
            //   this.date = schedual.schedule_date;
            //   // this.getScheduleDetail();
            //   // this.getLongAdvice();
            
            //   var patient_id = schedual.patient_id;
            //   var date = schedual.schedule_date;
            //   this.$router.push({
            //     path: "/dialysis/details",
            //     query: {
            //       patient_id: patient_id,
            //       date: date,
            //       patient_name: schedual.patient.name
            //     }
            //   });
        },
        getData(){
            let patientArr = []
            patientArr = JSON.parse(JSON.stringify(this.zone_schedules))
            console.log('patientArr',patientArr)
            let arr1 = []
            if(this.patientStateVal == 0){
                arr1 = patientArr
                console.log(arr1)
            }else if(this.patientStateVal == 1){
                let arr = []
                arr = patientArr
                for (let i = 0; i <arr.length; i++) {
                    for (let j = 0; j < arr[i].schedules.length; j++) {
                        if (arr[i].schedules.length > 0 && (arr[i].schedules[j].assessment_before_dislysis == null || arr[i].schedules[j].assessment_before_dislysis.weight_before == '' || arr[i].schedules[j].assessment_before_dislysis.diastolic_blood_pressure == '' || arr[i].schedules[j].assessment_before_dislysis.systolic_blood_pressure == '')) {
                            // 删除元素后改变i的值
                            arr[i].schedules.splice(j--, 1);
                        }
                    }
                }
                console.log("执行1",arr)
                arr1 = arr
            }else if(this.patientStateVal == 2){
                let arr = []
                arr = patientArr
                for (let i = 0; i < arr.length; i++) {
                    for (let j = 0; j < arr[i].schedules.length; j++) {
                        if (arr[i].schedules.length > 0 && (arr[i].schedules[j].assessment_before_dislysis != null && (arr[i].schedules[j].assessment_before_dislysis.weight_before != 0 || arr[i].schedules[j].assessment_before_dislysis.diastolic_blood_pressure != 0 || arr[i].schedules[j].assessment_before_dislysis.systolic_blood_pressure != 0))) {
                            // 删除元素后改变i的值
                            console.log('几次')
                            arr[i].schedules.splice(j--, 1);
                        }
                    }
                }
                console.log("执行2",arr)
                arr1 = arr
            }else if(this.patientStateVal == 3){
                let arr = []
                arr = patientArr
                for (let i = 0; i <arr.length; i++) {
                    for (let j = 0; j < arr[i].schedules.length; j++) {
                        if (arr[i].schedules.length > 0 && (arr[i].schedules[j].dialysis_order == null || (arr[i].schedules[j].dialysis_order != null && arr[i].schedules[j].dialysis_order.stage != 1))) {
                            // 删除元素后改变i的值
                            arr[i].schedules.splice(j--, 1);
                        }
                    }
                }
                console.log("执行1",arr)
                arr1 = arr
            }else if(this.patientStateVal == 4){
                let arr = []
                arr = patientArr
                for (let i = 0; i < arr.length; i++) {
                    for (let j = 0; j < arr[i].schedules.length; j++) {
                        if (arr[i].schedules.length > 0 && (arr[i].schedules[j].dialysis_order == null || (arr[i].schedules[j].dialysis_order != null && arr[i].schedules[j].dialysis_order.stage != 2))) {
                            // 删除元素后改变i的值
                            arr[i].schedules.splice(j--, 1);
                        }
                    }
                }
                console.log("执行2",arr)
                arr1 = arr
            }

            let arr2 = []
            if(this.treatStateVal == 0){
                arr2 = JSON.parse(JSON.stringify(arr1))
            }else if(this.treatStateVal == 1){
                let arr = []
                arr = JSON.parse(JSON.stringify(arr1))
                for (let i = 0; i < arr.length; i++) {
                    for (let j = 0; j < arr[i].schedules.length; j++) {
                        if (arr[i].schedules.length > 0 && (arr[i].schedules[j].prescription != null || arr[i].schedules[j].prescription != null ? arr[i].schedules[j].prescription.creater != 0 : false)) {
                            // 删除元素后改变i的值
                            arr[i].schedules.splice(j--, 1);
                        }
                    }
                }
                arr2 = arr
            }else if(this.treatStateVal == 2){
                let arr = []
                arr = JSON.parse(JSON.stringify(arr1))
                for (let i = 0; i < arr.length; i++) {
                    for (let j = 0; j < arr[i].schedules.length; j++) {
                        if (arr[i].schedules.length > 0 && arr[i].schedules[j].treatment_summary != null && arr[i].schedules[j].treatment_summary.dialysis_summary != '') {
                            // 删除元素后改变i的值
                            arr[i].schedules.splice(j--, 1);
                        }
                    }
                }
                arr2 = arr
            }
            

            let arr3 = []
            if(this.scheduleStateVal == 0){
                arr3 = JSON.parse(JSON.stringify(arr2))
            }else{
                let arr = []
                arr = JSON.parse(JSON.stringify(arr2))
                for (let i = 0; i < arr.length; i++) {
                    for (let j = 0; j < arr[i].schedules.length; j++) {
                        if (this.scheduleStateVal != arr[i].schedules[j].schedule_type) {
                            // 删除元素后改变i的值
                            arr[i].schedules.splice(j--, 1);
                        }
                    }
                }
                arr3 = arr
                console.log("上午",arr)
            }
            

            let arr4 = []
            if(this.zoneVal == 0){
                arr4 = JSON.parse(JSON.stringify(arr3))
            }else{
                let arr = []
                arr = JSON.parse(JSON.stringify(arr3))
                for (let i = 0; i < arr.length; i++) {
                    if (this.zoneVal != arr[i].zone_id) {
                    // 删除元素后改变i的值
                    arr.splice(i--, 1);
                    }
                }
                arr4 = arr
            }
            let newArr = []
            arr4.map(item => {
            newArr.push(...item.schedules)
            })
            this.tableData = newArr
            console.log('table',this.tableData)
        },

    }
  }
</script>

<style lang="scss" scoped>
.fastProvince{
  .newUl{
    li{
      padding:10px 20px !important;
    }
  }
}
.tableTitle {
  font-size: 16px;
  color: #000;
  font-weight: bold;
  line-height: 40px;
}
</style>
<style lang="scss">
.fastProvince{
  .el-form-item{
    margin-bottom: 0;
  }
  // .el-button--medium{
  //   padding: 10px 6px;
  // }
}
.newContainer{
    .el-date-editor{
        .el-input__inner{
            padding-right:0px;
        }
    }
}
</style>
