<template>
  <ai-list class="early-warning">
    <template slot="title">
      <ai-title title="健康预警" isShowArea isShowBottomBorder v-model="search.areaId" :instance="instance" @change="search.current = 1, getList()">
        <template #rightBtn>
          <el-button type="primary" @click="getRules(), isShow = true">预警规则</el-button>
        </template>
      </ai-title>
    </template>
    <template slot="content">
      <ai-search-bar class="search-bar">
        <template #left>
          <el-date-picker
            v-model="search.createTimeRange"
            type="daterange"
            size="small"
            @change="search.current = 1, getList()"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <ai-select
            v-model="search.item"
            @change="search.current = 1, getList()"
            placeholder="预警类型"
            :selectList="dict.getDict('intelligentGuardianshipItem3')">
          </ai-select>
        </template>
        <template slot="right">
          <el-input
            v-model="search.name"
            size="small"
            @keyup.enter.native="search.current = 1, getList()"
            placeholder="请输入成员姓名、设备号"
            clearable
            @clear="search.current = 1, search.name = '', getList()"
            suffix-icon="iconfont iconSearch">
          </el-input>
        </template>
      </ai-search-bar>
      <ai-table
        :tableData="tableData"
        :col-configs="colConfigs"
        :total="total"
        v-loading="loading"
        style="margin-top: 6px;"
        :current.sync="search.current"
        :size.sync="search.size"
        @getList="getList">
        <el-table-column slot="options" width="160px" fixed="right" label="操作" align="center">
          <template slot-scope="{ row }">
            <div class="table-options">
              <el-button type="text" @click="$router.push({name: '监护地图', query: {id: row.deviceId, lat: row.lat, lng: row.lng}})">地图查看</el-button>
              <el-button type="text" @click="toMonitor(row.deviceId)">监测数据</el-button>
            </div>
          </template>
        </el-table-column>
      </ai-table>
      <ai-dialog
        :visible.sync="isShow"
        width="690px"
        title="预警规则"
        @close="currIndex = 0"
        @onConfirm="onConfirm">
        <el-radio-group v-model="currIndex" size="small">
          <el-radio-button :label="0">体温</el-radio-button>
          <el-radio-button :label="1">心率</el-radio-button>
          <el-radio-button :label="2">血压</el-radio-button>
          <el-radio-button :label="3">血氧</el-radio-button>
          <el-radio-button :label="4">电量</el-radio-button>
        </el-radio-group>
        <el-form label-width="70px">
          <div class="rules-form" v-for="(item, index) in rules" :key="index" v-show="currIndex === index">
            <el-form-item label="规则推送">
              <el-switch
                v-model="item.pushType" active-value="1" inactive-value="0">
              </el-switch>
            </el-form-item>
            <el-form-item label="预警规则">
              <el-input size="small" placeholder="请输入" v-model="item.gtValue" v-if="index !== 4 && index !== 3">
                <template slot="prepend"><el-button>大于</el-button></template>
              </el-input>
              <el-input size="small" placeholder="请输入" v-model="item.ltValue">
                <template slot="prepend"><el-button type="info">小于</el-button></template>
              </el-input>
            </el-form-item>
          </div>
        </el-form>
      </ai-dialog>
    </template>
  </ai-list>
</template>

<script>
  import { mapState } from 'vuex'
  export default {
    name: 'List',

    props: {
      instance: Function,
      dict: Object
    },

    data() {
      return {
        search: {
          current: 1,
          size: 10,
          name: '',
          areaId: '',
          createTimeRange: [],
          item: ''
        },
        currIndex: 0,
        isShow: false,
        loading: false,
        rules: [],
        total: 0,
        colConfigs: [
          { prop: 'name', label: '姓名' },
          { prop: 'mid', label: '设备号' },
          {
            prop: 'departmentNames',
            label: '年龄',
            align: 'center',
            render: (h, { row }) => {
              return h('span', {}, this.getIdInfo(row.idNumber, 3))
            }
          },
          { prop: 'sex', align: 'center', label: '性别', formart: v => v === '1' ? '男' : '女' },
          { prop: 'phone', align: 'center', label: '联系方式' },
          { prop: 'areaName', align: 'center', label: '所属地区' },
          { prop: 'type', align: 'center', label: '预警类型', formart: v => this.dict.getLabel('intelligentGuardianshipItem3', v) },
          { prop: 'itemValue', align: 'center', label: '预警值' },
          { prop: 'gpsDesc', align: 'center', width: 150, label: '预警地点' },
          { prop: 'createTime', align: 'center', label: '预警时间' }
        ],
        tableData: []
      }
    },

    computed: {
      ...mapState(['user'])
    },

    mounted() {
      this.search.areaId = this.user.info.areaId
      this.dict.load(['intelligentGuardianshipItem3']).then(() => {
        this.getList()
      })
    },

    methods: {
      getList () {
        this.instance.post(`/app/appintelligentguardianshipalarm/list`, null, {
          params: {
            ...this.search,
            type: 0,
            createTimeRange: (this.search.createTimeRange && this.search.createTimeRange.length) ? this.search.createTimeRange.join(',') : ','
          }
        }).then(res => {
          if (res.code == 0) {
            this.tableData = res.data.records.map(v => {
              return {
                ...v,
                type: this.dict.getLabel('ntelligentGuardianshipItem3', v.item)
              }
            })
            this.total = res.data.total

            this.$nextTick(() => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        }).catch(() => {
          this.loading = false
        })
      },

      getRules () {
        this.instance.post(`/app/appintelligentguardianshipalarm/queryAlarmConfig`).then(res => {
          if (res.code == 0) {
            this.rules = res.data.sort((a, b) => a.item - b.item)

            if (!res.data.length) {
              this.rules = [0, 1, 2, 3, 4].map(index => {
                return {
                  gtValue: '',
                  item: index,
                  ltValue: '',
                  pushType: '1'
                }
              })
            }
          }
        })
      },

      onConfirm () {
        this.instance.post(`/app/appintelligentguardianshipalarm/addOrUpdateConfig`, this.rules).then(res => {
          if (res.code == 0) {
            this.$message.success('提交成功')
            this.isShow = false
          }
        })
      },

      getIdInfo (UUserCard, num) {
        if (num == 1) {
          var birth = UUserCard.substring(6, 10) + '-' + UUserCard.substring(10, 12) + '-' + UUserCard.substring(12, 14)
          return birth
        }
        if (num == 2) {
          if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
            return '1'
          } else {
            return '0'
          }
        }

        if (num == 3) {
          var myDate = new Date()
          var month = myDate.getMonth() + 1
          var day = myDate.getDate()
          var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
          if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
            age ++
          }

          return age
        }
      },

      remove (id) {
        this.$confirm('确定删除该数据？').then(() => {
          this.instance.post(`/app/appintelligentguardianshipdevice/delete?ids=${id}`).then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功！')
              this.getList()
            }
          })
        })
      },

      toMonitor (id) {
        this.$emit('change', {
          type: 'Monitor',
          params: {
            id: id || ''
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.early-warning {
  .rules-form {
    margin-top: 20px;
  }
}
</style>
