<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="query" :model="deviceSearch" style="display: inline-block;">
        <el-input v-model="deviceSearch.deviceName" placeholder="设备编号" style="width: 200px;" class="filter-item" name="userskk" />
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleSubmit">
          {{ $t('table.search') }}
        </el-button>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-plus" @click="addDevice">
          {{ $t('table.add') }}
        </el-button>
      </el-form>
      <el-button v-if="device != '' " v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('table.export') }}
      </el-button>
      <el-badge v-if="paper > 0" :value="paper" class="item" style="margin-bottom: 8px;">
        <el-button size="small" @click="pucharray">
          <svg-icon class-name="custom-class" icon-class="feizhilou" />废纸篓
        </el-button>
      </el-badge>
    </div>
    <el-tabs v-model="activeName" stretch @tab-click="handleClick">
      <el-tab-pane v-for="item in list" :key="item.tid" :label="item.tname" :tid="item.tid" :name="item.tid==1 ? 'second' : list.tid"></el-tab-pane>
    </el-tabs>
    <el-table :key="tableKey" v-loading="loading" :data="device" border fit highlight-current-rows>
      <el-table-column align="center" label="id" width="80">
        <template slot-scope="scope">
          <span style="color: #409EFF;" @click="deviceinfo(scope.row.id)">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备编号" width="150">
        <template slot-scope="scope">
          <span @click="handleCopy(scope.row.devicenum,$event)">{{ scope.row.devicenum }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备类型" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.tname }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名称" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.usernickname }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="介质状态" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.gas }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备名称" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="浓度" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.nd }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否已删除设备" width="170">
        <template slot-scope="scope">
          <span :style="{color:( scope.row.delete==1 ? '#F56C6C' : '#67C23A' )}">{{ scope.row.delete ==1 ? '设备已被丢弃废纸篓' : '设备正常' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备备注" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.deviceremark }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备详情" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.deviceinfo }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="IP地址" width="170">
        <template slot-scope="scope">
          <span @click="handleCopy(scope.row.ipaddr,$event)">{{ scope.row.ipaddr }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="170">
        <template slot-scope="scope">
          <span>{{ scope.row.deviceaddtime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备实时状态" width="170">
        <template slot-scope="scope">
          <span>
            <el-tag :type=" scope.row.status_name=='正常' ? 'success' : 'warning' " effect="dark">{{ scope.row.status_name }}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="170">
        <template slot-scope="scope">
          <span v-if="scope.row.status_name=='正常' " :style="{color:( scope.row.devicestatus==1 ? '#67C23A' : '#F56C6C' )}">{{ scope.row.devicestatus==1 ? '正常' : '设备错误' }}</span>
          <span v-if="scope.row.status_name!='正常' " :style="{color:( scope.row.status_name=='正常' ? '#67C23A' : '#F56C6C' )}">{{ scope.row.status_name=='正常' ? '正常' : '设备异常' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300px">
        <template slot-scope="scope">
          <el-popover width="160" trigger="click" placement="top">
            <p>此操作,分丢弃废纸篓,和删除设备</p>
            <div style="text-align: right; margin: 0">
              <el-button v-if="scope.row.delete==2" size="mini" type="text" @click="deviceDelete(scope.row.id, 1)">丢弃废纸篓</el-button>
              <el-button type="text" size="mini" @click="deviceDelete(scope.row.id, 2)">删除设备</el-button>
            </div>
            <el-button slot="reference" size="mini" type="danger" :disabled="scope.row.delete == 1 ? true : (scope.row.devicestatus > 1 ? true : false) ">操作</el-button>
          </el-popover>
          <el-button slot="reference" size="mini" type="primary" :disabled="scope.row.delete == 1 ? true : (scope.row.devicestatus > 1 ? true : false)" @click="contactsuser(scope.row.id)">添加联系人</el-button>
          <el-button slot="reference" size="mini" type="primary" :disabled="scope.row.delete == 1 ? true : (scope.row.devicestatus > 1 ? true : false)" @click="updatedevice(scope.row.id)">编辑设备</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="devicelist" />

    <el-dialog :visible.sync="dialogPvVisible" title="设备详情信息" width="50%">
      <el-table :data="devicefistr">
        <el-table-column type="expand">
          <template>
            <el-form v-for="item in deviceDataInfo" :key="item.id" label-position="left" inline class="demo-table-expand">
              <el-form-item label="姓名">
                <span>{{ item.contacts_name }}</span>
              </el-form-item>
              <el-form-item label="手机号">
                <span @click="handleCopyphone(item.contacts_phone,$event)">{{ item.contacts_phone }}</span>
              </el-form-item>
              <el-form-item label="添加用户">
                <span>{{ item.isadmin==1 ? '管理员' : '用户' }}</span>
              </el-form-item>
              <el-form-item label="状态">
                <span :style="{color:( item.isstatus==1 ? '#67C23A' : '#F56C6C' )}">{{ item.isstatus==1 ? '开启' : '禁用' }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="设备UUID" prop="deviceuuid" width="380px"></el-table-column>
        <el-table-column label="设备联系人" prop="devicelinkman"></el-table-column>
        <el-table-column label="设备手机号" prop="devicephone"></el-table-column>
      </el-table>
    </el-dialog>
    <el-drawer title="添加联系人" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
      <el-card class="box-card">
        <el-form ref="contactsdata" :model="contactsdata" label-width="80px">
          <el-form-item label="联系人名称" label-width="92px">
            <el-input v-model="contactsdata.contacts_name" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="联系人手机号" label-width="100px">
            <el-input v-model="contactsdata.contacts_phone" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="人员状态">
            <el-radio-group v-model="contactsdata.isstatus">
              <el-radio label="开启"></el-radio>
              <el-radio label="禁用"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="oncontacts">立即创建</el-button>
            <el-button @click="handleClose">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-drawer>
    <el-drawer
      title="编辑设备"
      :visible.sync="drawerup"
      :direction="directionup"
      :before-close="handleCloseup"
      custom-class="zl-drawer"
    >
      <el-card class="box-card">
        <el-form ref="updevicedata" :model="updevicedata" label-width="80px">
          <el-form-item label="设备编号" label-width="100px">
            <el-input v-model="updevicedata.devicenum" :disabled="disabled" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="用户名称" label-width="100px">
            <el-input v-model="updevicedata.name" :disabled="disabled" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="设备名称" label-width="100px">
            <el-input v-model="updevicedata.username" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="设备坐标" label-width="100px">
            <el-input v-model="updevicedata.devicecoord" style="width:50%"></el-input>
            <el-button type="primary" @click="drawerMap = true">
              拾取坐标
            </el-button>
          </el-form-item>
          <el-form-item label="设备联系人" label-width="100px">
            <el-input v-model="updevicedata.devicelinkman" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="设备手机号" label-width="100px">
            <el-input v-model="updevicedata.devicephone" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="设备备注" label-width="100px">
            <el-input v-model="updevicedata.deviceremark" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item label="设备安装位置" label-width="100px">
            <el-input v-model="updevicedata.deviceinfo" style="width: 80%;"></el-input>
          </el-form-item>
          <el-form-item v-if="checkPermission(['manage isadmin'])" label="选择用户" label-width="100px">
            <el-select v-model="updevicedata.uid" placeholder="请选择用户">
              <el-option v-for="item in addUserDevice" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择分类" label-width="100px">
            <el-select v-model="updevicedata.tid" placeholder="请选择分类">
              <el-option v-for="item in list" :key="item.id" :label="item.tname" :value="item.tid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="介质/单位" label-width="100px">
            <el-select v-model="updevicedata.status" placeholder="请选择介质">
              <el-option v-for="item in gas" :key="item.id" :label="item.gas" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="updevicedata.devicemonad" placeholder="请选择单位">
              <el-option v-for="item in danwei" :key="item.id" :label="item.danwei" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updedata">立即更新</el-button>
            <el-button @click="handleCloseup">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-drawer title="拾取坐标" :visible.sync="drawerMap" :modal="false" :direction="directionMap" :before-close="handleClose" size="70%" :with-header="false">
        <div><CoordinateMap @map-confirm="mapConfirmData" @giveLnglat="getLnglat"></CoordinateMap></div>
      </el-drawer>
    </el-drawer>
  </div>
</template>

<script>
import { deviceTypeList, deviceList, deviceDataInfo, deviceDataSearch, addUserDevice, deviceBasket, deviceDelete, addcontactsuser, postupdatedevice, updedata } from '@/api/device';
import Pagination from '@/components/Pagination'; // 分页
import waves from '@/directive/waves'; // 水波纹效果
import clip from '@/utils/clipboard';
import { parseTime } from '@/utils';
import checkPermission from '@/utils/permission';
import CoordinateMap from '@/components/coordinateMap';
export default {
  name: 'Devicetype',
  components: { Pagination, CoordinateMap },
  directives: { waves },
  data() {
    return {
      drawerMap: false,
      directionMap: 'rtl',
      tableKey: 0,
      downloadLoading: false,
      pvData: [],
      dialogPvVisible: false,
      activeName: 'second',
      list: [],
      danwei: [],
      gas: [],
      loading: true,
      device: [],
      deviceDataInfo: [],
      devicefistr: [],
      addUserDevice: [],
      page: 1,
      deviceSearch: {
        deviceName: '',
        limit: 10,
        page: 1,
      },
      limit: 10,
      type: '',
      total: 0,
      paper: undefined,
      drawer: false,
      disabled: true,
      direction: 'rtl',
      drawerup: false,
      directionup: 'ltr',
      contactsdata: {
        contactsid: undefined,
        contacts_name: undefined,
        contacts_phone: undefined,
        isstatus: undefined,
      },
      updevicedata: {},
      deid: undefined,
    };
  },
  created() {
    this.getList(); // 设备状态
    this.devicelist();
    this.deviceBasket();
  },

  methods: {
    mapConfirmData(text) {
      if (text.state === true) {
        this.updevicedata.devicecoord = text.location;
        this.drawerMap = false;
      }
      if (text.state === false) {
        this.drawerMap = false;
      }
    },
    getLnglat(lnglnt) {
      console.log(lnglnt);
    },
    checkPermission,
    getList() {
      deviceTypeList()
        .then(response => {
          var devicetype = response.data;
          this.list = devicetype['devicetype'];
          this.danwei = devicetype['danwei'];
          this.gas = devicetype['gas'];
        })
        .catch(err => {
          console.log(err);
        });
    },
    devicelist() {
      const limit = this.limit;
      const page = this.page;
      this.loading = true;
      deviceList(page, limit, this.type)
        .then(response => {
          var devicetype = response.data['devicelist'];
          this.device = devicetype;
          this.device.forEach((element, index) => {
            element['index'] = (page - 1) * limit + index + 1;
          });
          this.total = response.data.count;
          this.loading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleClick(tab) {
      this.type = tab.$attrs.tid;
      this.devicelist();
    },
    handleCopy(text, event) {
      clip(text, event);
    },
    // 跳转废纸废纸篓
    pucharray() {
      this.$router.push({ path: '/device/DeviceStutus' });
    },
    deviceinfo(row) {
      this.dialogPvVisible = true;
      this.deviceData(row);
    },
    deviceData(id){
      deviceDataInfo(id)
        .then(response => {
          var deviceData = response.data['devicedata'];
          this.deviceDataInfo = deviceData;
          this.devicefistr = response.data['devicedatainfo'];
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleCopyphone(text, event){
      clip(text, event);
    },
    // 添加设备
    addDevice() {
      this.$router.push({ path: '/device/addDevice' });
    },
    handleDownload() {
      this.downloadLoading = true;
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', '设备编号', '设备名称', '设备类型', '介质状态', '设备备注', '添加时间', '设备实时状态', '是否已删除设备'];
        const filterVal = ['id', 'devicenum', 'username', 'tname', 'gas', 'deviceremark', 'deviceaddtime', 'status_name', 'delete'];
        const data = this.formatJson(filterVal, this.device);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '设备列表',
        });
        this.downloadLoading = false;
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'deviceaddtime') {
          return parseTime(v[j]);
        } else if (j === 'delete') {
          return v[j] === 1 ? '已删除' : '正常';
        } else {
          return v[j];
        }
      }));
    },
    handleSubmit() {
      deviceDataSearch(this.deviceSearch)
        .then(response => {
          if (response.code === 105) {
            this.$message({
              message: response.msg,
              type: 'warning',
            });
            this.devicelist();
          }
          var deviceData = response.data['devicelist'];
          this.device.forEach((element, index) => {
            element['index'] = (this.deviceSearch.page - 1) * this.deviceSearch.limit + index + 1;
          });
          this.device = deviceData;
          this.total = response.data.count;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 获取废纸篓数量
    deviceBasket() {
      deviceBasket()
        .then(response => {
          this.paper = response.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    contactsuser(id) {
      const deviceid = id;
      this.drawer = true; // 打开抽屉
      this.contactsdata.contactsid = deviceid;
    },
    handleClose(done) {
      this.drawer = false; // 关闭抽屉
      this.contactsdata.contacts_name = undefined;
      this.contactsdata.contacts_phone = undefined;
      this.contactsdata.contactsid = undefined;
      this.contactsdata.isstatus = undefined;
    },
    oncontacts() {
      if (this.contactsdata.contacts_name === undefined) {
        this.$message({
          message: '联系人名称不能为空',
          type: 'warning',
        });
      } else if (this.contactsdata.contacts_phone === undefined) {
        this.$message({
          message: '联系人手机号不能为空',
          type: 'warning',
        });
      } else if (this.contactsdata.isstatus === undefined) {
        this.$message({
          message: '请选择用户状态',
          type: 'warning',
        });
      } else {
        this.contactsdata.isstatus === '开启' ? this.contactsdata.isstatus = 1 : this.contactsdata.isstatus = 2;
        addcontactsuser(this.contactsdata)
          .then(response => {
            this.$message({
              message: '添加成功',
              type: 'success',
            });
            this.handleClose();
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    deviceDelete(id, type) {
      this.$confirm('是否将设备丢弃', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deviceDelete(id, type)
          .then(response => {
            this.getList();
            this.devicelist();
            this.deviceBasket();
          })
          .catch(err => {
            console.log(err);
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消',
        });
      });
    },
    // 编辑设备
    updatedevice(id) {
      const deviceid = id;
      this.drawerup = true; // 打开抽屉
      this.postupdatedevice(deviceid);
      this.addUserDevices();
      this.deid = deviceid;
    },
    // 关闭
    handleCloseup(done) {
      this.drawerup = false; // 关闭抽屉
      this.deid = undefined;
    },
    // 请求数据
    postupdatedevice(id) {
      postupdatedevice(id)
        .then(response => {
          this.updevicedata = response.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    updedata() {
      this.updevicedata.deid = this.deid;
      updedata(this.updevicedata)
        .then(response => {
          this.handleCloseup();
          this.devicelist();
        })
        .catch(err => {
          console.log(err);
        });
    },
    addUserDevices() {
      addUserDevice()
        .then(response => {
          this.addUserDevice = response.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    accuracy() {
      window.open('latlge.html');
    },
  },
};
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .zl-drawer .el-drawer__body {
    overflow-y: auto !important;
  }
</style>
