<template>
  <div class="app-container">
    <div style="margin: 15px;">
      <el-row class="table-title">
        <el-col :span="6"><div class="title-header" style="margin-left: 10px;">人员信息</div></el-col>
        <el-col :span="12" :offset="6" class="edit_btns">
          <el-button class="edit_btn" size="small" @click="checkin">新增来访人员</el-button>
        </el-col>
      </el-row>

      <el-table :data="dataForm.visitorBaseDTOList" class="table" row-class-name="small-row-class" border>
        <!--序号列-->
        <el-table-column align="center" type="index" label="#" width="55"/>
        <!--内容列-->
        <el-table-column v-for="column in columns" :key="column.value" :label="column.text" :width="column.width" :align="column.align" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="column.value === 'idCard'">{{ encrypIdCardNo(scope.row[column.value]) }}</span>
            <span v-else :class="column.class">{{ scope.row[column.value] }}</span>
          </template>
        </el-table-column>
        <!--操作列-->
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="scope">
            <el-button type="text" @click="detail(scope.row)">详情</el-button>
            <el-button type="text" @click="del(scope.row.idCard)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div style="margin: 15px;">
      <el-row class="table-title">
        <el-col :span="6"><div class="title-header" style="margin-left: 10px;">来访信息</div></el-col>
      </el-row>

      <el-form v-loading="formLoading" ref="dataForm" :label-position="labelPosition" :rules="rules" :model="dataForm" class="main-form" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="访客所在单位" prop="deptname">
              <el-input v-model.trim="dataForm.deptname" clearable show-word-limit maxlength="30" type="text" placeholder="必填，访客所在单位"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="访客所在城市" prop="city">
              <el-input v-model.trim="dataForm.city" clearable show-word-limit maxlength="30" type="text" placeholder="必填，访客所在城市"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="接访部门" prop="deptid">
              <el-select v-show="!isDetailMode" v-model="dataForm.deptid" placeholder="所属组织" filterable clearable @change="fetchStaffList">
                <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
              <!--<dept-select ref="deptid" v-model="dataForm.deptid" :dept-show="true" :need-top="true" placeholder="所属组织" @change="fetchStaffList"/>-->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="接访人员" prop="personId">
              <el-select v-model="dataForm.personId" placeholder="请选择接访人" filterable clearable>
                <el-option v-for="item in staffList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来访事由" prop="matter">
              <el-input v-model.trim="dataForm.matter" clearable show-word-limit maxlength="30" type="text" placeholder="必填"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="授权时间">
              <el-radio-group v-model="authTimeType">
                <el-radio-button v-for="item in authTimeList" :key="item.value" :label="item.value">{{ item.name }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-date-picker
              :readonly="!customTimeRange"
              v-model="timeRange"
              :picker-options="datePickerOptions"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期" />
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div style="height: 120px;">
      <el-row type="flex" justify="center">
        <el-col :span="15" style="text-align:center">
          <el-button type="primary" style="width: 150px;" @click="saveData"> 保存 </el-button>
        </el-col>
      </el-row>
    </div>

    <visitor-check-in ref="checkin" @checked="visitorCheckedIn" />
  </div>
</template>

<script>
import DeptSelect from '@/components/DeptSelect'
import { daysInMonth, oneDayTime, getDate, formatToString } from '@/utils/calendarUtil'
import { getStaffByDept } from '@/api/staff'
import { addVisitorPerson } from '@/api/visitor'
import VisitorCheckIn from '@/views/visitor/visitorCheckIn'
import { getDeptTreeList } from '@/api/dept'
const now = new Date()

export default {
  name: 'VisitorAddPerson',
  components: { VisitorCheckIn, DeptSelect },
  data() {
    return {
      dataForm: {
        visitTime: '',
        deptname: '', // 访客所在单位
        city: '', // 访客所在城市
        deptid: '', // 接访部门
        personId: '', // 接访人员
        matter: '', // 来访原因
        beginTime: '',
        endTime: '',
        visitorBaseDTOList: []
      }, // 表单
      rules: {
        deptname: [{ required: true, message: '单位不能为空', trigger: ['blur', 'change'] }],
        city: [{ required: true, message: '城市不能为空', trigger: ['blur', 'change'] }],
        deptid: [{ required: true, message: '接访部门不能为空', trigger: ['blur', 'change'] }],
        personId: [{ required: true, message: '接访人员不能为空', trigger: ['blur', 'change'] }],
        matter: [{ required: true, message: '来访原因不能为空', trigger: ['blur', 'change'] }]
      },
      staffList: [], // 接访人员列表
      labelPosition: 'right',
      authTimeList: [{ name: '当日', value: '1' }, { name: '本周', value: '2' }, { name: '本月', value: '3' }, { name: '自定义', value: '4' }],
      authTimeType: '1',
      timeRange: [],
      customTimeRange: false,
      deptShowTop: true, // 权属单位下拉是否显示顶级
      deptShow: true,
      formLoading: false,
      deptList: [],
      dialogFormVisible: false,
      datePickerOptions: {
        disabledDate(time) {
          const yesterday = new Date(now.getTime() - oneDayTime)
          const oneYearLater = new Date(now.getTime() + (oneDayTime * 360))
          return time.getTime() < yesterday || time.getTime() > oneYearLater
        }
      },
      columns: [
        {
          text: '姓名',
          value: 'name',
          align: 'center',
          width: 140
        },
        {
          text: '性别',
          value: 'sexStr',
          align: 'center'
        },
        {
          text: '身份证号码',
          value: 'idCard',
          align: 'center'
        },
        {
          text: '联系方式',
          value: 'phone',
          align: 'center'
        },
        {
          text: '体温',
          value: 'temperature',
          align: 'center'
        }
      ] // 显示列
    }
  },
  watch: {
    'authTimeType': function(val) {
      const weekDay = now.getDay() // 周几
      const monthDay = now.getDate() // 日期
      const month = now.getMonth() // 月份

      this.customTimeRange = false

      if (val === '1') {
        this.timeRange = [getDate(0, 'DATE'), getDate(1, 'DATE')]
      } else if (val === '2') {
        this.timeRange = [getDate(0, 'DATE'), getDate(7 - weekDay + 1, 'DATE')]
      } else if (val === '3') {
        this.timeRange = [getDate(0, 'DATE'), getDate(daysInMonth[month + 1] - monthDay + 1, 'DATE')]
      } else if (val === '4') {
        this.timeRange = []
        this.customTimeRange = true
      }
    }
  },
  mounted() {
    getDeptTreeList().then(response => {
      const list = response.data.list
      for (let i = 0; i < list.length; i++) {
        if (list[i].pid !== '-1' && list[i].pid !== '0') {
          this.deptList.push(list[i])
        }
      }
    })
    this.resetForm()
    this.initDateRange()
  },
  methods: {
    // 重置表单
    resetForm() {
      this.dataForm = {
        visitTime: '',
        deptname: '', // 访客所在单位
        city: '', // 访客所在城市
        deptid: '', // 接访部门
        personId: '', // 接访人员
        matter: '', // 来访原因
        beginTime: '',
        endTime: '',
        visitorBaseDTOList: []
      }

      // 清除验证
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    initDateRange() {
      this.authTimeType = '1' // 当日
      this.dataForm.beginTime = getDate(0, 'DATE')
      this.dataForm.endTime = getDate(1, 'DATE')
      this.timeRange = [getDate(0, 'DATE'), getDate(1, 'DATE')]
    },
    // 身份证号加密显示
    encrypIdCardNo(idCard) {
      if (idCard.length > 6) {
        return idCard.substr(0, 6) + '********' + idCard.substr(14)
      } else if (idCard) {
        return idCard
      } else {
        return ''
      }
    },
    // 打开访客登记页面
    checkin() {
      this.dialogFormVisible = true
      this.$refs.checkin.initDialog('create', this.dialogFormVisible)
    },
    // 一位访客登记完毕
    visitorCheckedIn(visitor) {
      this.dataForm.visitorBaseDTOList.push(visitor)
    },
    detail(row) {
      this.dialogFormVisible = true
      this.$refs.checkin.initDialog('detail', this.dialogFormVisible, row)
    },
    del(idCard) {
      const that = this
      this.dataForm.visitorBaseDTOList.forEach(function(item, index) {
        if (item.idCard === idCard) {
          that.dataForm.visitorBaseDTOList.splice(index, 1)
        }
      })
    },
    // 保存数据
    saveData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (this.dataForm.visitorBaseDTOList.length === 0) {
          this.$message.error('来访人员列表不能为空')
        } else if (valid) {
          this.dataForm.visitTime = formatToString(now, 'SECOND')
          addVisitorPerson(this.dataForm).then(response => {
            if (response.code === 200) {
              // 注册成功后清除表单
              this.resetForm()

              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                })
              }).catch(() => {
                const code = this.$store.getters.currentSystem.code
                this.$router.replace({ path: '/' + code + '/staff/list' })
              })
            } else {
              this.$message.error(response.message)
              this.btnLoading = false
            }
          }).catch(() => {
            this.$message.error('保存失败，服务器异常')
          })
        }
      })
    },
    fetchStaffList() {
      getStaffByDept({ deptId: this.dataForm.deptid }).then(response => {
        this.dataForm.personId = ''
        this.staffList = response.data
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" >
  .hide .el-upload--picture-card {
    display: none;
  }
  .main-form{
    margin: 0px 30px;
    margin-top: 20px;
    padding: 10px;
    overflow: auto;
  }
  .el-dialog{
    width:700px
  }
  .el-select{
    width: 100%;
  }
  .line{
    width: 50px;
    margin-left: 5px;
  }
  .hide .el-upload-–picture-card{
    display: none;
  }
  .imgBox{
    width: 100%;
    text-align: center;
  }
  .avatar-uploader .el-upload {
    margin-left: 12px;
    margin-top: 10px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 238px;
    line-height: 238px;
    text-align: center;
  }
  .avatar {
    margin: 10px;
    display: block;
  }
  .id-card-btn{
    width:126px;
    margin-left: 12px;
    margin-top: 20px;
  }

  $tableTitleHeight:46px;
  .app-container{
    margin-bottom:20px
  }
  .table{
    margin-bottom: 20px;
  }
  .pagination-container{
    margin-bottom: 50px;
  }
  .table-title{
    background-color:rgba(243, 243, 243, 1);
    height: $tableTitleHeight;
    .title-header{
      line-height:$tableTitleHeight;
      color: #606266;
      font-size: 15px;
      i{
        margin-left: 5px;
        margin-right: 5px;
      }
    }
  }
  .edit_btns{
    .edit_btn{
      float:right;
      margin:7px 3px;//为了需要居中显示margin-top和bottom要用$tableTitleHeight减去按钮原高度除以2
    }
  }
</style>
