<template>
  <div class="app-container" v-if="props.isShow">
    <PageHeader :pageContent="pageContent" @goBack="goBack" />
    <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" label-width="68px" v-show="showSearch">
      <el-form-item label="关键字" prop="keyWord">
        <el-input v-model="queryForm.keyWord" clearable placeholder="请输入关键字" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">搜索</el-button>
        <el-button type="primary" size="small" @click="bindNewIOT">绑定新设备</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="55"
        :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column label="设备类型" prop="iotTypeName" align="center" />
      <el-table-column label="设备编号" prop="iotCode" align="center" />
      <el-table-column label="设备状态" prop="iotStatus" align="center">
        <!-- iotStatus 0 在线 1 掉线 -->
        <template v-slot="{ row }">
          <el-tag v-if="row.iotStatus == 0" type="success">在线</el-tag>
          <el-tag v-else type="danger">掉线</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="绑定日期" prop="bindTime" align="center" />

      <el-table-column label="操作" align="center">
        <template v-slot="{ row }">
          <el-button type="text" size="small" @click="handleUnbind(row)" style="color: red" icon="el-icon-connection">解绑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 绑定设备 -->
    <el-dialog title="绑定设备" :visible.sync="IOTOpen" width="500px" append-to-body :rules="rules">
      <el-form :model="IOTForm" ref="IOTForm" label-width="120px" size="small" :rules="rules">
        <el-form-item label="设备类型" prop="iotType">
          <el-select
            v-model="IOTForm.iotType"
            filterable
            clearable
            placeholder="请选择"
            style="width: 280px"
            @change="changeIotType"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.iotTypeId"
              :label="item.iotTypeName"
              :value="item.iotTypeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号" prop="iotId">
          <el-select v-model="IOTForm.iotId" filterable clearable placeholder="请选择" style="width: 280px">
            <el-option v-for="item in codeOptions" :key="item.iotId" :label="item.iotCode" :value="item.iotId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="IOTOpen = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="loading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PageHeader from '@/components/pageHeader'
import { selectList, bindIot, getTypeList, unbindIot } from '@/api/store/iotManagement'

export default {
  name: 'BindIOT',
  props: {
    props: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    PageHeader,
  },
  data() {
    return {
      loading: false,
      showSearch: true, // 是否显示搜索
      queryForm: {
        keyWord: '',
      },
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      tableData: [],
      pageContent: 'IOT设备查看',
      IOTForm: {
        iotType: '',
        iotId: '',
      },
      IOTOpen: false,
      typeOptions: [], // 设备类型下拉
      codeOptions: [], // 设备编号下拉
      rules: {
        iotType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
        iotId: [{ required: true, message: '请选择设备编号', trigger: 'change' }],
      },
    }
  },
  created() {
    console.log('🚀 ~ created ~ BindIOT', this.props)
    this.getList()
  },
  methods: {
    // 查询
    handleQuery() {
      console.log('🚀 ~ handleQuery ~ 查询:', this.queryForm.keyWord)
      this.getList()
    },
    // 获取列表
    async getList() {
      try {
        const params = {
          maCode: this.props.maCode,
          ...this.queryForm,
          ...this.queryParams,
        }
        console.log('🚀 ~ getList ~ 获取列表', params)

        const res = await getTypeList(params)
        this.tableData = res.rows
        this.total = res.total
      } catch (err) {
        console.log('🚀 ~ getList ~ err:', err)
      }
    },
    // 返回
    goBack() {
      this.$tab.refreshPage()
    },
    // 绑定新设备
    bindNewIOT() {
      console.log('🚀 ~ bindNewIOT ~ 绑定新设备')
      this.IOTOpen = true
      this.getIotType()
      this.$nextTick(() => {
        this.$refs.IOTForm.resetFields()
      })
    },
    // 解绑
    handleUnbind(row) {
      console.log('🚀 ~ handleUnbind ~ 解绑', row)
      try {
        const params = {
          maCode: this.props.maCode,
          typeId: this.props.typeId,
          id: row.id,
          iotId: row.iotId,
        }
        this.$confirm('确定解绑设备吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            await unbindIot(params)
            this.$message.success('解绑成功')
            this.getList()
          })
          .catch(() => {
            this.$message.info('已取消解绑')
          })
      } catch (err) {
        console.log('🚀 ~ handleUnbind ~ err:', err)
      }
    },
    // 提交
    submit() {
      try {
        // 校验
        this.$refs.IOTForm.validate(async valid => {
          if (valid) {
            this.loading = true
            const params = {
              iotTypeId: this.IOTForm.iotType,
              iotId: this.IOTForm.iotId,
              maCode: this.props.maCode,
              typeId: this.props.typeId,
            }
            console.log('🚀 ~ submit ~ 提交绑定设备', params, this.props)
            await bindIot(params)
            this.$message.success('绑定成功')
            this.IOTOpen = false
            this.loading = false
            this.getList()
          } else {
            return false
          }
        })
      } catch (err) {
        console.log('🚀 ~ submit ~ err:', err)
        this.loading = false
      }
    },
    // 获取下拉
    async getIotType() {
      try {
        const res = await selectList()
        this.typeOptions = res.data
      } catch (err) {
        console.log('🚀 ~ getIotType ~ err:', err)
      }
    },
    // 设备类型改变
    async changeIotType(iotTypeId) {
      try {
        this.codeOptions = []
        this.IOTForm.iotId = ''
        if (!iotTypeId) return
        const params = {
          iotTypeId,
        }
        // 获取设备编号
        const res = await selectList(params)
        this.codeOptions = res.data
      } catch (err) {
        console.log('🚀 ~ changeIotType ~ err:', err)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.maCode {
  margin-top: 15px;
  font-size: 18px;
}
</style>
