<template>
  <div class="app-container">
    <van-nav-bar
      title="围栏信息"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />

    <van-form @submit="onSubmit">
      <van-field
        input-align="right"
        v-model="formData.name"
        name="name"
        label="围栏名称"
        placeholder="请输入围栏名称"
        maxlength="10"
        clearable
        required
      />

      <van-field v-show="fenceType!='sos'" name="inFenceAlarm" label="进围栏告警" input-align="right">
        <template #input>
          <van-switch
            v-model="formData.inFenceAlarm"
            size="20"
            active-color="#4cd864"
            inactive-color="#dcdee0"
          />
        </template>
      </van-field>

      <!-- 进围栏告警时间 -->
      <div v-show="fenceType!='sos'" v-for="(key,index) in inTime" :key="'in'+index">
        <van-field
            input-align="right"
            readonly
            clickable
            type="time"
            :label="'进时间段'+(index+1)"
          >
          <template #input>
            <van-field :value="inTime[index][0]" @click="updateTime('inTime',index,0)" readonly placeholder="开始时间" input-align="right" />
              —
            <van-field :value="inTime[index][1]" @click="updateTime('inTime',index,1)" readonly placeholder="结束时间" />

            <van-icon :name="index ? 'minus' : 'plus'" size="20" @click="inTime[index?'pop':'push']([])" />
          </template>
        </van-field>
      </div>

      <van-field v-show="fenceType!='sos'" name="outFenceAlarm" label="出围栏告警" input-align="right">
        <template #input>
          <van-switch
            v-model="formData.outFenceAlarm"
            size="20"
            active-color="#4cd864"
            inactive-color="#dcdee0"
          />
        </template>
      </van-field>

      <!-- 出围栏告警时间 -->
      <div v-show="fenceType!='sos'" v-for="(key,index) in outTime" :key="'out'+index">
        <van-field
            input-align="right"
            readonly
            clickable
            :label="'出时间段'+(index+1)"
          >
          <template #input>
            <van-field :value="outTime[index][0]" @click="updateTime('outTime',index,0)" readonly placeholder="开始时间" input-align="right" />
              —
            <van-field :value="outTime[index][1]" @click="updateTime('outTime',index,1)" readonly placeholder="结束时间" />

            <van-icon :name="index ? 'minus' : 'plus'" size="20" @click="outTime[index?'pop':'push']([])" />
          </template>
        </van-field>
      </div>
      <!-- 推送间隔 -->
      <van-field
        input-align="right"
        readonly
        clickable
        :value="intervalColumns[currentIntervalIndex]"
        label="推送间隔"
        placeholder="点击选择告警推送间隔"
        @click="showIntervalPicker = true"
        name="sentInterval"
      />

      <!-- 推送用户 -->
      <van-field
        input-align="right"
        readonly
        clickable
        label="推送用户"
        name="pushUsers"
      >
        <template #input>
          <div style="max-height:100px;overflow:auto;">
            <van-checkbox-group v-model="checkedPushUsers" style="margin-right:20px;">
              <van-checkbox class="checkbox-flex-end" checked-color="#4cd864" shape="square" label-position="left"
                v-for="user in pushUsers"
                :key="user.id"
                :name="user.id"
              >
                {{user.phone}}（{{user.realname}}）
              </van-checkbox>
            </van-checkbox-group>
          </div>
          
        </template>
      </van-field>

      <div style="margin: 26px">
        <van-button round block type="info" size="small" native-type="submit"
          >确定</van-button
        >
      </div>
    </van-form>

    <!-- 时间选择 -->
    <van-popup v-model="showTimePicker" position="bottom">
      <van-datetime-picker
        v-model="checkedTime"
        type="time"
        @confirm="onConfirm"
        @cancel="showTimePicker = false"
      />
    </van-popup>
    <!-- 推送间隔选择 -->
    <van-popup v-model="showIntervalPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="intervalColumns"
        @confirm="onConfirmInterval"
        @cancel="showIntervalPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import Vue from "vue";
import {
  Form,
  Field,
  NavBar,
  Icon,
  Button,
  Switch,
  DatetimePicker,
  Popup,
  Picker,
  Checkbox,
  CheckboxGroup,
} from "vant";

Vue.use(Form);
Vue.use(Field);
Vue.use(NavBar);
Vue.use(Icon);
Vue.use(Button);
Vue.use(Switch);
Vue.use(DatetimePicker);
Vue.use(Popup);
Vue.use(Picker);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);

export default {
  data() {
    return {
      id: '',
      fenceType: '',
      userid: '',
      openid: '',

      showTimePicker: false,
      showIntervalPicker: false,
      intervalColumns: [],
      intervalList: [],
      currentIntervalIndex: '', 
      // 当前 timepicker 变量, inTime[index][key]
      currentVal: '',
      currentIndex: '',
      currentKey: '',
      checkedTime: '',
      inTime: [],
      outTime: [],
      // 推送用户
      pushUsers: [],
      checkedPushUsers: [],

      formData: {
        name: '',
        inFenceAlarm: false,
        outFenceAlarm: false,
      },
    };
  },
  created() {
    this.userid = localStorage.getItem('yysUserid');
    this.openid = localStorage.getItem('openid');
    this.id = this.$route.query.id || '';
    this.fenceType = this.$route.query.type;
    // 获取围栏信息
    this.getFenceAlarmIntervals();
    this.getRightUsers();
  },
  mounted() {
    this.getFenceInfo();
  },
  methods: {
    // 获取告警时间间隔
    getFenceAlarmIntervals() {
      this.$http.get('getFenceAlarmIntervals&openid='+this.openid+'&userid='+this.userid)
          .then(resp => {
            if (resp.status !== 200 || !resp.data.success) {
              this.$notify(resp.data.message || '获取告警时间间隔失败');
              return;
            }
            if (!resp.data.data || !resp.data.data.length) {
              this.$notify(resp.data.message || '未设置告警时间间隔');
              return;
            }
            resp.data.data.forEach((item,index) => {
              this.intervalColumns.push(item.text);
              this.intervalList.push(item);
              if (this.formData.sent_interval && this.formData.sent_interval == item.value) {
                this.currentIntervalIndex = index;
              }
            })
            
          })
          .catch(err => {
            console.log(err);
          })
    },
    /**
     * 获取权限范围内用户
     */
    getRightUsers() {
      this.$http.get('getRightUsers&openid='+this.openid+'&userid='+this.userid)
          .then(resp => {
            if (resp.status !== 200 || !resp.data.success) {
              this.$notify(resp.data.message || '获取推送用户失败');
              return;
            }
            this.pushUsers = resp.data.data;
          })
    },
    // 获取围栏信息
    getFenceInfo() {
      if (!this.id) {
        return;
      }
      this.$http.get('getFenceInfo&openid='+this.openid+'&userid='+this.userid+'&id='+this.id)
          .then(resp => {
            if (resp.status !== 200 || !resp.data.success) {
              this.$notify(resp.data.message || '出错了，请稍后再试');
              return;
            }
            let data = resp.data.data;
            
            this.formData.name = data.name;
            this.formData.inFenceAlarm = (data.is_check_in === '0') ? false : true;
            this.formData.outFenceAlarm = (data.is_check_out === '0') ? false : true;
            // 告警时间段
            if (data.in_fence_time_area && data.in_fence_time_area.length) {
              this.inTime = data.in_fence_time_area;
            } else {
              this.inTime = [['00:00','23:59']];
            }
            if (data.out_fence_time_area && data.out_fence_time_area.length) {
              this.outTime = data.out_fence_time_area;
            } else {
              this.outTime = [['00:00','23:59']];
            }
            // 推送间隔
            this.intervalList.length && this.intervalList.forEach((item,index) => {
              if (item.value == data.sent_interval) {
                this.currentIntervalIndex = index;
              }
            })
            // 推送用户（组件需要 String 值）
            data.push_users.length && data.push_users.forEach(item => {
              this.checkedPushUsers.push(item+'');
            })
            
          }).catch(err => {
            this.$notify(resp.data.message || '出错了，请稍后再试');
            console.log(err);
          })
    },
    /**
     * 修改时间，搭配 onConfirm 使用
     */
    updateTime(val, index, key) {
      this.currentVal = val;
      this.currentIndex = index;
      this.currentKey = key;
      // 组件时间
      this.checkedTime = this[val][index][key];

      this.showTimePicker = true;
    },
    /**
     * 确定修改时间，搭配 updateTime 使用
     */
    onConfirm(val) {
      this[this.currentVal][this.currentIndex][this.currentKey] = val;
      this.showTimePicker = false;
    },
    /**
     * 确定推送时间
     */
    onConfirmInterval(val, index) {
      this.currentIntervalIndex = index;
      this.showIntervalPicker = false;
    },
    /**
     * 提交
     */
    onSubmit(val) {

      let postData = {
        name: val.name,
        sent_interval: this.intervalList[this.currentIntervalIndex].value,
        push_users: val.pushUsers || [],
      }
      if (this.fenceType == 'inout') {
        postData.is_check_in = val.inFenceAlarm ? 1 : 0;
        postData.is_check_out = val.outFenceAlarm ? 1 : 0;
        postData.in_fence_time_area = this.inTime;
        postData.out_fence_time_area = this.outTime;
      }

      this.$http.post('addEditFence&userid='+this.userid+'&openid='+this.openid+'&id='+this.id, JSON.stringify(postData))
          .then(resp => {

              if(!resp.data.success){
                this.$notify(resp.data.message);
                return;
              }
              this.$notify({type:'success', message: resp.data.message});

          })
          .catch(err => {
            this.$notify('出错了，请稍后重试');
            console.log(err);
          })
    },
  },
};
</script>

<style lang="scss" scoped>
.checkbox-flex-end {
  justify-content: flex-end;
  padding: 2px 0;
}
</style>