<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模型名称" prop="deviceModeName">
        <el-input
          v-model="queryParams.deviceModeName"
          placeholder="请输入模型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属场景" prop="sceneId">
        <el-select v-model="queryParams.sceneId" placeholder="请选择"  @input="sceneChange">
          <el-option
            v-for="(scene, index) in scenes"
            :key="index"
            :label="scene.sceneName"
            :value="scene.sceneId"
          ></el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="定位标识" prop="gpsFlag">
        <el-select v-model="queryParams.gpsFlag" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.hw_device_mode_gps_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模型分类" prop="modeClassfication">
        <el-select v-model="queryParams.modeClassfication" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.hw_mode_function_mode_classfication"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </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="['business:deviceMode: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="['business:deviceMode:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:deviceMode:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceModeList" @selection-change="handleSelectionChange">
      <el-table-column label="模型名称" align="center" prop="deviceModeName"/>
      <el-table-column label="所属租户" align="center" prop="tenantName"/>
      <el-table-column label="所属场景" align="center" prop="sceneName"/>
      <el-table-column label="定位标识" align="center" prop="gpsFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hw_device_mode_gps_flag" :value="scope.row.gpsFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="模型分类" align="center" prop="modeClassfication">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hw_mode_function_mode_classfication" :value="scope.row.modeClassfication"/>
        </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="['business:deviceMode:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:deviceMode:remove']"
          >删除
          </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"
    />

  </div>
</template>

<script>
import {listDeviceMode, getDeviceMode, delDeviceMode, addDeviceMode, updateDeviceMode,getScenes} from "@/api/business/deviceMode";
import {getLanguages} from "@/api/basic/language";

export default {
  dicts: ['hw_device_mode_gps_flag', 'hw_mode_function_mode_classfication'],
  name: "DeviceMode",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedHwDeviceModeFunction: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备模型表格数据
      deviceModeList: [],
      // 设备模型功能表格数据
      hwDeviceModeFunctionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      //场景列表
      scenes: [],
      //语言列表
      languages: [],


      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceModeName: null,
        tenantId: null,
        sceneId: null,
        languageCode: null,
        gpsFlag: null,
        deviceModeStatus: null,
        commonFlag: null,
        modeClassfication: null,
        deviceModePic: null,
        dataVerifyLevel: null,
        deviceModeField: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceModeName: [
          {required: true, message: "设备模型名称不能为空", trigger: "blur"}
        ],
        gpsFlag: [
          {required: true, message: "定位标识不能为空", trigger: "blur"}
        ],
        deviceModeStatus: [
          {required: true, message: "设备模型状态不能为空", trigger: "change"}
        ],
        commonFlag: [
          {required: true, message: "是否通用物模型不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    getLanguages().then(response => {
      this.languages = response.data;
    });

    getScenes().then(response => {
      this.scenes = response.data;
    });
  },
  computed: {
    formatRow() {
      return (row) => {
        let languages = this.languages;
        for (let i = 0; i < languages.length; i++) {
          if (languages[i].languageCode === row.languageCode) {
            return languages[i].languageName;
          }
        }
      };
    },
  },

  activated() {
    const time = this.$route.query.t;
    if (time != null && time != this.uniqueId) {
      this.uniqueId = time;
      this.queryParams.pageNum = Number(this.$route.query.pageNum);
      this.getList();
    }
  },

  methods: {
    /** 查询设备模型列表 */
    getList() {
      this.loading = true;
      listDeviceMode(this.queryParams).then(response => {
        this.deviceModeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceModeId: null,
        deviceModeName: null,
        tenantId: null,
        sceneId: null,
        languageCode: null,
        gpsFlag: null,
        deviceModeStatus: null,
        commonFlag: null,
        modeClassfication: null,
        deviceModePic: null,
        dataVerifyLevel: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deviceModeField: null
      };
      this.hwDeviceModeFunctionList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceModeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      const params = {pageNum: this.queryParams.pageNum};
      this.$tab.openPage("添加设备模型", '/deviceMode/mode-add/index', params);

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceModeId = row.deviceModeId || this.ids
      const deviceModeName = row.deviceModeName || this.tableNames[0];
      const params = {pageNum: this.queryParams.pageNum};
      this.$tab.openPage("修改设备模型[" + deviceModeName + "]", '/deviceMode/mode-edit/index/' + deviceModeId, params);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.hwDeviceModeFunctionList = this.hwDeviceModeFunctionList;
          if (this.form.deviceModeId != null) {
            updateDeviceMode(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeviceMode(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceModeName = row.deviceModeName;
      const deviceModeIds = row.deviceModeId || this.ids;
      this.$modal.confirm('是否确认删除设备模型名称为"' + deviceModeName + '"的数据项？').then(function () {
        return delDeviceMode(deviceModeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 设备模型功能序号 */
    rowHwDeviceModeFunctionIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 设备模型功能添加按钮操作 */
    handleAddHwDeviceModeFunction() {
      let obj = {};
      obj.functionMode = "";
      obj.coordinate = "";
      obj.functionName = "";
      obj.functionIdentifier = "";
      obj.functionType = "";
      obj.dataType = "";
      obj.dataDefinition = "";
      obj.functionFormula = "";
      obj.propertyUnit = "";
      obj.displayFlag = "";
      obj.rwFlag = "";
      obj.invokeMethod = "";
      obj.eventType = "";
      obj.remark = "";
      obj.acquisitionFormula = "";
      obj.orderFlag = "";
      obj.deviceRegister = "";
      obj.propertyStep = "";
      obj.propertyField = "";
      this.hwDeviceModeFunctionList.push(obj);
    },
    /** 设备模型功能删除按钮操作 */
    handleDeleteHwDeviceModeFunction() {
      if (this.checkedHwDeviceModeFunction.length == 0) {
        this.$modal.msgError("请先选择要删除的设备模型功能数据");
      } else {
        const hwDeviceModeFunctionList = this.hwDeviceModeFunctionList;
        const checkedHwDeviceModeFunction = this.checkedHwDeviceModeFunction;
        this.hwDeviceModeFunctionList = hwDeviceModeFunctionList.filter(function (item) {
          return checkedHwDeviceModeFunction.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleHwDeviceModeFunctionSelectionChange(selection) {
      this.checkedHwDeviceModeFunction = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/deviceMode/export', {
        ...this.queryParams
      }, `deviceMode_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
