<template>
  <ai-detail class="wristband-add">
    <template slot="title">
      <ai-title :title="id ? '编辑人员' : '添加人员'" isShowBack isShowBottomBorder @onBackClick="cancel(false)">
      </ai-title>
    </template>
    <template slot="content">
      <el-form ref="form" :model="form" label-width="120px" label-position="right">
        <ai-card title="个人信息">
          <template #content>
            <div class="ai-form">
              <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
                <el-input size="small" placeholder="请输入姓名" v-model="form.name"></el-input>
              </el-form-item>
              <el-form-item label="身份证号码" prop="idNumber" :rules="[{ required: true, message: '请输入身份证号码', trigger: 'blur' }, {validator: validatorId, trigger: 'blur'}]">
                <el-input size="small" @blur="onBlur" placeholder="请输入身份证号码" v-model="form.idNumber"></el-input>
              </el-form-item>
              <el-form-item label="年龄" prop="age" :rules="[{ required: true, message: '请输入年龄', trigger: 'blur' }]">
                <el-input size="small" disabled placeholder="请输入年龄" v-model="form.age"></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="sex" placeholder="请选择性别" :rules="[{ required: true, message: '请选择性别', trigger: 'change' }]">
                <el-radio-group v-model="form.sex" disabled>
                  <el-radio label="1">男</el-radio>
                  <el-radio label="0">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="设备号" prop="mid" :rules="[{ required: true, message: '请输入设备号', trigger: 'blur' }]">
                <el-input size="small" placeholder="请输入设备号" v-model="form.mid"></el-input>
              </el-form-item>
              <el-form-item label="联系方式" prop="phone">
                <el-input size="small" placeholder="请输入联系方式" v-model="form.phone"></el-input>
              </el-form-item>
              <el-form-item label="所属地区" prop="areaName" style="width: 100%;" :rules="[{ required: true, message: '请选择地区', trigger: 'change' }]">
                <ai-area-get v-model="form.areaId" :root="areaRootid" :instance="instance" :name.sync="form.areaName" @change="onAreaChange"></ai-area-get>
              </el-form-item>
              <el-form-item label="备注" style="width: 100%;" prop="remark">
                <el-input size="small" placeholder="请输入备注" v-model="form.remark"></el-input>
              </el-form-item>
            </div>
          </template>
        </ai-card>
        <ai-card title="监护人信息">
          <template #right>
            <el-button type="text" @click="isShow = true">添加监护人</el-button>
          </template>
          <template #content>
            <ai-table
              :border="true"
              :tableData="form.guardians"
              :isShowPagination="false"
              :col-configs="colConfigs"
              :stripe="false"
              @getList="() => {}">
              <el-table-column
                slot="index"
                type="index"
                width="100px"
                label="序号"
                align="center">
              </el-table-column>
              <el-table-column
                slot="options"
                width="120px"
                label="操作"
                align="center">
                <template slot-scope="{ row, $index }">
                  <div class="table-options">
                    <el-button type="text" @click="edit(row, $index)">编辑</el-button>
                    <el-button type="text" @click="remove($index)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </ai-table>
          </template>
        </ai-card>
      </el-form>
      <ai-dialog
        :visible.sync="isShow"
        width="690px"
        :title="guardiansId ? '修改监护人' : '添加监护人'"
        @close="onClose"
        @onConfirm="onUserConfirm">
        <el-form
          ref="userForm"
          :model="userForm"
          label-width="130px"
          label-position="right">
          <el-form-item
            label="监护人姓名"
            prop="guardianName"
            :rules="[{ required: true, message: '请输入监护人姓名', trigger: 'blur' }]">
            <el-input
              size="small"
              :maxLength="30"
              v-model="userForm.guardianName"
              placeholder="请输入监护人姓名">
            </el-input>
          </el-form-item>
          <el-form-item
            label="监护人联系电话"
            prop="guardianPhone"
            :rules="[{ required: true, message: '请输入监护人联系电话', trigger: 'blur' }]">
            <el-input
              size="small"
              :maxLength="11"
              v-model="userForm.guardianPhone"
              placeholder="请输入监护人联系电话">
            </el-input>
          </el-form-item>
        </el-form>
      </ai-dialog>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">提交</el-button>
    </template>
  </ai-detail>
</template>

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

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

    data () {
      const validatorId = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入身份证号'))
        } else if (!this.idCardNoUtil.checkIdCardNo(value)) {
          callback(new Error('身份证号格式错误'))
        } else {
          callback()
        }
      }
      return {
        info: {},
        isShow: false,
        colConfigs: [
          { slot: 'index', label: '序号', width: 200 },
          { prop: 'guardianName', label: '监护人姓名' },
          { prop: 'guardianPhone', label: '监护人联系电话' }
        ],
        userForm: {
          guardianName: '',
          guardianPhone: ''
        },
        validatorId,
        form: {
          guardians: [],
          idNumber: '',
          name: '',
          phone: '',
          age: '',
          areaName: '',
          areaId: '',
          sex: '',
          remark: '',
          mid: ''
        },
        areaRootid: '',
        id: '',
        guardiansId: ''
      }
    },

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

    created () {
      this.areaRootid = this.user.info.areaId

      if (this.params && this.params.id) {
        this.id = this.params.id
        this.getInfo(this.params.id)
      }
    },

    methods: {
      getInfo (id) {
        this.instance.post(`/app/appintelligentguardianshipdevice/queryDetailById?id=${id}`).then(res => {
          if (res.code === 0) {
            this.form = {
              ...res.data
            }
            this.form.age = this.getIdInfo(res.data.idNumber, 3)
          }
        })
      },

      onAreaChange (e) {
        if (e) {
          this.$nextTick(() => {
            this.$refs.form.clearValidate('areaName')
          })
        } else {
          setTimeout(() => {
            this.$refs.form.validateField('areaName')
          }, 80);
        }
      },

      onBlur () {
        this.form.age = this.getIdInfo(this.form.idNumber, 3)
        this.form.sex = this.getIdInfo(this.form.idNumber, 2)
      },

      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
        }
      },

      onClose () {
        this.userForm.guardianName = ''
        this.userForm.guardianPhone = ''
        this.guardiansId = ''
      },

      edit (row, index) {
        this.guardiansId = index
        this.userForm = {
          ...row
        }
        this.isShow = true
      },

      onUserConfirm () {
        this.$refs.userForm.validate((valid) => {
          if (valid) {
            if (this.guardiansId || this.guardiansId === 0) {
              this.isShow = false
              this.$set(this.form.guardians, this.guardiansId, JSON.parse(JSON.stringify(this.userForm)))
            } else {
              this.isShow = false
              this.form.guardians.push(JSON.parse(JSON.stringify(this.userForm)))
            }
          }
        })
      },

      confirm () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.instance.post(`/app/appintelligentguardianshipdevice/addOrUpdate`, {
              ...this.form
            }).then(res => {
              if (res.code == 0) {
                this.$message.success('提交成功')
                setTimeout(() => {
                  this.cancel(true)
                }, 600)
              }
            })
          }
        })
      },

      remove (index) {
        this.form.guardians.splice(index, 1)
      },

      cancel (isRefresh) {
        this.$emit('change', {
          type: 'list',
          isRefresh: !!isRefresh
        })
      }
    }
  }
</script>

<style scoped lang="scss">
.wristband-add {
  ::v-deep .ai-table .el-table__header tr th:first-child .cell, ::v-deep .ai-table .el-table__body tr td:first-child .cell {
    padding: 0!important;
  }
}
</style>
