<template>
  <div>
    <van-nav-bar title="紧急联系人" left-text="返回" left-arrow @click-left="$router.back()" />

    <van-form @submit="onSubmit">
      
      <!-- 设备 -->
      <van-field
        readonly
        clickable
        name="device_id"
        :value="deviceName"
        label="设备名称"
        placeholder="点击选择"
        @click="showDevicePicker = true"
      />
      <van-popup v-model="showDevicePicker" position="top">
        <van-picker
          show-toolbar
          value-key="device_name"
          :columns="deviceColumns"
          @confirm="onConfirmDevice"
          @cancel="showDevicePicker = false"
        />
      </van-popup>

      <!-- 姓名 -->
      <van-field
        v-model="name"
        name="name"
        label="联系人姓名"
        placeholder="请输入联系人姓名"
        clearable
        :rules="[{ required: true, message: '请输入紧急联系人姓名' }]"
      />
      <!-- 电话 -->
      <van-field
        v-model="phone"
        type="number"
        maxlength="11"
        show-word-limit
        name="phone"
        label="联系人号码"
        clearable
        placeholder="请输入联系人手机号码"
        :rules="[{ required: true, pattern: new RegExp(/[0-9]{11}/), message: '请输入11位的紧急联系人手机号码' }]"
      />
      <!-- 社会关系 -->
      <van-field
        readonly
        clickable
        name="relationship"
        :value="relationshipText"
        label="社会关系"
        placeholder="点击选择"
        @click="showRelationshipPicker = true"
      />
      <van-popup v-model="showRelationshipPicker" position="bottom">
        <van-picker
          show-toolbar
          value-key="text"
          :columns="relationshipColumns"
          @confirm="onConfirmRelationship"
          @cancel="showRelationshipPicker = false"
        />
      </van-popup>

      <div style="margin: 16px">
        <van-button class="form-btn" round block type="info" size="small" native-type="submit">提交</van-button>
      </div>
      <div style="margin: 16px">
        <van-button class="form-btn" round block type="danger" size="small" native-type="button" v-if="urgentId" @click="onDelete">删除</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import Vue from "vue";
import "vant/lib/index.css";
import { Form, Field, Picker, Popup, Notify, NavBar, Dialog, Button } from "vant";

Vue.use(Form);
Vue.use(Button);
Vue.use(Field);
Vue.use(Picker);
Vue.use(Popup);
Vue.use(Notify);
Vue.use(NavBar);
Vue.use(Dialog);

export default {
  data() {
    return {
      action: '添加',
      name: '',
      phone: '',
      relationship: '',
      relationshipText: '',
      relationshipColumns: [],
      showRelationshipPicker: false,
      device_id: null,
      urgentId: null,
      userid: null,
      // 设备
      showDevicePicker: false,
      deviceName: '',
      deviceColumns: [],
    };
  },
  created() {

    this.userid = localStorage.getItem("userid");
    this.openid = localStorage.getItem("openid");
    this.device_id = this.$route.query.device_id;
    this.urgentId = this.$route.query.id;
    
    // 社会关系
    this.getRelationshipData();
    this.getDeviceList();

    this.$nextTick(() => {
      // 修改操作
      if (this.urgentId) {
          this.action = '修改';
          this.getUrgentData(this.urgentId);
      }
    })
  },
  watch: {
    relationshipColumns(val) {
      if (!this.relationship) {
        return;
      }
      val.forEach(item => {
        if (item.id == this.relationship) {
          this.relationshipText = item.text
        }
      })
    },
  },
  methods: {
    goBack() {
      this.$router.back()
    },
    // 获取联系人数据
    getUrgentData(id) {
      this.$http
          .get('getUrgentById&userid=' + this.userid + '&openid=' + this.openid + '&id=' + id)
          .then(resp => {
            if (resp.status === 200 && resp.data && resp.data.success) {
              let urgentInfo = resp.data.data || {}
              if (urgentInfo.id) {
                this.name = urgentInfo.name
                this.phone = urgentInfo.phone
                this.relationship = urgentInfo.relationship
              }
            }
          })
    },
    // 获取关系数据
    getRelationshipData() {
      this.$http
          .get('getRelationshipList')
          .then(resp => {
            if (resp.status === 200 && resp.data && resp.data.success) {
              this.relationshipColumns = resp.data.data || []
            }
          })
    },
    onConfirmRelationship(obj) {
      this.relationship = obj.id;
      this.relationshipText = obj.text;
      this.showRelationshipPicker = false;
    },
    onSubmit(vals) {
      let data = {
        name: this.name,
        phone: this.phone,
        relationship: this.relationship,
        device_id: this.device_id,
        userid: this.userid,
      };
      if (this.urgentId) {
        data.id = this.urgentId;
      }
      this.$http
        .post("/addEditUrgent", JSON.stringify(data))
        .then((res) => {
          let resp = res.data;
          if (!resp.success) {
            this.$dialog.toast({
              mes: resp.message,
            });
            return;
          }

          Notify({ type: "success", message: resp.message });
          this.$router.back();
        })
        .catch((res) => {
          console.log(res);
        });
    },
    onDelete() {
      if (!this.userid || !this.urgentId || !this.device_id) {
        return;
      }
      Dialog.confirm({
        title: '删除联系人',
        message: '确定要删除该紧急联系人吗？'
      })
      .then(resp => {
        this.$http.get('deleteUrgent&userid='+ this.userid + '&device_id=' + this.device_id +'&id=' + this.urgentId)
                  .then(resp => {
                    if (resp.status === 200 && resp.data && resp.data.success) {
                      Notify({ type: "success", message: resp.data.message });
                      this.$router.back();
                    } else {
                      Notify({ message: resp.data.message });
                    }
                  })
      })
      .catch(()=>{})

    },
    /**
     * 选择设备
     */
    onConfirmDevice(obj) {
      this.device_id = obj.id;
      this.deviceName = obj.device_name;
      this.showDevicePicker = false;
    },
    /**
     * 获取设备列表
     */
    getDeviceList() {

      this.$http
        .get("/getMyDevices&userid=" + this.userid + '&openid=' + this.openid)
        .then(res => {
          this.deviceColumns = res.data.data || [];
          // 设备id存在,默认选中
          if (this.device_id) {
            this.deviceColumns.forEach(item => {
              if (item.id == this.device_id) {
                this.deviceName = item.device_name
              }
            })
          }

        })
        .catch(res => {
        });
    },
    
  },
};
</script>
<style scoped="less" >

</style>