<template>
  <div class="common-page device-manage">

    <div class="option page-row">
      <!--工具栏-->
      <div class="head-container">
        <!-- 搜索 -->
        <label class="el-form-item-label" style="font-weight: 500;">人员姓名</label>
        <el-input v-model="query.name" clearable size="small" placeholder="请输入人员姓名" style="width:180px;"/>
        <label class="el-form-item-label" style="font-weight: 500;">安全帽</label>
        <el-input v-model="query.safetyhatmac" clearable size="small" placeholder="请输入安全帽MAC" style="width:180px;"/>
        <label class="el-form-item-label" style="font-weight: 500;">日期范围</label>
        <el-date-picker
          v-model="query.timeList"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
        <el-button size="mini" type="success" icon="el-icon-search" @click="toSearch">搜索</el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="clearLimit">重置</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="panel-bottom page-row">
      <div class="ctin-box">
        <div class="content-within">
          <div class="content-fix">
            <div class="toolbar">
              <el-button size="mini" type="primary" icon="el-icon-plus" @click="toAdd">新增</el-button>
              <el-button size="mini" icon="el-icon-document" @click="downloadFile">导出</el-button>
            </div>
            <div class="content">
              <el-table :data="tableData" v-loading="loading" border style="width:auto" :row-class-name="tableRowClassName">
                <el-table-column prop="name" label="人员姓名" align="center"></el-table-column>
                <el-table-column prop="sex" label="性别" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.sex===1?'男':'女' }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="phone" label="电话" align="center"></el-table-column>
                <el-table-column prop="cameraid" label="摄像头id" align="center"></el-table-column>
                <el-table-column prop="safetyhatmac" label="安全帽MAC" align="center"></el-table-column>
                <el-table-column prop="safetyhatelectricity" label="安全帽电量" align="center"></el-table-column>
                <el-table-column prop="safetyhatstatus" label="安全帽状态" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.safetyhatstatus=='1'?'在线':'离线' }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="lastonlinetime" label="最后一次在线时间" align="center"></el-table-column>
                <el-table-column label="操作" align="center" fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="toEdit(scope.row)"></el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" @click="toDelete(scope.row)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!--分页组件-->
              <el-pagination :total="total" :current-page="page" style="margin-top: 8px;"
                             layout="total, prev, pager, next, sizes" @size-change="sizeChange"
                             @current-change="pageChange"/>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 表单渲染 -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelForm" :visible.sync="visible" :title="title" width="800px">
      <el-form :model="formData" :rules="rules" ref="formViewRef" :inline="true" :status-icon="true">
        <el-row>
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="人员名称：" class="form-cell" prop="name">
                <div class="cell-box">
                  <el-input v-model="formData.name" class="cell-input"></el-input>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="性别：" class="form-cell" prop="sex">
                <div class="cell-box">
                  <el-select v-model="formData.sex" placeholder="无" class="cell-input">
                    <el-option v-for="item in sexOpts" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="电话：" class="form-cell" prop="phone">
                <div class="cell-box">
                  <el-input v-model="formData.phone" class="cell-input"></el-input>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="摄像头id：" class="form-cell" prop="cameraid">
                <div class="cell-box">
                  <el-input v-model="formData.cameraid" class="cell-input"></el-input>
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="部门：" class="form-cell" prop="deptid">
                <div class="cell-box">
                  <treeselect
                    :multiple="false"
                    :options="allDepartmentData"
                    :load-options="loadOptions"
                    placeholder="请选择部门"
                    style="width: 200px"
                    @select="selectDepart"
                    v-model="formData.deptid"
                  />
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="岗位：" class="form-cell" prop="postid">
                <div class="cell-box">
                  <el-select v-model="formData.postid" placeholder="请选择岗位" >
                    <el-option v-for="(obj,index) in allPostData" :label="obj.name" :value="obj.name" :key="index"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="安全帽MAC：" class="form-cell" prop="safetyhatmac">
                <div class="cell-box">
                  <el-input v-model="formData.safetyhatmac" class="cell-input"></el-input>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="安全帽颜色：" class="form-cell" prop="color">
                <div class="cell-box">
                  <el-select v-model="formData.color" placeholder="无" class="cell-input">
                    <el-option v-for="item in colorOpts" :key="item.value" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content">
              <el-form-item label="身份证号：" class="form-cell" prop="idcard">
                <div class="cell-box">
                  <el-input v-model="formData.idcard" class="cell-input"></el-input>
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="grid-content">
              <el-form-item label="上传照片：" class="form-cell">
                <div class="cell-box">
                  <el-input v-model="formData.photo" style="width:160px;" placeholder="请上传照片" disabled />
                  <input type="file" name="image" @change="excelImport($event)" />
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="submitForm('formViewRef', formData)">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {Tools, HttpReq, Dates} from '@/assets/js/common.js';
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

export default {
  name: 'peopleLocation',
  components: {Treeselect},
  data() {
    const basePathUrl = window.basePathUrl || ''
    return {
      configUrl: basePathUrl + 'config/config.json',
      title: '新增',
      visible: false,
      loading: false,
      page: 1,
      size: 10,
      total: 0,
      query: {},
      map: null,
      graphicLayer: null,
      sexOpts: [
        {label: '男', value: 1},
        {label: '女', value: 2},
      ],
      colorOpts:[
        {label: '红色', value: '1'},
        {label: '黄色', value: '2'},
        {label: '蓝色', value: '3'},
      ],
      tableData: [],
      allDepartmentData: [],
      allPostData: [],
      formData: {
        name: '',
        sex: 1,
        phone: '',
        cameraid: '',
        idcard: '',
        safetyhatmac: '',
        color: '1',
        deptid: undefined,
        postid: undefined,
        photo: '',
      },
      deptName: '',
      rules: {
        name: {required: true, message: ' ', trigger: 'blur'},
        phone: {required: true, message: ' ', trigger: 'blur'},
        cameraid: {required: true, message: ' ', trigger: 'blur'},
        safetyhatmac: {required: true, message: ' ', trigger: 'blur'},
        idcard: {required: true, message: ' ', trigger: 'blur'},
      },
    }
  },
  mounted() {
    this.$nextTick(() => {
      //获取用于选择的部门
      HttpReq.truckDispatching.getAllDepartmentQuery({enabled: true}).then((response) => {
        for(let index of response.content){
          let modeInfo = {} ;
          modeInfo.id = index.id
          modeInfo.label = index.name;
          modeInfo.children = null;
          this.allDepartmentData.push(modeInfo);
        }
      });
      //获取用于选择的岗位
      HttpReq.truckDispatching.getAllPostQuery({size:9999}).then((res) => {
        this.allPostData = res.content;
      });
      this.loadData();
    })
  },
  methods: {
    selectDepart(val){
      this.deptName = val.label;
      return val.label;
    },
    loadOptions({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        HttpReq.truckDispatching.getAllDepartmentQuery({enabled: true, pid: parentNode.id}).then(response => {
          let arr = [];
          for(let index of response.content){
            let chiledModeInfo = {};
            chiledModeInfo.id = index.id;
            chiledModeInfo.label = index.name;
            arr.push(chiledModeInfo);
          }
          parentNode.children = response.content.map(function(obj) {
            if(obj.hasChildren) {
              obj.children = null;
            }
            return obj
          })
        });
        setTimeout(() => {
          callback()
        }, 200)
      }
    },
    formatOpt(arr,val){
      let str='';
      arr.forEach((item)=>{
        if(item.value==val){
          str = item.label;
        }
      });
      return str;
    },
    loadData() {
      var param = this.query;
      param.page = this.page - 1;
      param.size = this.size;
      param.exact = {"type":"0"};
      param.vague = {name:param.name||undefined,safetyhatmac:param.safetyhatmac||undefined};
      param.sort = `date,desc`;
      param.daterange = undefined;
      if(param.timeList && param.timeList.length){
        param.daterange=param.timeList.join(',');
      }
      this.$nextTick(() => {
        //获取安检信息
        HttpReq.truckDispatching.propleGetPerequipment(param).then((res) => {
          if (res.code == 200) {
            this.loading = false;
            this.tableData = res.body.list;
            this.total = res.body.total;
          }
        })
      })
    },
    toAdd() {
      this.title = '新增';
      this.visible = true;
      this.formData = {
        name: '',
        sex: 1,
        phone: '',
        cameraid: '',
        idcard: '',
        safetyhatmac: '',
        color: '1',
        deptid: undefined,
        postid: undefined,
        photo: '',
      };
    },
    toEdit(item) {
      this.title = '编辑';
      this.visible = true;
      this.formData = item;
    },
    toDelete(item) {
      var id = item.id;
      this.$confirm('确认删除该条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((e) => {
        HttpReq.truckDispatching.propleDeletePerequipment({id}).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.loadData();
          }
        })
      })
    },
    download(text, name, suffix) {
      var link = document.createElement('a');
      link.style.display = 'none';
      link.href = URL.createObjectURL(new Blob([text], { type: "application/vnd.ms-excel" }));
      link.setAttribute('download', name + '.' + suffix);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    downloadFile() {
      var loading = this.$loading({
        lock: true,
        text: '请稍后.....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      var param = this.query;
      param.page = this.page - 1;
      param.size = this.size;
      param.vague = {name:param.name||undefined,safetyhatmac:param.safetyhatmac||undefined};
      param.exact = {"type":"0"};
      param.sort = `date,desc`;
      param.daterange = undefined;
      if(param.timeList && param.timeList.length){
        param.daterange=param.timeList.join(',');
      }
      HttpReq.truckDispatching.propleGetPerequipmentOut(param).then((res) => {
        loading.close();
        let d = new Date();
        this.download(res, `人员设备定位_${d.getFullYear()}${('0'+(d.getMonth()+1)).substr(-2)}${('0'+(d.getDate())).substr(-2)}`, 'xlsx')
      })
    },
    cancelForm() {
      this.visible = false;
    },
    tableRowClassName({row, rowIndex}) {
    },
    // 点击搜索
    toSearch() {
      this.page = 1;
      this.loadData();
    },
    // 重置搜索
    clearLimit() {
      this.query = {};
      this.loadData()
    },
    pageChange(e) {
      this.page = e
      this.loadData()
    },
    sizeChange(e) {
      this.page = 1
      this.size = e
      this.loadData()
    },
    //图片上传
    excelImport(event) {
      let file = event.target.files[0];
      let formData = new FormData();
      formData.append("files", file);
      HttpReq.truckDispatching.proplePostPerequipmentUpload(formData).then((res) => {
        this.$notify({
          title: '上传成功！',
          type: 'success',
          duration: 2500
        });
        this.formData.photo = res.body;
      })
    },
    submitForm(validateName, item) {
      this.$refs[validateName].validate(valid => {
        if (valid) {
          item.type = 0;
          item.deptid = this.deptName;
          if (this.title === '新增') {
            HttpReq.truckDispatching.proplePostPerequipment(item).then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.cancelForm();
                this.loadData()
              }
            })
          } else {
            HttpReq.truckDispatching.proplePutPerequipment(item).then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.cancelForm();
                this.loadData()
              }
            })
          }
        }
      });
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scope>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.cell-input {
  //min-width: 220px;
}

.form-cell {
  margin: 0 !important;
  width: 100%;
}

.grid-content {
  //border: 1px solid rgba(100, 100, 100, 0.1);
  padding: 5px 30px;
}
.cell-box {
  min-width: 120px;
}
.cell-box .el-input__inner {
  border: 1px solid rgba(100, 100, 100, 0.1);
}

.cell-box .el-input.is-disabled .el-input__inner {
  border: 1px solid rgba(100, 100, 100, 0.1);
  background: white;
  cursor: text;
}

.cell-box .el-input.is-disabled .el-input__icon {
  cursor: text;
}

.cell-box .el-icon-arrow-up:before {
  content: '';
}

.mapcontainer {
  height: 30vh;
  width: 680px;
  overflow: hidden;
}
</style>
