<template>
  <div id="app">
    <el-container class="container">
      <!--      显示设备信息-->
      <el-main class="el-table">
        <div class="buttons" v-if="user.roleName!='企业用户'">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <el-input v-model="companyName" placeholder="企业名称" />
            </el-form-item>
            <el-form-item>
              <el-input v-model="deviceName" placeholder="设备名称" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search"
              >查询
              </el-button
              >
              <el-button
                type="warning"
                icon="el-icon-refresh-right"
                @click="test"
              >重置
              </el-button
              >
              <el-button
                type="success"
                icon="el-icon-circle-plus"
                @click="AddDevicedialogVisible = true"
              >新增
              </el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="tableData" border>
          <el-table-column label="设备编号" align="center">
            <template slot-scope="scope" align="center">
              <span style="margin-left: 10px">{{ scope.row.deviceId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备名称">
            <template slot-scope="scope" align="center">
              <span style="margin-left: 10px">{{ scope.row.deviceName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备启用日期" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{
                  scope.row.deviceStartDate
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属行业" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{
                  scope.row.industryValue
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="粉尘类别" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.dustName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属企业名称" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.companyName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备位置" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{
                  scope.row.deviceLocation
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-tooltip content="编辑" placement="bottom" effect="light">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="handleEdit(scope.row)"
                  v-show="scope.row.editable!=0"
                />
              </el-tooltip>
              <el-tooltip content="删除" placement="bottom" effect="light">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  v-show="user.roleName!='企业用户'"
                  @click="removeDeviceById(scope.row.deviceId)"
                />
              </el-tooltip>
              <el-tooltip content="设置工作时间" placement="bottom" effect="light">
                <el-button
                  type="success"
                  icon="el-icon-time"
                  circle
                  @click="timeSetting(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="解除编辑锁定" placement="bottom" effect="light">
                <el-button
                  type="warning"
                  icon="el-icon-lock"
                  circle
                  v-show="user.roleName!='企业用户'&&scope.row.editable!='1'"
                  @click="unlockEdit(scope.row.deviceId)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="传感器" align="center">
            <template slot-scope="scope">
              <el-tooltip content="传感器管理" placement="bottom" effect="light">
                <el-button
                  type="primary"
                  icon="el-icon-odometer"
                  circle
                  @click="sensorInfo(scope.row.deviceId)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <div class="block">
          <span class="demonstration" />
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="pagination.num"
            :limit.sync="pagination.size"
            @pagination="test"
          />
        </div>
      </el-main>
    </el-container>
    <!--    //编辑信息-->
    <el-dialog
      title="设备信息编辑"
      :visible.sync="dialogFormVisible"
      width="28%"
      @close="closedFun"
    >
      <el-form :model="form01">
        <el-form-item label="设备编号">
          <el-col :span="11">
            <el-input v-model="form01.deviceId" disabled />
          </el-col>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-col :span="11">
            <el-input v-model="form01.deviceName" />
          </el-col>
        </el-form-item>
        <el-form-item label="设备启用日期">
          <el-col :span="11">
            <!--            <el-input v-model="form01.deviceStartDate" />-->
            <el-date-picker
              v-model="form01.deviceStartDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="行业编码/粉尘类别">
          <span class="demonstration" />
          <el-cascader
            ref="cascader"
            v-model="form01.industryCode"
            placeholder="行业编码/粉尘类别"
            :options="cascader_options"
            filterable
          />
        </el-form-item>
        <el-form-item label="所属企业id" hidden>
          <el-col :span="11">
            <el-input v-model="form01.companyId" />
          </el-col>
        </el-form-item>
        <el-form-item label="所属企业名称">
          <el-col :span="11">
            <el-autocomplete
              v-model="form01.companyName"
              class="inline-input"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              :trigger-on-focus="false"
              @select="handleSelect"
              aria-readonly="true"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="设备位置">
          <el-col :span="11">
            <el-input v-model="form01.deviceLocation" />
          </el-col>
        </el-form-item>
        <el-form-item label="经度">
          <el-col :span="11">
            <el-input v-model="form01.longitude" />
          </el-col>
        </el-form-item>
        <el-form-item label="纬度">
          <el-col :span="11">
            <el-input v-model="form01.latitude" />
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
    <!--    // 新增设备信息-->
    <el-dialog
      title="新增设备信息"
      :visible.sync="AddDevicedialogVisible"
      width="35%"
      @close="closedFun"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="设备编号">
          <el-input v-model="form.deviceId" />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="form.deviceName" />
        </el-form-item>
        <el-form-item label="设备启用日期">
          <el-col>
            <el-date-picker
              v-model="form.deviceStartDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="行业编码/粉尘类别">
          <span class="demonstration" />
          <el-cascader
            ref="cascader"
            v-model="form.industryCode"
            placeholder="行业编码/粉尘类别"
            :options="cascader_options"
            filterable
          />
        </el-form-item>

        <el-form-item label="所属企业名称">
          <el-autocomplete
            v-model="form.companyName"
            class="inline-input"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            :trigger-on-focus="false"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="企业编码" hidden>
          <el-input v-model="form.companyId" />
        </el-form-item>
        <el-form-item label="功能区" hidden>
          <el-input v-model="form.possession" />
        </el-form-item>
        <el-form-item label="设备位置">
          <el-input v-model="form.deviceLocation" />
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="form.longitude" />
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="form.latitude" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
          <el-button @click="AddDevicedialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--    传感器-->
    <el-dialog
      title="传感器"
      :visible.sync="senorDialogVisible"
      width="50%"
      @close="closedFun"
    >
      <div class="buttons" style="width: 95%; margin: auto">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-add"
              @click="handleAddSenor()"
            >新增传感器
            </el-button
            >
          </el-form-item>
        </el-form>
        <el-table :data="SenortableData" border>
          <el-table-column fixed prop="sensorId" label="id" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed
            prop="sensorId"
            label="传感器编号"
            align="center"
          >
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.sensorId }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deviceId" label="所属设备编号" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.deviceId }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sensorName" label="传感器名称" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.sensorName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sensorUnit" label="传感器单位" align="center">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.sensorUnit }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            class-name="small-padding fixed-width"
            style="display: block"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                class="el-icon-edit table-operation"
                style="color: #2db7f5; margin-right: -30px"
                type="text"
                size="small"
                @click="SenorhandleEdit(scope.$index, scope.row)"
              />
              <el-button
                class="el-icon-delete table-operation"
                style="color: #f50; margin-right: -30px"
                type="text"
                size="small"
                @click="removeSenorById(scope.row.id)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <!--    新增传感器-->
    <el-dialog
      title="新增传感器"
      :visible.sync="AddSenordialogVisible"
      width="35%"
      @close="closedFun"
    >
      <el-form ref="form" :model="senorform" label-width="100px">
        <el-form-item label="传感器编号">
          <el-input v-model="senorform.sensorId" />
        </el-form-item>
        <el-form-item label="所属设备编号">
          <el-input v-model="senorform.deviceId" />
        </el-form-item>
        <el-form-item label="传感器名称">
          <el-input v-model="senorform.sensorName" />
        </el-form-item>
        <el-form-item label="传感器单位">
          <el-input v-model="senorform.sensorUnit" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="SenoronSubmit">立即创建</el-button>
          <el-button @click="AddSenordialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--    编辑传感器-->
    <el-dialog
      title="设备信息编辑"
      :visible.sync="EditSenordialogVisible"
      width="28%"
    >
      <el-form :model="senorformEdit">
        <el-form-item label="传感器编号">
          <el-col :span="11">
            <el-input v-model="senorformEdit.sensorId" />
          </el-col>
        </el-form-item>
        <el-form-item label="所属设备编号">
          <el-col :span="11">
            <el-input v-model="senorformEdit.deviceId" />
          </el-col>
        </el-form-item>
        <el-form-item label="传感器名称">
          <el-col :span="11">
            <el-input v-model="senorformEdit.sensorName" />
          </el-col>
        </el-form-item>
        <el-form-item label="传感器单位">
          <el-col :span="11">
            <el-input v-model="senorformEdit.sensorUnit" />
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="EditSenordialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSenorEdit">确 定</el-button>
      </div>
    </el-dialog>
    <!--    工作时间设置-->
    <el-dialog
      title="工作时间设置"
      :visible.sync="timesettingdialogVisible"
      width="28%"
      @close="closedTimePicker"
    >
      <div style="text-align: center">
        <el-time-picker
          is-range
          v-model="workTime"
          value-format="HH:mm:ss"
          range-separator="-"
          style="text-align: center"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        >
        </el-time-picker>
        <div slot="footer" class="dialog-footer" style="margin-top: 25px">
          <el-button @click="timesettingdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setWorkTime">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  data() {
    return {
      companyName: '',
      deviceName: '',
      workTime: [],
      tableData: [],
      pagesize: 8,
      currentPage: 1,
      dialogFormVisible: false,
      form: {},
      form01: {},
      formSenor: {},
      senorform: {},
      senorformEdit: {},
      deviceId: null,
      AddDevicedialogVisible: false,
      AddSenordialogVisible: false,
      EditSenordialogVisible: false,
      timesettingdialogVisible: false,
      senorDialogVisible: false,
      devicethreshold: false,
      total: 0,
      industryCode: [],
      cascader_options: [],
      SenortableData: [],
      params: {},
      pagination: {
        size: 10,
        num: 1
      }
    }
  },
  created() {
    this.test()
    this.jilian()
    // this.Serortest();
  },
  computed: {
    user() {
      return this.$store.state.account.user
    }
  },
  mounted() {
  },
  methods: {
    timeSetting(row) {
      console.log(row)
      this.deviceId = row.deviceId
      if (row.workTimeFrom != null) {
        this.workTime = [row.workTimeFrom, row.workTimeTo]
      }
      this.timesettingdialogVisible = true
    },
    closedTimePicker() {
      this.workTime = ''
    },
    setWorkTime() {
      const arr = this.workTime
      this.$post('/demp/info/deviceInfo/setWorkTime/', {
        from: arr[0],
        to: arr[1],
        id: this.deviceId
      })
        .then(() => {
          this.$message({
            message: this.$t('设置成功!'),
            type: 'success'
          })
          this.timesettingdialogVisible = false
          this.search()
        })
        .catch((r) => {
        })
    },
    unlockEdit(id) {
      this.$post('/demp/info/deviceInfo/unlockEdit/', {
        id: id
      })
        .then(() => {
          this.$message({
            message: this.$t('设置成功!'),
            type: 'success'
          })
          this.timesettingdialogVisible = false
          this.search()
        })
        .catch((r) => {
        })
    },
    // 编辑传感器信息
    submitSenorEdit() {
      this.$put('/demp/info/sensorInfo/', this.senorformEdit)
        .then(() => {
          this.$message({
            message: this.$t('传感器信息修改成功'),
            type: 'success'
          })
          // this.$emit("success");
          this.EditSenordialogVisible = false
          this.sensorInfo(this.deviceId)
          this.senorform = {}
        })
        .catch((r) => {
        })
    },
    // 修改设备信息
    submitEdit() {
      const nodesObj = this.$refs['cascader'].getCheckedNodes(true)
      const newform = this.form01
      newform.industryCode = this.form01.industryCode[0]
      newform.dustType = nodesObj[0].value
      this.$put('/demp/info/deviceInfo/', newform)
        .then(() => {
          this.$message({
            message: this.$t('设备信息修改成功'),
            type: 'success'
          })
          // this.$emit('success')
          this.dialogFormVisible = false
          this.search()
        })
        .catch((r) => {
        })
    },
    closedFun() {
      this.form = {}
      this.form01 = {}
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function(size) {
      this.pagesize = size
      console.log(this.pagesize) // 每页下拉显示数据
      this.test()
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
      console.log(this.currentPage) // 点击第几页
    },
    querySearch(queryString, cb) {
      var list = [{}]
      this.$get(
        'demp/info/companyInfo/getThirdPartyCompanyInfo?companyName=' +
        queryString
        // enterpriseName: this.companyName
      ).then((r) => {
        for (const i of r.data.datas) {
          i.value = i.enterpriseName // 将想要展示的数据作为value
        }
        list = r.data.datas
        cb(list)
      })
    },
    handleSelect(item) {
      this.form.companyId = item.id
      this.form.possession = item.possession
      this.form01.companyId = item.id
      this.form01.possession = item.possession
    },
    onSubmit() {
      const nodesObj = this.$refs['cascader'].getCheckedNodes(true)
      const newform = this.form
      newform.industryCode = this.form.industryCode[0]
      newform.dustType = nodesObj[0].value
      this.$post('/demp/info/deviceInfo', newform)
        .then(() => {
          this.$message({
            message: this.$t('tips.createSuccess'),
            type: 'success'
          })
          // this.$emit("success");
          this.AddDevicedialogVisible = false
          this.search()
        })
        .catch((r) => {
        })
    },
    getCascaderObj(val, opt) {
      return val.map(function(value, index, array) {
        for (var itm of opt) {
          if (itm.id == value) {
            opt = itm.children
            return itm
          }
        }
        return null
      })
    },
    handleAddSenor() {
      this.senorform.deviceId = this.deviceId
      this.AddSenordialogVisible = true
    },
    SenoronSubmit() {
      this.$post('/demp/info/sensorInfo/', this.senorform)
        .then(() => {
          this.$message({
            message: this.$t('tips.createSuccess'),
            type: 'success'
          })
          // this.$emit("success");
          this.AddSenordialogVisible = false
          this.sensorInfo(this.senorform.deviceId)
          this.senorform = {}
        })
        .catch((r) => {
        })
    },
    async removeDeviceById(id) {
      const ids = [id]
      const comfirmResult = await this.$confirm(
        '此操作将永久删除该设备, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => {
        return err
      })
      if (comfirmResult !== 'confirm') {
        return this.$message.info('取消删除设备')
      }
      this.$delete(`demp/info/deviceInfo/${ids}`).then(() => {
        this.$message({
          message: this.$t('tips.deleteSuccess'),
          type: 'success'
        })
        this.search()
      })
    },
    async removeSenorById(id) {
      console.log(id)
      const comfirmResult = await this.$confirm(
        '此操作将永久删除该传感器, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => {
        return err
      })
      if (comfirmResult !== 'confirm') {
        return this.$message.info('取消删除传感器')
      }
      this.$delete('demp/info/sensorInfo', {
        id
      }).then((r) => {
        this.$message({
          message: this.$t('tips.deleteSuccess'),
          type: 'success'
        })
        this.sensorInfo(this.deviceId)
        // console.log(r.data.rows);
      })
    },
    search() {
      this.$get('demp/info/deviceInfo/list', {
        companyName: this.companyName,
        deviceName: this.deviceName,
        pageSize: this.pagination.size,
        pageNum: this.pagination.num
      }).then((r) => {
        this.tableData = r.data.data.rows
        this.total = r.data.data.total
      })
    },

    handleView(index, row) {
      console.log(index, row)
    },
    handleEdit(row) {
      const row_ = JSON.parse(JSON.stringify(row))
      this.form01 = row_
      this.form01.industryCode = [row_.industryCode, row_.dustType]
      // this.form01.industryCode = row.industryCode
      this.dialogFormVisible = true
    },
    SenorhandleEdit(index, row) {
      this.senorformEdit = row
      this.EditSenordialogVisible = true
      console.log(index, row)
    },
    handleThreshold(id) {
      this.form.deviceId = id
      this.devicethreshold = true
    },
    test() {
      this.params.pageSize = this.pagination.size
      this.params.pageNum = this.pagination.num
      this.$get('/demp/info/deviceInfo/list', { ...this.params }).then((r) => {
        this.tableData = r.data.data.rows
        this.total = r.data.data.total
        this.companyName = ''
        this.deviceName = ''
      })
    },
    sensorInfo(deviceId) {
      this.deviceId = deviceId
      this.senorDialogVisible = true
      this.$get('/demp/info/sensorInfo/list', { deviceId }).then((r) => {
        this.SenortableData = r.data.data.rows
        this.totals = r.data.data.total
      })
    },
    jilian() {
      this.$get('demp/info/codeIndustry').then((r) => {
        for (let i = 0; i < r.data.data.length; i++) {
          r.data.data[i].label = r.data.data[i].value
          r.data.data[i].value = r.data.data[i].code
          r.data.data[i].children = []
          this.cascader_options.push(r.data.data[i])
          this.$get(
            'demp/info/codeDustType?industryCode=' +
            this.cascader_options[i].value
          ).then((ri) => {
            for (let j = 0; j < ri.data.data.length; j++) {
              this.cascader_options[i].children.push({
                label: ri.data.data[j].dustName,
                value: ri.data.data[j].code
              })
            }
          })
        }
      })
    }
  }
}
</script>
<style>
h1 {
  text-align: center;
  font-weight: normal;
}
</style>
