<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <label class="el-form-item-label">申请人</label>
        <el-input v-model="query.requestUser" clearable placeholder="申请人" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">到访时间</label>
        <DateRangePicker
          v-model="buildDate"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width: 300px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-refresh-left" @click="changeDate">搜索</el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetDate">重置</el-button>
        <!-- <rrOperation :crud="crud" /> -->
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <el-button
        v-if="crud.optShow.add"
        v-permission="permission.add"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="crud.toAdd"
      >
        访客申请
      </el-button>
      <el-button
        v-if="crud.optShow.download"
        :loading="crud.downloadLoading"
        :disabled="!crud.data.length"
        class="filter-item"
        size="mini"
        type="warning"
        icon="el-icon-download"
        @click="crud.doExport"
      >导出</el-button>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="closeAll" :visible="crud.status.cu > 0" :title="crud.status.title" width="660px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
          <el-form-item label="被访人员姓名" prop="dmUser.id">
            <el-select
              v-model="form.dmUser.id"
              style="width: 370px;"
              filterable
              placeholder="请选择"
              @change="selectDept"
            >
              <el-option
                v-for="item in dmUsers"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="到访部门" prop="dept.id">
            <!--            <treeselect-->
            <!--              v-model="form.dept.id"-->
            <!--              :options="depts"-->
            <!--              :load-options="loadDepts"-->
            <!--              style="width: 370px;"-->
            <!--              placeholder="选择部门"-->
            <!--            />-->
            <el-input v-model="form.dept.name" disabled style="width: 370px;" />
          </el-form-item>
          <el-form-item label="到访开始时间">
            <el-date-picker v-model="form.startTime" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="到访结束时间">
            <el-date-picker v-model="form.endTime" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="访客办公室">
            <el-input v-model="form.administration" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="访客信息">
            <el-button type="primary" @click="addVisitor">新增访客</el-button>
            <el-table :data="data" border style="width: 480px">
              <el-table-column prop="visitorName" label="访客姓名">
                <template slot-scope="{ $index, row }">
                  <el-input v-if="($index === 0 && !isAdd) || row.isEdit" v-model="row.visitorName" />
                  <span v-else>{{ row.visitorName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="visitorPhone" label="访客手机号">
                <template slot-scope="{ $index, row }">
                  <el-input v-if="($index === 0 && !isAdd) || row.isEdit" v-model="row.visitorPhone" />
                  <span v-else>{{ row.visitorPhone }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="plateNumber" label="访客车辆">
                <template slot-scope="{ $index, row }">
                  <el-input v-if="($index === 0 && !isAdd) || row.isEdit" v-model="row.plateNumber" />
                  <span v-else>{{ row.plateNumber }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80px">
                <template slot-scope="{ row, $index }">
                  <el-button v-if="row.isEdit" type="text" @click="save(row)">保存</el-button>
                  <el-button v-else type="text" @click="edit(row)">编辑</el-button>
                  <el-button type="text" @click="del(row, $index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="到访事由">
            <el-input v-model="form.forVisiting" type="textarea" style="width: 480px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="closeAll">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="submitCU()">确认</el-button>
        </div>
      </el-dialog>
      <!-- 详情 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="detailShowXq" title="访客申请详情" width="40%">
        <el-descriptions class="margin-top" title="访客申请信息" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              被访人员姓名:
            </template>
            {{ detailItem.dmUser && detailItem.dmUser.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              被访人员职务:
            </template>
            {{ detailItem.dmUser && detailItem.dmUser.jobs && detailItem.dmUser.jobs[0] && detailItem.dmUser.jobs[0].name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              到访部门:
            </template>
            {{ detailItem.dept && detailItem.dept.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              到访办公室:
            </template>
            {{ detailItem.administration }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              到访开始时间:
            </template>
            {{ detailItem.startTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              到访结束时间:
            </template>
            {{ detailItem.endTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              到访事由:
            </template>
            {{ detailItem.forVisiting }}
          </el-descriptions-item>
        <!-- <el-descriptions-item>
          <template slot="label">
            访客二维码:
          </template>
          {{ detailItem.qrCode }}
        </el-descriptions-item> -->
        </el-descriptions>
        <br>
        <label>访客信息</label>
        <el-table :data="dataXq" border>
          <el-table-column prop="visitorName" label="访客姓名" />
          <el-table-column prop="visitorPhone" label="访客手机号" />
          <el-table-column prop="plateNumber" label="访客车牌" />
        </el-table>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="dmUser.name" label="被访人员姓名" />
        <el-table-column prop="dept.name" label="被访人员职务" />
        <el-table-column prop="administration" label="到访办公室" />
        <el-table-column prop="startTime" label="到访开始时间" />
        <el-table-column prop="endTime" label="到访结束时间" />
        <el-table-column prop="visNumber" label="到访人数" />
        <el-table-column prop="requestUser.name" label="申请人" />
        <el-table-column prop="createTime" label="申请时间" />
        <el-table-column prop="qrCode" label="访客二维码">
          <template slot-scope="scope">
            <QrCode :content="scope.row.qrCode" />
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','dmVisitorsApply:edit','dmVisitorsApply:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
            <!-- :show-del="false" -->
            <el-button slot="reference" type="primary" icon="el-icon-search" size="mini" @click="toDetail(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDmVisitorsApply from '@/api/dmVisitorsApply'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
import { getUser } from '@/api/dm/user/dmUser'
import { get, del } from '@/api/dmVisitorsUser'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
// import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import QrCode from '@/components/QrCode/QrCode.vue'

const defaultForm = { id: null, enabled: 'false', dept: { id: null }, dmUser: { id: null }, startTime: null, endTime: null, qrCode: null, forVisiting: null, administration: null }
export default {
  name: 'DmVisitorsApply',
  components: { QrCode, pagination, udOperation, DateRangePicker, [QrCode.name]: QrCode },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '访客记录', url: 'api/dmVisitorsApply', idField: 'id', sort: 'id,desc', crudMethod: { ...crudDmVisitorsApply }})
  },
  data() {
    return {
      buildDate: [],
      depts: [],
      dmUsers: [],
      permission: {
        add: ['admin', 'dmVisitorsApply:add'],
        edit: ['admin', 'dmVisitorsApply:edit'],
        del: ['admin', 'dmVisitorsApply:del']
      },
      rules: {
        id: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'userNumber', display_name: '被访人员工号' },
        { key: 'startTime', display_name: '到访开始时间' },
        { key: 'endTime', display_name: '到访结束时间' }
      ],
      // 访客信息表格数据
      data: [],
      isAdd: true,
      dataXq: [], // 详情表格
      detailItem: {}, // 详情
      detailShowXq: false
    }
  },
  methods: {
    selectDept(e) {
      const index = this.dmUsers.findIndex(item => item.id === e)
      this.form.dept.id = this.dmUsers[index].deptId
      this.form.dept.name = this.dmUsers[index].deptName
    },
    changeDate() {
      this.crud.query.startTime = this.buildDate[0] || ''
      this.crud.query.endTime = this.buildDate[1] || ''
      this.crud.query.requestUser = this.query.requestUser
      this.crud.toQuery()
    },
    resetDate() {
      this.buildDate = []
      this.query.requestUser = ''
      this.changeDate()
    },
    addVisitor() {
      if (!this.isAdd) {
        this.$message({
          message: '请先保存当前添加的数据',
          type: 'warning'
        })
        return
      }
      this.isAdd = false
      this.data.unshift({
        visitorName: '',
        visitorPhone: '',
        plateNumber: '',
        isEdit: true
      })
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getAllDmUser(form.id)
      if (form.id == null) {
        this.getDepts()
      } else {
        this.getVisApply(form.id)
        this.getSupDepts(form.dept.id)
      }
      form.enabled = form.enabled.toString()
    },
    getVisApply(id) {
      get({ id }).then(res => {
        this.data = res.content
        this.dataXq = res.content
      }).catch(() => { })
    },
    // 获取弹窗内DM用户数据
    getAllDmUser(params) {
      getUser(params).then(res => {
        this.dmUsers = res
      }).catch(() => { })
    },
    getSupDepts(deptId) {
      getDeptSuperior(deptId).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    save(item) {
      console.log(item)
      // if($index === 0) {
      this.isAdd = true
      this.$set(item, 'isEdit', false)
      this.$forceUpdate()
      // }
    },
    edit(item) {
      this.$set(item, 'isEdit', true)
      this.$forceUpdate()
    },
    del(item, $index) {
      console.log(item)
      this.data.splice($index, 1)
      if ($index === 0) {
        this.isAdd = true
      }
      const ids = []
      ids.push(item.visitorId)
      del(ids).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      }).catch((res) => {
      })
    },
    submitCU() {
      const param = {
        ... this.form,
        visNumber: this.data.length,
        visotors: this.data
      }
      // 访客信息数据
      if (this.form.id === null || this.form.id === undefined) {
        crudDmVisitorsApply.add(param).then(res => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.crud.cancelCU()
          this.crud.refresh()
        }).catch((res) => {
        })
      } else {
        crudDmVisitorsApply.edit(param).then(res => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.crud.cancelCU()
          this.crud.refresh()
        }).catch((res) => {
        })
      }
    },
    // 详情
    toDetail(row) {
      this.detailItem = row
      this.detailShowXq = true
      this.getVisApply(row.id)
    },
    closeAll() {
      this.form.dmUser.id = ''
      this.form.dept.id = ''
      this.form.startTime = ''
      this.form.endTime = ''
      this.form.administration = ''
      this.form.forVisiting = ''
      this.data = []
      this.crud.status.cu = 0
      this.crud.cancelCU()
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }
  }
}
</script>

<style scoped>

</style>
