<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="tenantId">
        <el-input
          v-model="queryParams.tenantId"
          placeholder="请输入租户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属场景" prop="sceneId">
        <el-input
          v-model="queryParams.sceneId"
          placeholder="请输入所属场景"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="语言" prop="languageCode">
        <el-select v-model="queryParams.languageCode" placeholder="请选择">
          <el-option
            v-for="(language, index) in languages"
            :key="index"
            :label="language.languageName"
            :value="language.languageCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="定位标识" prop="gpsFlag">
        <el-input
          v-model="queryParams.gpsFlag"
          placeholder="请输入定位标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通用标识" prop="commonFlag">
        <el-input
          v-model="queryParams.commonFlag"
          placeholder="请输入是否通用物模型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型分类" prop="modeClassfication">
        <el-input
          v-model="queryParams.modeClassfication"
          placeholder="请输入模型分类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:deviceMode: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="['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="tenantId"/>
      <el-table-column label="所属场景" align="center" prop="sceneId"/>
      <el-table-column label="语言" align="center" prop="languageCode" :formatter="formatRow"/>
      <el-table-column label="定位标识" align="center" prop="gpsFlag"/>
      <el-table-column label="是否通用物模型" align="center" prop="commonFlag"/>
      <el-table-column label="模型分类" align="center" prop="modeClassfication"/>
      <el-table-column label="设备模型图片地址" align="center" prop="deviceModePic"/>
      <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"
    />

    <!-- 添加或修改设备模型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备模型名称" prop="deviceModeName">
          <el-input v-model="form.deviceModeName" placeholder="请输入设备模型名称" />
        </el-form-item>
        <el-form-item label="租户ID，关联hw_tenant的tenant_id" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入租户ID，关联hw_tenant的tenant_id" />
        </el-form-item>
        <el-form-item label="所属场景，关联hw_scene表的scene_id字段" prop="sceneId">
          <el-input v-model="form.sceneId" placeholder="请输入所属场景，关联hw_scene表的scene_id字段" />
        </el-form-item>
        <el-form-item label="语言code,关联表hw_language的language_code字段" prop="languageCode">
          <el-input v-model="form.languageCode" placeholder="请输入语言code,关联表hw_language的language_code字段" />
        </el-form-item>
        <el-form-item label="定位标识" prop="gpsFlag">
          <el-input v-model="form.gpsFlag" placeholder="请输入定位标识" />
        </el-form-item>
        <el-form-item label="是否通用物模型" prop="commonFlag">
          <el-input v-model="form.commonFlag" placeholder="请输入是否通用物模型" />
        </el-form-item>
        <el-form-item label="模型分类" prop="modeClassfication">
          <el-input v-model="form.modeClassfication" placeholder="请输入模型分类" />
        </el-form-item>
        <el-form-item label="设备模型图片地址" prop="deviceModePic">
          <el-input v-model="form.deviceModePic" placeholder="请输入设备模型图片地址" />
        </el-form-item>
        <el-form-item label="预留字段，数据校验级别" prop="dataVerifyLevel">
          <el-input v-model="form.dataVerifyLevel" placeholder="请输入预留字段，数据校验级别" />
        </el-form-item>
        <el-form-item label="场景描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="预留字段" prop="deviceModeField">
          <el-input v-model="form.deviceModeField" placeholder="请输入预留字段" />
        </el-form-item>
        <el-divider content-position="center">设备模型功能信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddHwDeviceModeFunction">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteHwDeviceModeFunction">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="hwDeviceModeFunctionList" :row-class-name="rowHwDeviceModeFunctionIndex" @selection-change="handleHwDeviceModeFunctionSelectionChange" ref="hwDeviceModeFunction">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="功能模式" prop="functionMode" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.functionMode" placeholder="请输入功能模式" />
            </template>
          </el-table-column>
          <el-table-column label="坐标标识" prop="coordinate" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.coordinate" placeholder="请输入坐标标识" />
            </template>
          </el-table-column>
          <el-table-column label="功能名称" prop="functionName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.functionName" placeholder="请输入功能名称" />
            </template>
          </el-table-column>
          <el-table-column label="标识符" prop="functionIdentifier" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.functionIdentifier" placeholder="请输入标识符" />
            </template>
          </el-table-column>
          <el-table-column label="功能类型(1、直采变量 2、手录变量 3、运算性变量)" prop="functionType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.functionType" placeholder="请选择功能类型(1、直采变量 2、手录变量 3、运算性变量)">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数据类型" prop="dataType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.dataType" placeholder="请选择数据类型">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数据定义，按json保存，示例如下：
            1、取值范围：{'minValue':1,'maxValue':100},
            2、枚举型：
            {'1':'成功','2','失败','3','提示}
            3、bool型：
            {'0':'关','1','开'}
            4、Text型：
            {'dataLength'：1024}
            5、String类型" prop="dataDefinition" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataDefinition" placeholder="请输入数据定义，按json保存，示例如下：
            1、取值范围：{'minValue':1,'maxValue':100},
            2、枚举型：
            {'1':'成功','2','失败','3','提示}
            3、bool型：
            {'0':'关','1','开'}
            4、Text型：
            {'dataLength'：1024}
            5、String类型" />
            </template>
          </el-table-column>
          <el-table-column label="运算性变量公式" prop="functionFormula" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.functionFormula" placeholder="请输入运算性变量公式" />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="propertyUnit" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.propertyUnit" placeholder="请输入单位" />
            </template>
          </el-table-column>
          <el-table-column label="显示标识" prop="displayFlag" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.displayFlag" placeholder="请输入显示标识" />
            </template>
          </el-table-column>
          <el-table-column label="读写标识" prop="rwFlag" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.rwFlag" placeholder="请输入读写标识" />
            </template>
          </el-table-column>
          <el-table-column label="调用方式" prop="invokeMethod" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.invokeMethod" placeholder="请输入调用方式" />
            </template>
          </el-table-column>
          <el-table-column label="事件类型" prop="eventType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.eventType" placeholder="请选择事件类型">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="预留字段，采集公式：设备上行数据经采集公式计算后显示，公式中的%s为占位符，是固定字段。
            如：
            加：%s+10
            减：%s-10
            乘：%s10
            除：%s/10
            余数：%s%10" prop="acquisitionFormula" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.acquisitionFormula" placeholder="请输入预留字段，采集公式：设备上行数据经采集公式计算后显示，公式中的%s为占位符，是固定字段。
            如：
            加：%s+10
            减：%s-10
            乘：%s10
            除：%s/10
            余数：%s%10" />
            </template>
          </el-table-column>
          <el-table-column label="预留字段，顺序" prop="orderFlag" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.orderFlag" placeholder="请输入预留字段，顺序" />
            </template>
          </el-table-column>
          <el-table-column label="预留字段，寄存器" prop="deviceRegister" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.deviceRegister" placeholder="请输入预留字段，寄存器" />
            </template>
          </el-table-column>
          <el-table-column label="预留字段，步长" prop="propertyStep" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.propertyStep" placeholder="请输入预留字段，步长" />
            </template>
          </el-table-column>
          <el-table-column label="预留字段" prop="propertyField" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.propertyField" placeholder="请输入预留字段" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

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

export default {
  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;
          }
        }
      };
    },
  },


  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};


      getDeviceMode(deviceModeId).then(response => {
        // this.form = response.data;
        // this.hwDeviceModeFunctionList = response.data.hwDeviceModeFunctionList;
        // this.open = true;
        // this.title = "修改设备模型";
        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>
