<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="设备模型ID，关联表hw_device_mode的device_mode_id" prop="deviceModeId">
        <el-input
          v-model="queryParams.deviceModeId"
          placeholder="请输入设备模型ID，关联表hw_device_mode的device_mode_id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="功能模式" prop="functionMode">
        <el-input
          v-model="queryParams.functionMode"
          placeholder="请输入功能模式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="坐标标识" prop="coordinate">
        <el-input
          v-model="queryParams.coordinate"
          placeholder="请输入坐标标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="功能名称" prop="functionName">
        <el-input
          v-model="queryParams.functionName"
          placeholder="请输入功能名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标识符" prop="functionIdentifier">
        <el-input
          v-model="queryParams.functionIdentifier"
          placeholder="请输入标识符"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据定义，按json保存，示例如下：
            1、取值范围：{'minValue':1,'maxValue':100},
            2、枚举型：
            {'1':'成功','2','失败','3','提示}
            3、bool型：
            {'0':'关','1','开'}
            4、Text型：
            {'dataLength'：1024}
            5、String类型" prop="dataDefinition">
        <el-input
          v-model="queryParams.dataDefinition"
          placeholder="请输入数据定义，按json保存，示例如下：
            1、取值范围：{'minValue':1,'maxValue':100},
            2、枚举型：
            {'1':'成功','2','失败','3','提示}
            3、bool型：
            {'0':'关','1','开'}
            4、Text型：
            {'dataLength'：1024}
            5、String类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="运算性变量公式" prop="functionFormula">
        <el-input
          v-model="queryParams.functionFormula"
          placeholder="请输入运算性变量公式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位" prop="propertyUnit">
        <el-input
          v-model="queryParams.propertyUnit"
          placeholder="请输入单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="显示标识" prop="displayFlag">
        <el-input
          v-model="queryParams.displayFlag"
          placeholder="请输入显示标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="读写标识" prop="rwFlag">
        <el-input
          v-model="queryParams.rwFlag"
          placeholder="请输入读写标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="调用方式" prop="invokeMethod">
        <el-input
          v-model="queryParams.invokeMethod"
          placeholder="请输入调用方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预留字段，采集公式：设备上行数据经采集公式计算后显示，公式中的%s为占位符，是固定字段。
            如：
            加：%s+10
            减：%s-10
            乘：%s10
            除：%s/10
            余数：%s%10" prop="acquisitionFormula">
        <el-input
          v-model="queryParams.acquisitionFormula"
          placeholder="请输入预留字段，采集公式：设备上行数据经采集公式计算后显示，公式中的%s为占位符，是固定字段。
            如：
            加：%s+10
            减：%s-10
            乘：%s10
            除：%s/10
            余数：%s%10"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预留字段，顺序" prop="orderFlag">
        <el-input
          v-model="queryParams.orderFlag"
          placeholder="请输入预留字段，顺序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预留字段，寄存器" prop="deviceRegister">
        <el-input
          v-model="queryParams.deviceRegister"
          placeholder="请输入预留字段，寄存器"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预留字段，步长" prop="propertyStep">
        <el-input
          v-model="queryParams.propertyStep"
          placeholder="请输入预留字段，步长"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预留字段" prop="propertyField">
        <el-input
          v-model="queryParams.propertyField"
          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:deviceModeFunction: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:deviceModeFunction: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:deviceModeFunction: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:deviceModeFunction:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceModeFunctionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备模型功能ID" align="center" prop="modeFunctionId" />
      <el-table-column label="设备模型ID，关联表hw_device_mode的device_mode_id" align="center" prop="deviceModeId" />
      <el-table-column label="功能模式" align="center" prop="functionMode" />
      <el-table-column label="坐标标识" align="center" prop="coordinate" />
      <el-table-column label="功能名称" align="center" prop="functionName" />
      <el-table-column label="标识符" align="center" prop="functionIdentifier" />
      <el-table-column label="功能类型(1、直采变量 2、手录变量 3、运算性变量)" align="center" prop="functionType" />
      <el-table-column label="数据类型" align="center" prop="dataType" />
      <el-table-column label="数据定义，按json保存，示例如下：
            1、取值范围：{'minValue':1,'maxValue':100},
            2、枚举型：
            {'1':'成功','2','失败','3','提示}
            3、bool型：
            {'0':'关','1','开'}
            4、Text型：
            {'dataLength'：1024}
            5、String类型" align="center" prop="dataDefinition" />
      <el-table-column label="运算性变量公式" align="center" prop="functionFormula" />
      <el-table-column label="单位" align="center" prop="propertyUnit" />
      <el-table-column label="显示标识" align="center" prop="displayFlag" />
      <el-table-column label="读写标识" align="center" prop="rwFlag" />
      <el-table-column label="调用方式" align="center" prop="invokeMethod" />
      <el-table-column label="事件类型" align="center" prop="eventType" />
      <el-table-column label="描述" align="center" prop="remark" />
      <el-table-column label="预留字段，采集公式：设备上行数据经采集公式计算后显示，公式中的%s为占位符，是固定字段。
            如：
            加：%s+10
            减：%s-10
            乘：%s10
            除：%s/10
            余数：%s%10" align="center" prop="acquisitionFormula" />
      <el-table-column label="预留字段，顺序" align="center" prop="orderFlag" />
      <el-table-column label="预留字段，寄存器" align="center" prop="deviceRegister" />
      <el-table-column label="预留字段，步长" align="center" prop="propertyStep" />
      <el-table-column label="预留字段" align="center" prop="propertyField" />
      <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:deviceModeFunction:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:deviceModeFunction: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="设备模型ID，关联表hw_device_mode的device_mode_id" prop="deviceModeId">
          <el-input v-model="form.deviceModeId" placeholder="请输入设备模型ID，关联表hw_device_mode的device_mode_id" />
        </el-form-item>
        <el-form-item label="功能模式" prop="functionMode">
          <el-input v-model="form.functionMode" placeholder="请输入功能模式" />
        </el-form-item>
        <el-form-item label="坐标标识" prop="coordinate">
          <el-input v-model="form.coordinate" placeholder="请输入坐标标识" />
        </el-form-item>
        <el-form-item label="功能名称" prop="functionName">
          <el-input v-model="form.functionName" placeholder="请输入功能名称" />
        </el-form-item>
        <el-form-item label="标识符" prop="functionIdentifier">
          <el-input v-model="form.functionIdentifier" placeholder="请输入标识符" />
        </el-form-item>
        <el-form-item label="数据定义，按json保存，示例如下：
            1、取值范围：{'minValue':1,'maxValue':100},
            2、枚举型：
            {'1':'成功','2','失败','3','提示}
            3、bool型：
            {'0':'关','1','开'}
            4、Text型：
            {'dataLength'：1024}
            5、String类型" prop="dataDefinition">
          <el-input v-model="form.dataDefinition" placeholder="请输入数据定义，按json保存，示例如下：
            1、取值范围：{'minValue':1,'maxValue':100},
            2、枚举型：
            {'1':'成功','2','失败','3','提示}
            3、bool型：
            {'0':'关','1','开'}
            4、Text型：
            {'dataLength'：1024}
            5、String类型" />
        </el-form-item>
        <el-form-item label="运算性变量公式" prop="functionFormula">
          <el-input v-model="form.functionFormula" placeholder="请输入运算性变量公式" />
        </el-form-item>
        <el-form-item label="单位" prop="propertyUnit">
          <el-input v-model="form.propertyUnit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="显示标识" prop="displayFlag">
          <el-input v-model="form.displayFlag" placeholder="请输入显示标识" />
        </el-form-item>
        <el-form-item label="读写标识" prop="rwFlag">
          <el-input v-model="form.rwFlag" placeholder="请输入读写标识" />
        </el-form-item>
        <el-form-item label="调用方式" prop="invokeMethod">
          <el-input v-model="form.invokeMethod" 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="预留字段，采集公式：设备上行数据经采集公式计算后显示，公式中的%s为占位符，是固定字段。
            如：
            加：%s+10
            减：%s-10
            乘：%s10
            除：%s/10
            余数：%s%10" prop="acquisitionFormula">
          <el-input v-model="form.acquisitionFormula" placeholder="请输入预留字段，采集公式：设备上行数据经采集公式计算后显示，公式中的%s为占位符，是固定字段。
            如：
            加：%s+10
            减：%s-10
            乘：%s10
            除：%s/10
            余数：%s%10" />
        </el-form-item>
        <el-form-item label="预留字段，顺序" prop="orderFlag">
          <el-input v-model="form.orderFlag" placeholder="请输入预留字段，顺序" />
        </el-form-item>
        <el-form-item label="预留字段，寄存器" prop="deviceRegister">
          <el-input v-model="form.deviceRegister" placeholder="请输入预留字段，寄存器" />
        </el-form-item>
        <el-form-item label="预留字段，步长" prop="propertyStep">
          <el-input v-model="form.propertyStep" placeholder="请输入预留字段，步长" />
        </el-form-item>
        <el-form-item label="预留字段" prop="propertyField">
          <el-input v-model="form.propertyField" placeholder="请输入预留字段" />
        </el-form-item>

        <el-form-item label="布尔值" prop="boolFalse" v-show="inputParameterForm.dataType == '8'">
          0——
          <el-input v-model="inputParameterForm.boolFalse" placeholder="请输入值" style="width:150px;"/>
        </el-form-item>
        <el-form-item label="" prop="boolTrue" v-show="inputParameterForm.dataType == '8'">
          1——
          <el-input v-model="inputParameterForm.boolTrue" placeholder="请输入值" style="width:150px;"/>
        </el-form-item>

        <el-form-item label="长度" prop="dataDefinition" v-show="inputParameterForm.dataType == '10'">
          <el-input-number v-model="inputParameterForm.dataDefinition" placeholder="请输入最大长度" :max="1000" style="width:150px;"/>
        </el-form-item>

      </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 { listDeviceModeFunction, getDeviceModeFunction, delDeviceModeFunction, addDeviceModeFunction, updateDeviceModeFunction } from "@/api/business/deviceModeFunction";

export default {
  name: "DeviceModeFunction",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备模型功能表格数据
      deviceModeFunctionList: [],
      // 弹出层标题
      title: "",

      // 表单参数
      modeFunctionForm: {},
      // 是否显示弹出层
      open: false,

      deviceModeId: '',

      servicesData: [],

      inputParametersData: [],
      inputParameterTitle: "",
      inputParameterOpen: false,
      inputParameterForm: {},

      outputParametersData: [],

      modeFunctionRules: {
        functionType: [
          {required: true, message: "请选择功能类型", trigger: "blur"},
        ],
        functionName: [
          { required: true, message: "功能名称不能为空", trigger: "blur" }
        ],
        functionIdentifier: [
          { required: true, message: "标识符不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备模型功能列表 */
    getList() {
      this.loading = true;
      listDeviceModeFunction(this.queryParams).then(response => {
        this.deviceModeFunctionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.open = true;
      this.title = "添加设备模型服务";
    },
    // 表单重置
    reset() {
      this.form = {
        modeFunctionId: null,
        deviceModeId: null,
        functionMode: null,
        coordinate: null,
        functionName: null,
        functionIdentifier: null,
        functionType: null,
        dataType: null,
        dataDefinition: null,
        functionFormula: null,
        propertyUnit: null,
        displayFlag: null,
        rwFlag: null,
        invokeMethod: null,
        eventType: null,
        remark: null,
        acquisitionFormula: null,
        orderFlag: null,
        deviceRegister: null,
        propertyStep: null,
        propertyField: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    handleUpdateService(row) {
      // this.reset();
      this.modeFunctionForm = row;
      if (row.modeFunctionId !== undefined) {
        getDeviceModeParameters(row.modeFunctionId).then(res => {
          if (res.data !== undefined) {
            this.modeFunctionForm.inputParameters = (res.data)["1"];
            this.modeFunctionForm.outputParameters = (res.data)["2"];
          }

          if (this.modeFunctionForm.inputParameters === undefined) {
            this.modeFunctionForm.inputParameters = [];
          }

          if (this.modeFunctionForm.outputParameters === undefined) {
            this.modeFunctionForm.outputParameters = [];
          }

          // alert(JSON.stringify(this.modeFunctionForm))
        });
      }
      this.open = true;
      this.title = "添加设备模型功能";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const modeFunctionId = row.modeFunctionId || this.ids
      getDeviceModeFunction(modeFunctionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备模型功能";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          /** 设备模型添加后在list中添加 */
          if (this.deviceModeId && this.deviceModeId !== '') {
            let modeFunctionId = this.modeFunctionForm.modeFunctionId;
            this.modeFunctionForm.deviceModeId = this.deviceModeId;
            if (modeFunctionId !== undefined) {
              updateDeviceModeFunction(this.modeFunctionForm).then(res => {
                this.$modal.msgSuccess(res.msg);
                if (res.code === 200) {
                  this.open = false;
                }
              });
            } else {
              addDeviceModeFunction(this.modeFunctionForm).then(res => {
                this.$modal.msgSuccess(res.msg);
                if (res.code === 200) {
                  this.open = false;
                  this.modeFunctionForm.modeFunctionId = res.data;
                  this.pushData();
                }
              });
            }
          } else {
            addDeviceModeFunction(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },

    pushData() {
      let index = this.servicesData.indexOf(this.modeFunctionForm)
      if (index < 0) {
        this.servicesData.push(this.modeFunctionForm)
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 参数弹窗取消按钮
    cancelParameter() {
      this.inputParameterOpen = false;
      this.resetInputParameter();
    },

    // 参数表单重置
    resetInputParameter(parameterType) {
      this.inputParameterForm = {
        parameterType: parameterType,
        parameterName: null,
        parameterIdentifier: null,
        dataType: null,
        dataDefinition: null,
        minvalue: '',
        maxValue: '',
        boolFalse: '',
        boolTrue: ''
      };
      //this.resetForm("inputParameterForm");
    },

    handleAddInputParameter() {
      this.resetInputParameter(1);
      this.inputParameterOpen = true;
      this.inputParameterTitle = "添加设备模型服务输入参数";
    },

    handleUpdateInputParameter(row) {
      this.convertParameterDefinition(row);
      this.inputParameterForm = row;
      this.inputParameterOpen = true;
      this.inputParameterTitle = "添加设备模型服务输入参数";
    },

    convertParameterDefinition(row) {
      if (parseInt(row.dataType) === 8) {
        let dataDefinitionJson = JSON.parse(row.dataDefinition)
        alert(row.dataDefinition)
        row.boolFalse = dataDefinitionJson["0"];
        row.boolTrue = dataDefinitionJson["1"];
      }
    },

    handleDeleteInputParameter(row) {
      // this.reset();
      // const deviceModeIds = row.deviceModeId || this.ids;
      // this.$modal.confirm('是否确认删除设备模型编号为"' + deviceModeIds + '"的数据项？').then(function() {
      //   return delDeviceMode(deviceModeIds);
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("删除成功");
      // }).catch(() => {});


      // const inputParameters = this.modeFunctionForm.inputParameters;
      // alert(this.modeFunctionForm.inputParameters.indexOf(row))
      // alert(inputParameters.indexOf(row))
      this.modeFunctionForm.inputParameters.splice(this.modeFunctionForm.inputParameters.indexOf(row), 1);

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modeFunctionIds = row.modeFunctionId || this.ids;
      this.$modal.confirm('是否确认删除设备模型功能编号为"' + modeFunctionIds + '"的数据项？').then(function() {
        return delDeviceModeFunction(modeFunctionIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    handleUpdateOutputParameter(row) {
      this.convertParameterDefinition(row);
      this.inputParameterForm = row;
      this.inputParameterOpen = true;
      this.inputParameterTitle = "添加设备模型服务输出参数";
    },

    handleDeleteOutputParameter(row) {
      // this.reset();
      this.modeFunctionForm.outputParameters.splice(this.modeFunctionForm.outputParameters.indexOf(row), 1);
    },

    submitInputParameterForm() {
      this.$refs['inputParameterForm'].validate(valid => {
        if (valid) {
          /** 设备模型添加后在list中添加 */
          //alert(this.minValue+"--"+this.maxValue)
          if (this.inputParameterForm.dataType === "8") {
            let boolFalse = this.inputParameterForm.boolFalse;
            let boolTrue = this.inputParameterForm.boolTrue;
            if (boolFalse === '' || boolTrue === '') {
              this.$modal.msgError("请输入布尔值");
              return;
            } else {
              this.inputParameterForm.dataDefinition = '{"0":"' + boolFalse + '","1":"' + boolTrue + '"}';
            }
          }

          this.inputParameterOpen = false;
          let inputParameters = this.inputParameterForm;
          if (parseInt(this.inputParameterForm.parameterType) === 1) {
            let index = this.modeFunctionForm.inputParameters.indexOf(inputParameters)
            if (index < 0) {
              this.modeFunctionForm.inputParameters.push(inputParameters);
            }
          } else {
            let index = this.modeFunctionForm.outputParameters.indexOf(inputParameters)
            if (index < 0) {
              this.modeFunctionForm.outputParameters.push(inputParameters);
            }
          }

        }
      })
    }
  }
};
</script>
