// 添加/修改
<template>
  <el-dialog
    :title="isEdit ? '编辑受访人' : '添加受访人'"
    width="500px"
    :visible.sync="visible"
    :destroy-on-close="false"
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :rules="rules"
      :model="form"
      label-position="left"
      label-width="90px"
    >
      <el-form-item prop="id" style="margin-bottom: 0">&nbsp;</el-form-item>
      <el-form-item
        v-if="checkRole([1])"
        label="绑定账号"
        prop="adminId"
        required
      >
        <el-select
          v-model="form.adminId"
          class="filter-item"
          placeholder="请选择账号"
          clearable
          filterable
        >
          <el-option
            v-for="item in userList"
            :key="item.adminId"
            :label="item.username"
            :value="item.adminId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="form.name"
          :disabled="nameReadOnly"
          placeholder="请输入姓名"
          maxlength="10"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="form.phone"
          :disabled="phoneReadOnly"
          placeholder="请输入手机号"
          maxlength="11"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idNumber">
        <el-input
          v-model="form.idNumber"
          :disabled="idNumberReadOnly"
          placeholder="请输入身份证号"
          maxlength="18"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="单位名称" prop="company">
        <el-input
          v-model="form.company"
          placeholder="请输入单位名称"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="部门" prop="unitName">
        <el-input
          v-model="form.unitName"
          placeholder="请输入部门"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="楼层" prop="floor" required>
        <el-input
          v-model="form.floor"
          placeholder="请输入楼层，多个楼层请用英文逗号分隔"
        />
      </el-form-item>
      <el-form-item label="房间号" prop="room">
        <el-input
          v-model="form.room"
          placeholder="请输入房间号"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="显示标题" prop="showTitle" required>
        <el-input
          v-model="form.showTitle"
          placeholder="请输入显示标题"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        v-if="!checkRole([99])"
        label="区域"
        prop="selectAreaList"
        required
      >
        <el-select
          v-model="form.selectAreaList"
          class="filter-item"
          placeholder="请选择区域"
          clearable
          multiple
          filterable
          @change="areaChange"
        >
          <el-option
            v-for="item in areaList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button type="primary" :loading="submitLoading" @click="submit">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { checkRole } from '@/utils/checkRole'
import { addOrUpdate } from '@/api/visitee'

export default {
  props: {
    userList: {
      type: Array,
      default: () => []
    },
    areaList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      nameReadOnly: false,
      phoneReadOnly: false,
      idNumberReadOnly: false,
      form: {
        id: null,
        adminId: null,
        name: null,
        phone: null,
        idNumber: null,
        company: null,
        unitName: null,
        floor: null,
        room: null,
        showTitle: null,
        selectAreaList: []
      },
      visible: false,
      submitLoading: false,
      isEdit: false
    }
  },
  computed: {
    rules() {
      return {
        adminId: [
          {
            required: true,
            type: 'number',
            message: '不能为空!',
            trigger: ['change', 'blur']
          }
        ],
        phone: [
          {
            required: false,
            len: 11,
            trigger: ['change', 'blur'],
            validator: (rule, value, callback) => {
              if (!value || this.phoneReadOnly) {
                return callback()
              }
              const reg = /^1[3-9]\d{9}$/
              if (!reg.test(value)) {
                return callback('手机号格式错误!')
              }
              return callback()
            }
          }
        ],
        // idNumber: [
        //   {
        //     required: false,
        //     max: 18,
        //     trigger: ["change", "blur"],
        //     validator: (rule, value, callback) => {
        //       if (!value || this.idNumberReadOnly) {
        //         return callback();
        //       }
        //       if (value.length === 15) {
        //         const idreg =
        //           /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
        //         if (!idreg.test(value)) {
        //           return callback("身份证号格式错误!");
        //         }
        //       } else if (value.length === 18) {
        //         const idreg =
        //           /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
        //         if (!idreg.test(value)) {
        //           return callback("身份证号格式错误!");
        //         }
        //       } else {
        //         return callback("身份证号位数错误!");
        //       }
        //       return callback();
        //     },
        //   },
        // ],
        floor: [
          {
            required: true,
            whitespace: true,
            message: '不能为空!',
            trigger: ['change', 'blur']
          },
          {
            pattern: /^-?[-,1-9a-zA-Z]{1,}\d*$/,
            message: '楼层只能为整数或英文字母组合,多个楼层请用英文逗号隔开!',
            trigger: ['change', 'blur']
          }
        ],
        showTitle: [
          {
            required: true,
            whitespace: true,
            message: '不能为空!',
            trigger: ['change', 'blur']
          }
        ],
        selectAreaList: [
          {
            required: true,
            type: 'array',
            message: '不能为空!',
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  methods: {
    checkRole,
    areaChange(e) {
      this.form = { ...this.form }
      this.$forceUpdate()
    },
    open(obj) {
      this.visible = true
      this.submitLoading = false
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        if (obj && Object.keys(obj).length > 0) {
          const areas = obj.zoneIds
          delete obj.zoneIds
          delete obj.zoneNames
          this.form = obj
          if (areas) {
            this.form.selectAreaList = JSON.parse(areas)
          } else {
            this.form.selectAreaList = [0]
          }
          // console.info('form-->', this.form)
          this.isEdit = true
          if (obj.name) {
            this.nameReadOnly = true
          } else {
            this.nameReadOnly = false
          }
          if (obj.phone) {
            this.phoneReadOnly = true
          } else {
            this.phoneReadOnly = false
          }
          if (obj.idNumber) {
            this.idNumberReadOnly = true
          } else {
            this.idNumberReadOnly = false
          }
        } else {
          this.isEdit = false
          this.nameReadOnly = false
          this.phoneReadOnly = false
          this.idNumberReadOnly = false
          this.form.selectAreaList = []
        }
      })
    },
    submit(e) {
      e.preventDefault()
      this.$refs.form.validate(async(valid) => {
        if (!valid) {
          return false
        }
        if (this.submitLoading) {
          return
        }
        // if (!this.form.adminId) {
        //   this.form.adminId = this.$store.getters.adminId
        // }
        delete this.form.createTime
        this.submitLoading = true
        let zoneIds = null
        let zoneNames = null
        if (this.form.selectAreaList && this.form.selectAreaList.length > 0) {
          if (this.form.selectAreaList.indexOf(0) > -1) {
            // 全部
            zoneIds = null
            zoneNames = null
          } else {
            const selectAreaList = this.areaList.filter((item) => {
              return (
                this.form.selectAreaList.findIndex(
                  (items) => items && items === item.id
                ) > -1
              )
            })
            zoneIds = selectAreaList.map((item) => item.id)
            zoneNames = selectAreaList.map((item) => item.name)
          }
        }
        try {
          const params = {
            ...this.form,
            selectAreaList: null,
            zoneIds: zoneIds ? `[${zoneIds.join(',')}]` : null,
            zoneNames: zoneNames ? zoneNames.join(',') : null
          }
          if (this.isEdit) {
            if (this.nameReadOnly) {
              params.name = null
            }
            if (this.phoneReadOnly) {
              params.phone = null
            }
            if (this.idNumberReadOnly) {
              params.idNumber = null
            }
          }
          await addOrUpdate(params)
          this.visible = false
          this.form.selectAreaList = []
          this.$emit('success', this.isEdit)
        } catch (e) {
          this.$refs.form.resetFields()
          console.info('add', e)
        } finally {
          this.submitLoading = false
        }
      })
    }
  }
}
</script>

<style scoped>
::v-deep .el-select {
  width: 100%;
}
::v-deep .el-dialog__body {
  padding-bottom: 0;
}
</style>
