<template>
  <div class="app-container">
    <el-form label-width="80px">
      <el-row>
        <el-col :span="4">
          <el-form-item label="姓名">
            <el-input v-model="USERNAME" placeholder="请输入隐患描述" class="filter-item" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="出入类型">
            <el-select v-model="STATE" clearable style="width: 100%;">
              <el-option v-for="item in stateList" :key="item.value" :label="item.lable" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请时间">
            <el-date-picker v-model="dates" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="10px">
            <el-button v-waves type="primary" icon="el-icon-search" @click="getQuery">
              查询
            </el-button>
            <el-button v-waves type="success" icon="el-icon-refresh" @click="goKeyReset">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table v-loading="listLoading" ref="multipleTable" :data="varList" :row-key="getRowKey" :header-cell-style="{'font-weight': 'bold','color': '#000'}" tooltip-effect="dark" border fit highlight-current-row>
      <el-table-column :reserve-selection="true" type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="CARDNUMBER" label="卡号" />
      <el-table-column prop="USERNUMBER" label="持卡人编号" />
      <el-table-column prop="USERNAME" label="持卡人姓名">
        <!--<template slot-scope="{row}"/>-->
      </el-table-column>
      <el-table-column prop="STATE" label="出入类型" >
        <template slot-scope="{row}">
          <template v-if="row.STATE =='0'">进入</template>
          <template v-else>出去</template>
        </template>
      </el-table-column>
      <el-table-column prop="TIME" label="时间"/>
      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="{row}">
          <el-button icon="el-icon-view" size="mini" @click="goDetail(row)">查看</el-button>
          <!--<template v-if="row.STATE=='0'">
            <el-button v-show="edit" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row.FOREIGNCAR_ID)">编辑</el-button>
          </template>
          <el-button v-show="del" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row)">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">申请</el-button>
        <!--
        <el-button v-show="del" type="danger" icon="el-icon-delete" plain @click="batchDel">删除</el-button>
-->
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog :visible.sync="dialogFormEdit" :title="dialogType==='edit'?'修改':'申请'" width="600px">
      <el-form ref="form" :rules="rules" :model="form" label-width="110px" style="width: 500px;">
        <el-form-item label="来源单位" prop="SOURCE_UNIT">
          <el-input v-model="form.SOURCE_UNIT" placeholder="请输入来源单位" />
        </el-form-item>
        <el-form-item label="车牌号" prop="LICENSE_PLATE">
          <el-input v-model="form.LICENSE_PLATE" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="申请用时" prop="APPLICATION_TIME">
          <div class="block">
            <el-date-picker
              :default-time="['00:00:00','23:59:59']"
              v-model="form.APPLICATION_TIME"
              value-format=" yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%;"
            />
          </div>
        </el-form-item>
        <el-form-item label="车型" prop="MODEL">
          <el-input v-model="form.MODEL" placeholder="请输入车型信息" />
        </el-form-item>
        <el-form-item label="车内人员数" prop="NUMBER_PEOPLE_CAR">
          <el-input v-model.number="form.NUMBER_PEOPLE_CAR" placeholder="请输入车内人员数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--        <el-button type="primary" plain @click="gosave">保 存</el-button>-->
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="confirm">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import SelectTree from '@/components/SelectTree'
import waves from '@/directive/waves' // waves directive
import vueQr from 'vue-qr'
import { upload } from '@/utils/upload'
import { Message } from 'element-ui'
import moment from 'moment'
export default {
  components: { Pagination, SelectTree, vueQr },
  directives: { waves },
  data() {
    return {
      styleText: '<style type="text/css" media="print">\n' + '  @page { size: landscape; }\n' + '</style>',
      config: config,
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      CARDNUMBER: '',
      USERNAME: '',
      TYPE: '',
      STATE: '',
      dates: [],
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      KEYWORDS: this.$route.query.KEYWORDS || '',
      DEPARTMENT_ID: '',
      varList: [],
      qrcodeStr: '',
      form: {
        SOURCE_UNIT: '',
        LICENSE_PLATE: '',
        APPLICATION_TIME: [],
        MODEL: '',
        NUMBER_PEOPLE_CAR: '',
        STATE: ''
      },
      stateList: [
        { lable: '进入', value: '0' },
        { lable: '出去', value: '1' }
      ],

      treeData: [],
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogFormShow: false,
      dialogType: 'add',
      rules: {
        SOURCE_UNIT: [{ required: true, message: '来源单位不能为空', trigger: 'blur' }],
        LICENSE_PLATE: [{ required: true, message: '车牌号不能为空', trigger: 'blur' }],
        APPLICATION_TIME: [{ required: true, message: '申请用时不能为空', trigger: 'blur' }],
        MODEL: [{ required: true, message: '车型不能为空', trigger: 'blur' }],
        NUMBER_PEOPLE_CAR: [
          { required: true, message: '车内人员数不能为空', trigger: 'change' },
          { type: 'number', message: '车内人员数必须为数字' }
        ]
      },
      dialogFormDaoru: false,
      daoruFrom: {
        FFILE: '',
        FFILEName: ''
      }
    }
  },
  created() {
    this.getList()
    this.getTreeList()
  },
  methods: {
    getRowKey(row) {
      return row.RISKUNIT_ID
    },
    getTreeList() {
      requestFN(
        '/department/listTree',
        {}
      ).then((data) => {
        this.treeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
      })
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.SOURCE_UNIT = ''
      this.USERNAME = ''
      this.TYPE = ''
      this.STATE = ''
      this.dates = []
      this.DEPARTMENT_ID = ''
      this.getQuery()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/homeseconddoor/listCardUser?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          SOURCE_UNIT: this.SOURCE_UNIT,
          DEPARTMENT_ID: this.DEPARTMENT_ID,
          STATE: this.STATE,
          TYPE: this.TYPE,
          USERNAME: this.USERNAME,
          STARTTIME: this.dates[0],
          ENDTIME: this.dates[1]
        }
      ).then((data) => {
        this.listLoading = false
        console.log(data.varList)
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 添加
    handleAdd() {
      this.dialogType = 'add'
      this.dialogFormEdit = true
      this.resetForm()
      this.$refs.deptTree.clearHandle()
      this.getDict()
    },
    // 修改
    handleEdit(ID) {
      this.getDict()
      this.dialogType = 'edit'
      requestFN(
        '/foreigncar/goEdit',
        {
          FOREIGNCAR_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        // eslint-disable-next-line no-unused-vars
        var arrList = this.form.APPLICATION_TIME.split(',')
        this.form.APPLICATION_TIME = arrList
        const node = {}
        node.id = this.form.DEPARTMENT_ID
        if (this.form.STATE != '0') {
          this.$message('状态不是已打回')
          this.dialogFormEdit = false
        } else {
          this.dialogFormEdit = true
        }
        this.$refs.deptTree.clearHandle()
        this.$nextTick(() => { // 此处使用这个可以等节点渲染后再获取节点
          this.$refs.deptTree.handleNodeClick(node)
        })
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 保存
    gosave() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          this.form.STATE = '0'
          this.form.STARTTIME = this.form.APPLICATION_TIME[0]
          this.form.ENDTIME = this.form.APPLICATION_TIME[1]
          requestFN(
            '/foreigncar/' + this.dialogType,
            this.form
          ).then((data) => {
            this.listLoading = false
            this.dialogFormEdit = false
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    // 提交
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const startTime = this.form.APPLICATION_TIME[0]
          const endTime = this.form.APPLICATION_TIME[1]
          if (moment(startTime).diff(moment(endTime), 'minute') < -1440) {
            this.$message.error('申请用时不能超过24小时')
            return false
          }
          this.listLoading = true
          this.form.STATE = '1'
          requestFN(
            '/foreigncar/' + this.dialogType,
            this.form
          ).then((data) => {
            this.listLoading = false
            this.dialogFormEdit = false
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    goQrcode(row) {
      this.dialogFormShow = true
      this.pd = Object.assign({}, row)
      this.qrcodeStr = this.config.weburl + 'static/qrcode/views/fxfb/index.html?FID=' + row.RISKUNIT_ID
    },
    beforeFileUpload(file) {
      this.daoruFrom.FFILE = file
      this.daoruFrom.FFILEName = file.name
      this.$forceUpdate()
      return false
    },
    goUpload() {
      const formData = new FormData()
      Object.keys(this.daoruFrom).map(key => {
        formData.append(key, this.daoruFrom[key])
      })
      upload(
        '/riskunit/readExcel',
        formData
      ).then((data) => {
        if (data.msg) {
          Message({
            message: data.msg,
            type: data.type,
            duration: 5 * 1000
          })
        }
        this.dialogFormDaoru = false
        this.getList()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    getDaochu() {
      this.$confirm('确定要导出到excel吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.location.href = config.httpurl + 'riskunit/excel'
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    },
    getExcelModel() {
      this.$confirm('确定要下载excel模板吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.location.href = config.httpurl + 'riskunit/excelModel'
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    },
    handleDelete(row) {
      if (row.STATE > 0) {
        this.$message('流程进行中，不可删除')
      } else {
        (
          this.$confirm('确定要删除吗?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.listLoading = true
            requestFN(
              '/foreigncar/delete',
              {
                FOREIGNCAR_ID: row.FOREIGNCAR_ID
              }
            ).then(() => {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.listLoading = false
              this.varList = []
              this.listQuery.page = 1
              this.getList()
            }).catch((e) => {
              this.listLoading = false
            })
          }).catch(() => {
          })
        )
      }
    },

    batchDel() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.RISKUNIT_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/riskunit/deleteAll',
          {
            DATA_IDS: ids
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 判断按钮权限，用于是否显示按钮
    hasButton() {
      var keys = 'foreigncar:add,foreigncar:del,foreigncar:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.foreigncarfhadminadd		// 新增权限
        this.del = data.foreigncarfhadmindel		// 删除权限
        this.edit = data.foreigncarfhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取数据字典数据
    getDict() {
    },
    resetForm() {
      this.$refs.form && this.$refs.form.resetFields()
    },
    goDetail(row) {
      this.$parent.activeName = 'Info'
      this.$parent.CARDID = row.CARDID
    }
  }
}

</script>
<style lang="sass" scoped>
  .table-qrcode
    text-align: center
    padding-top: 20px
    width: 100%
  .filter-container
    position: relative
    .filter-flot
      position: absolute
      right: 0
      top: 0
  .uploader
    width: 570px
    display: flex
    align-items: center
  .el-form-item__content
    line-height: 1
</style>
