<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <!--        <label class="el-form-item-label">卡号</label>-->
        <el-input v-model="query.cardNumber" clearable placeholder="卡号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!--        <label class="el-form-item-label">工号</label>-->
        <el-input v-model="query.dmUserNumber" clearable placeholder="工号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!--        <label class="el-form-item-label">员工名称</label>-->
        <el-input v-model="query.userName" clearable placeholder="员工名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!--        <label class="el-form-item-label">开卡状态</label>-->
        <el-select v-model="query.status" clearable placeholder="请选择开卡状态" class="filter-item" style="width: 185px" @keyup.enter.native="crud.toQuery">
          <el-option
            v-for="item in dict.card_status"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">开卡时间</label>
        <DateRangePicker
          v-model="query.createTime"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width: 300px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <el-button class="button" style="margin-right: 20px" type="primary" @click="toOpenKai()">开卡</el-button>
      <!-- <el-button style="margin-right: 20px" type="primary" @click="toOpenGua(crud.data)">挂失</el-button>-->
      <el-button class="button1" style="margin-right: 20px" type="primary" @click="toOpenJie()">解挂</el-button>
      <!-- <el-button type="primary" @click="toOpenZhu(crud.data)">注销</el-button> -->
      <!-- 详情 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="detailShow" title="一卡通详情" width="40%">
        <el-descriptions class="margin-top" title="基本信息" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              一卡通卡号:
            </template>
            {{ detailItem.cardNumber }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              一卡通状态:
            </template>
            {{ dict.label.card_status[detailItem.status] }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              开卡时间:
            </template>
            {{ detailItem.createTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              开卡操作账号:
            </template>
            {{ detailItem.createBy }}
          </el-descriptions-item>
        </el-descriptions>
        <br>
        <el-descriptions class="margin-top" title="持卡人信息" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              持卡人姓名:
            </template>
            {{ detailItem.userName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              人员种类:
            </template>
            {{ dict.label.user_type[detailItem.userType] }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              员工工号:
            </template>
            {{ detailItem.dmUser && detailItem.dmUser.userNumber }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              所属单位:
            </template>
            {{ detailItem.dmUser && detailItem.dmUser.company }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              手机号:
            </template>
            {{ detailItem.dmUser && detailItem.dmUser.contacts }}
          </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.dmUser && detailItem.dmUser.dept && detailItem.dmUser.dept.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              人员状态:
            </template>
            {{ dict.label.dept_status[detailItem.dmUser && detailItem.dmUser.status] }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              人脸照片:
            </template>
            <el-image
              style="width: 100px; height: 100px"
              :src="baseApi + '/file/' + (detailItem.dmUser && detailItem.dmUser.picture)"
              :preview-src-list="[baseApi + '/file/' + (detailItem.dmUser && detailItem.dmUser.picture)]"
              fit="contain"
              lazy
              class="el-avatar"
            >
              <div slot="error">
                <i class="el-icon-picture" />
              </div>
            </el-image><br>
            照片要求：<label style="color:red">人脸照片将用于门禁/考勤/消费类结算，请务必上传本人近照，照片务必为人脸照；且清晰呈现人脸面部</label>
          </el-descriptions-item>
        </el-descriptions>
        <!-- <el-table :data="data" border style="width: 480px">
          <el-table-column prop="cardNumber" label="设备编号" />
          <el-table-column prop="cardNumber" label="安装位置" />
       </el-table> -->
        <!-- <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="detailShow = false">关闭</el-button>
        </div> -->
      </el-dialog>
      <!-- 开卡 -->
      <el-dialog :close-on-click-modal="false" :before-close="close" :visible.sync="detailShow1" title="开卡" width="30%">
        <div class="block">
          <el-timeline ref="form" :model="form" :rules="rules">
            <el-timeline-item color="#2F8CE9">
              <h2 style="color: #2F8CE9">第一步</h2>
              <h4 style="color: #B4B0B0">请将鼠标点击到卡号输入栏，将IC卡放置于读卡器内，读出的卡号将自动输入到当前的输入栏内</h4>
              <label class="el-form-item-label">一卡通卡号:</label>
              <el-input v-model="form.cardNumber" placeholder="请输入内容" style="width: 235px;" class="filter-item" @change="changeKai()" />
              <h6 style="color: #E42525">注：请先确认已连接读卡器</h6>
            </el-timeline-item>
            <el-timeline-item v-show="showKai2" color="#2F8CE9">
              <h2 style="color: #2F8CE9">第二步</h2>
              <h4 style="color: #B4B0B0">请选择持卡人</h4>
              <label class="el-form-item-label">持卡人姓名:</label>
              <!-- <el-input v-model="query.blurry" placeholder="搜索员工姓名/员工工号" style="width: 235px;" class="filter-item" @change="getUser"></el-input> -->
              <el-select
                v-model="form.blurry"
                style="width: 300px"
                filterable
                :filter-method="filterUser"
                placeholder="搜索员工姓名/员工工号"
                @change="changeUser()"
              >
                <el-option
                  v-for="item in dmUsers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-timeline-item>
            <el-timeline-item v-show="showKai3" color="#2F8CE9">
              <h2 style="color: #2F8CE9">第三步</h2>
              <h4 style="color: #B4B0B0">请核对持卡人相关信息</h4>
              <el-descriptions :column="2">
                <el-descriptions-item label="一卡通卡号">{{ detaKai.cardNumber }}</el-descriptions-item>
                <el-descriptions-item label="持卡人姓名">{{ detaKai.name }}</el-descriptions-item>
                <el-descriptions-item label="员工工号">{{ detaKai.userNumber }}</el-descriptions-item>
                <el-descriptions-item label="人员种类">
                  {{ dict.label.user_type[detaKai.userType] }}
                </el-descriptions-item>
                <el-descriptions-item label="手机号">{{ detaKai.contacts }}</el-descriptions-item>
                <el-descriptions-item label="在职状态">
                  {{ dict.label.dm_enabled[detaKai.enabled] }}
                </el-descriptions-item>
                <el-descriptions-item label="所属部门">{{ detaKai.dept }}</el-descriptions-item>
                <el-descriptions-item label="当前职务">{{ detaKai.jobs }}</el-descriptions-item>
              </el-descriptions>
            </el-timeline-item>
            <el-timeline-item v-show="showKai4" color="#2F8CE9">
              <h2 style="color: #2F8CE9">第四步</h2>
              <h4 style="color: #B4B0B0">点击“开通”，激活此卡。</h4>
              <h6 style="color: #E42525">注：此人未做“登记”，请先至“人员管理”模块完成人脸及门禁权限相关配置，完成“登记”后再开卡</h6>
              <el-button style="margin-left: 250px" :loading="crud.status.cu === 2" type="primary" @click="openCard">开通</el-button>
              <el-button type="info" @click="detailShow1 = false">关闭</el-button>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-dialog>
      <!-- 挂失 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="detailShow2" title="挂失" width="35%">
        <div class="block">
          <h2>您正在对以下账号进行操作，确认对此卡进行挂失操作</h2>
          <h4 style="color: #B4B0B0">挂失完成将冻结此卡全部权限</h4>
          <el-descriptions>
            <el-descriptions-item label="一卡通卡号：">{{ detaGua.cardNumber }}</el-descriptions-item>
            <el-descriptions-item label="持卡人姓名：">{{ detaGua.userName }}</el-descriptions-item>
          </el-descriptions>
          <el-button style="margin-left: 220px;margin-top: 20px" type="primary" @click="approval('01')">确定</el-button>
          <el-button style="margin-top: 20px" type="info" @click="detailShow2 = false">取消</el-button>
        </div>
      </el-dialog>
      <!-- 解挂 -->
      <el-dialog :close-on-click-modal="false" :before-close="close" :visible.sync="detailShow3" title="解挂" width="30%">
        <div class="block">
          <el-timeline ref="form" :model="form" :rules="rules">
            <el-timeline-item color="#2F8CE9">
              <h2 style="color: #2F8CE9">第一步</h2>
              <h4 style="color: #B4B0B0">请将鼠标点击到卡号输入栏，将IC卡放置于读卡器内，读出的卡号将自动输入到当前的输入栏内</h4>
              <label class="el-form-item-label">一卡通卡号:</label>
              <el-input v-model="form.cardNumber" placeholder="请输入内容" style="width: 235px;" class="filter-item" @change="changeJie()" />
              <h6 style="color: #E42525">注：请先确认已连接读卡器</h6>
            </el-timeline-item>
            <el-timeline-item v-show="showKai2" color="#2F8CE9">
              <h2 style="color: #2F8CE9">第二步</h2>
              <h4 style="color: #B4B0B0">请核对以下持卡人信息确认无误</h4>
              <el-descriptions :column="2">
                <el-descriptions-item label="一卡通卡号">{{ detaJie.cardNumber }}</el-descriptions-item>
                <el-descriptions-item label="持卡人姓名">{{ detaJie.name }}</el-descriptions-item>
                <el-descriptions-item label="员工工号">{{ detaJie.userNumber }}</el-descriptions-item>
                <el-descriptions-item label="人员种类">
                  {{ dict.label.user_type[detaJie.userType] }}
                </el-descriptions-item>
                <el-descriptions-item label="手机号">{{ detaJie.contacts }}</el-descriptions-item>
                <el-descriptions-item label="人员状态">
                  {{ dict.label.dept_status[detaJie.user_status] }}
                </el-descriptions-item>
                <el-descriptions-item label="所属部门">{{ detaJie.dept }}</el-descriptions-item>
                <el-descriptions-item label="当前职务">{{ detaJie.jobs }}</el-descriptions-item>
              </el-descriptions>
            </el-timeline-item>
            <el-timeline-item v-show="showKai2" color="#2F8CE9">
              <h2 style="color: #2F8CE9">第三步</h2>
              <h4 style="color: #B4B0B0">点击“解挂”，重新启用此卡权限</h4>
              <el-button style="margin-left: 250px" :loading="crud.status.cu === 2" type="primary" @click="approval('00')">解挂</el-button>
              <el-button type="info" @click="detailShow3 = false">关闭</el-button>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-dialog>
      <!-- 注销 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="detailShow4" title="注销" width="35%">
        <div class="block">
          <h2>您正在对以下账号进行操作，确认对此卡进行注销操作</h2>
          <h4 style="color: #B4B0B0">注销完成将此卡全部权限将失效</h4>
          <el-descriptions>
            <el-descriptions-item label="一卡通卡号：">{{ detaZhu.cardNumber }}</el-descriptions-item>
            <el-descriptions-item label="持卡人姓名：">{{ detaZhu.userName }}</el-descriptions-item>
          </el-descriptions>
          <el-button style="margin-left: 220px;margin-top: 20px" type="primary" @click="approval('02')">确定</el-button>
          <el-button style="margin-top: 20px" type="info" @click="detailShow4 = false">取消</el-button>
        </div>
      </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="id" label="id" /> -->
        <el-table-column prop="cardNumber" label="卡号" />
        <el-table-column prop="dmUser.userNumber" label="用户工号" />
        <el-table-column prop="userName" label="用户名称" />
        <el-table-column prop="userType" label="用户种类">
          <template slot-scope="scope">
            {{ dict.label.user_type[scope.row.userType] }}
          </template>
        </el-table-column>
        <el-table-column label="余额">
          <template slot-scope="scope">
            <!--            {{ scope.row.balance }}-->
            <el-button v-if="scope.row.balance == null" @click="getCardBalance(scope.row)">查看余额</el-button>
            <span v-if="scope.row.balance !== null">{{ scope.row.balance }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dept.name" label="用户部门" />
        <el-table-column prop="status" label="开卡状态">
          <template slot-scope="scope">
            {{ dict.label.card_status[scope.row.status] }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="balance" label="余额" /> -->
        <el-table-column prop="createTime" label="开卡时间" />
        <el-table-column v-if="checkPer(['admin','dmCard:edit','dmCard:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <!-- <udOperation
              :data="scope.row"
              :permission="permission"
            /> -->
            <el-button
              v-if="scope.row.status === '00'"
              size="mini"
              type="primary"
              @click="toOpenGua(scope.row)"
            >挂失</el-button>
            <el-button
              v-if="scope.row.status === '00'"
              size="mini"
              type="primary"
              @click="toOpenZhu(scope.row)"
            >注销</el-button>
            <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 crudDmCard from '@/api/dm/card/dmCard'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
// import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
import { getAllDmUserCard, getAll } from '@/api/dm/user/dmUser'
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 { mapGetters } from 'vuex'

const defaultForm = { id: null, cardNumber: null, blurry: null, userNumber: null, userName: null, enabledForm: 'false', userType: null, jobs: { id: null }, dept: { id: null }, dmUser: { id: null }, status: null, balance: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'DmCard',
  components: { DateRangePicker, pagination, crudOperation, rrOperation }, //, udOperation, Treeselect
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['user_type', 'dept_status', 'card_status', 'dm_enabled'],
  cruds() {
    return CRUD({ title: '一卡通管理', url: 'api/dmCard', idField: 'id', sort: 'id,desc', crudMethod: { ...crudDmCard }, optShow: { download: true, reset: true }})
  },
  data() {
    return {
      detailShow: false,
      detailItem: {},
      data: [],
      depts: [],
      deptData: {},
      appId: '',
      dmUsers: [],
      dmUsersCopy: [], // 用作下拉框筛选
      detaGua: {},
      detaZhu: {},
      detaKai: {},
      detaJie: {},
      detailShow1: false,
      detailShow2: false,
      detailShow3: false,
      detailShow4: false,
      showKai2: false,
      showKai3: false,
      showKai4: false,
      permission: {
        add: ['admin', 'dmCard:add'],
        edit: ['admin', 'dmCard:edit'],
        del: ['admin', 'dmCard:del']
      },
      rules: {
        // id: [
        //   { required: true, message: '不能为空', trigger: 'blur' }
        // ],
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'cardNumber', display_name: '卡号' },
        { key: 'userNumber', display_name: '用户工号' },
        { key: 'userName', display_name: '用户名称' },
        { key: 'userType', display_name: '用户种类(00-正式人员、01-外协单位、02-租户、03-访客)' },
        { key: 'deptId', display_name: '用户部门' },
        { key: 'status', display_name: '开卡状态(00-已开通、01-挂失中、02-已注销)' },
        // { key: 'balance', display_name: '余额' },
        { key: 'createBy', display_name: '创建者' },
        { key: 'updateBy', display_name: '更新者' },
        { key: 'createTime', display_name: '创建时间' },
        { key: 'updateTime', display_name: '更新时间' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      // 'imagesUploadApi',
      'baseApi'
    ])
  },
  created() {
    this.getUser()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    getCardBalance(row) {
      const index = this.crud.data.findIndex(item => item.id === row.id)
      crudDmCard.getCardBalance(row.cardNumber).then(res => {
        row.balance = res.data
        this.$set(this.crud.data, index, row)
      })
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getAllDmUserCard(form.id)
      if (form.id == null) {
        this.getDepts()
      } else {
        this.getSupDepts(form.dept.id)
      }
      form.enabledForm = form.enabledForm.toString()
    },
    changeKai() {
      if (this.form.cardNumber !== undefined || this.form.cardNumber !== null) {
        this.showKai2 = true
      }
    },
    changeJie() {
      crudDmCard.get({ 'cardNumber': this.form.cardNumber }).then(res => {
        this.detaJie.status = res.content[0].status
        this.appId = res.content[0].id
        if (this.form.cardNumber !== undefined || this.form.cardNumber !== null) {
          if (this.detaJie.status === '01') {
            this.showKai2 = true
          } else {
            this.$message({
              message: '此卡号未挂失',
              type: 'success'
            })
          }
        }
      }).catch((res) => {
      })
      getAll({
        id: this.form.blurry
      }).then(res => {
        this.detaJie = res.content[0]
        this.detaJie.cardNumber = this.form.cardNumber
        this.detaJie.dept = res.content[0].dept.name
        this.detaJie.jobs = res.content[0].jobs[0].name
      }).catch(() => { })
    },
    changeUser() {
      this.showKai3 = true
      this.showKai4 = true
      getAll({
        id: this.form.blurry
      }).then(res => {
        this.detaKai = res.content[0]
        this.detaKai.cardNumber = this.form.cardNumber
        this.deptData = res.content[0].dept
        this.detaKai.dept = res.content[0].dept.name
        this.detaKai.jobs = res.content[0].jobs[0] && res.content[0].jobs[0].map(item => item.name).join(',')
      }).catch(() => { })
    },
    toOpenKai() {
      this.detailShow1 = true
    },
    toOpenGua(row) {
      this.detaGua = row
      this.appId = row.id
      this.detailShow2 = true
    },
    toOpenJie() {
      // this.detaJie = row
      this.detailShow3 = true
    },
    toOpenZhu(row) {
      this.detaZhu = row
      this.appId = row.id
      this.detailShow4 = true
    },
    // 用戶根据工号或者姓名查询
    filterUser(val) {
      if (val) {
        this.dmUsers = this.dmUsersCopy.filter(item => {
          return (item.name && item.name.indexOf(val) > -1) || (item.id && item.id.indexOf(val) > -1)
        })
        // this.showKai3=true
      } else {
        this.dmUsers = this.dmUsersCopy
      }
    },
    // 选择人员信息
    getUser() {
      getAllDmUserCard({
        blurry: this.form.blurry
      }).then(res => {
        this.dmUsers = res
        this.dmUsersCopy = JSON.parse(JSON.stringify(res))// .content
      }).catch(() => { })
    },
    // 开卡
    openCard() {
      var data = {}
      data = this.form
      // data['dmUser'] = this.detaKai
      // data['deptId'] = this.deptData.id
      const user = JSON.parse(JSON.stringify(this.detaKai))
      delete user.dept
      user.jobs = null
      data['dmUser'] = user
      data['dept'] = this.deptData
      data['status'] = '00'
      // data[this.tmpType + 'List'] = user
      // console.log(typeof this.dept);
      crudDmCard.add(data).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.detailShow1 = false
        this.crud.refresh()
      }).catch((res) => {
        this.$message({
          message: '操作失败',
          type: 'success'
        })
      })
    },
    // 挂失,注销,解挂
    approval(value) {
      crudDmCard.edit({ 'id': this.appId, 'status': value }).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.id = ''
        if (value === '01') {
          this.detailShow2 = false
        } else if (value === '02') {
          this.detailShow4 = false
        } else if (value === '00') {
          this.detailShow3 = false
        }
        this.crud.refresh()
      }).catch((res) => {
      })
    },
    // 详情
    toDetail(row) {
      this.detailItem = row
      this.detailShow = true
    },
    // 获取弹窗内DM用户数据
    getAllDmUserCard(params) {
      getAllDmUserCard(params).then(res => {
        this.dmUsers = res
      }).catch(() => { })
    },
    getDepts() {
      getDepts({ enabledForm: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    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
        }
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabledForm: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    close(done) {
      this.form.cardNumber = ''
      this.showKai2 = false
      done()
    }
  }
}
</script>

<style scoped>
.button{
  position: relative;
  left: 80px;
  top: -42px;
  height: 28px;
  width: 80px;
}
.button1{
  position: relative;
  left: 63px;
  top: -42px;
  height: 28px;
  width: 80px;
}
</style>
