<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备厂商" prop="factoryName">
        <el-select
          v-model="queryParams.factoryName"
          placeholder="请选择设备厂商"
          clearable
        >
          <el-option
            v-for="dict in dict.type.iot_factory_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:iotConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:towerDataWarning:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:iotConfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:iotConfig:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-refresh"
          size="mini"
          :disabled="single"
          @click="handleRefreshPoint"
          v-hasPermi="['manage:iotConfig:edit']"
          >刷新设备</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-alert title="配置说明" type="success">
      <template slot="default">
        <div>1、新增的配置自动刷新设备。</div>
        <div>2、修改配置后手动刷新设备或等待设备心跳后更新点位。</div>
        <div>3、初始化失败的配置，常见原因为通信账号、通信密码不匹配！</div>
      </template>
    </el-alert>
    <el-table
      v-loading="loading"
      :data="iotConfigList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="总包单位" align="center" prop="comName" />
      <el-table-column label="通信账号" align="center" prop="signalName" />
      <el-table-column label="通信密码" align="center" prop="signalCode" />
      <el-table-column label="设备厂商" align="center" prop="factoryName" width="120">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.iot_factory_type"
            :value="scope.row.factoryName"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="是否启用"
        align="center"
        prop="isDel"
        width="120"
        v-hasPermi="['manage:iotConfig:edit']"
      >
        <template slot-scope="scope">
          <el-tooltip
            v-if="scope.row.isDel != '99'"
            :content="scope.row.isDel == '0' ? '启用' : '停用'"
            placement="top"
          >
            <el-switch
              active-value="0"
              inactive-value="1"
              v-model="scope.row.isDel"
              @change="setStatus($event, scope.row)"
            />
          </el-tooltip>
          <el-button v-else type="danger" link disabled>初始化失败</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="是否启用"
        align="center"
        prop="isDel"
        width="120"
        v-notHasPermi="['manage:iotConfig:edit']"
      >
        <template slot-scope="scope">
          <dict-tag
            v-if="scope.row.isDel != '99'"
            :options="dict.type.sys_normal_disable"
            :value="scope.row.isDel"
          />
          <el-button v-else type="danger" link disabled>初始化失败</el-button>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:iotConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:iotConfig:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改配电箱配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="iotConfigRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择所属项目" style="width:100%">
            <el-option
              v-for="(item, index) in projectOptions"
              :key="index"
              :label="item.projectName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通信账号" prop="signalName">
          <el-input
            v-model="form.signalName"
            placeholder="请输入通信账号"
            maxlength="64"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="通信密码" prop="signalCode">
          <el-input
            v-model="form.signalCode"
            placeholder="请输入通信密码"
            maxlength="64"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="设备厂商" prop="factoryName">
          <el-select
            v-model="form.factoryName"
            placeholder="请选择设备厂商"
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.iot_factory_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listIotConfig,
  getIotConfig,
  delIotConfig,
  addIotConfig,
  updateIotConfig,
  findIotConfigPoint,
} from "@/api/device/iotConfig";

export default {
  name: "IotConfig",
  dicts: ["sys_normal_disable", "iot_factory_type"],
  data() {
    return {
      iotConfigList: [],
      open: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      form: {
        id: null,
        comId: null,
        projectId: null,
        signalName: null,
        signalCode: null,
        factoryName: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        comId: null,
        projectId: null,
        signalName: null,
        signalCode: null,
        factoryName: null,
        isDel: null,
      },
      rules: {
        projectId: [{ required: true, message: "所属项目不能为空", trigger: "change" }],
        signalName: [{ required: true, message: "通信账号不能为空", trigger: "blur" }],
        signalCode: [{ required: true, message: "通信密码不能为空", trigger: "blur" }],
        factoryName: [{ required: true, message: "设备厂商不能为空", trigger: "change" }],
      },
      projectOptions: [],
    };
  },
  created() {
    this.$api.publics.getMyProjectList({}).then((response) => {
      this.projectOptions = response.rows;
    });
    this.getList();
  },
  methods: {
    /** 查询配电箱配置列表 */
    getList() {
      this.loading = true;
      listIotConfig(this.queryParams).then((response) => {
        this.iotConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        comId: null,
        projectId: null,
        signalName: null,
        signalCode: null,
        factoryName: null,
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.$refs.iotConfigRef && this.$refs.iotConfigRef.resetFields();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryRef && this.$refs.queryRef.resetFields();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加配电箱配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const _id = row.id || this.ids;
      getIotConfig(_id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改配电箱配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.iotConfigRef.validate((valid) => {
        if (valid) {
          if (this.form.id !== null) {
            updateIotConfig(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIotConfig(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getIotConfigPoint(response.data.id);
            });
          }
        }
      });
    },
    /** 状态滑块控制 */
    setStatus(val, row) {
      this.$modal
        .confirm(`是否确认${val === "0" ? "启用" : "停用"}当前数据项？`)
        .then(() => {
          const _data = { id: row.id, isDel: val };
          return updateIotConfig(_data);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("修改成功");
        })
        .catch(() => {
          // 取消时恢复原始开关状态
          if (val === "0") {
            row.isDel = "1";
          } else {
            row.isDel = "0";
          }
        });
    },
    /** 配电箱配的点位 */
    getIotConfigPoint(id) {
      findIotConfigPoint(id).then((res) => {
        this.getList();
        if (res.code === 200) {
          this.$modal.msgSuccess("初始化配置点位成功！！！");
        }
      });
    },
    /** 刷新点位操作 */
    handleRefreshPoint() {
      this.getIotConfigPoint(this.ids);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const _ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除配电箱配置编号为"' + _ids + '"的数据项？')
        .then(() => {
          return delIotConfig(_ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "manage/iotConfig/export",
        {
          ...this.queryParams,
        },
        `iotConfig_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
