<template>
  <div>

    <el-row :gutter="5" class="mb8">
      <el-col :span="15">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
    </el-row>


    <el-table ref="serviceTable" :data="servicesData" row-key="columnId">
      <el-table-column label="序号" type="index" prop="index" min-width="5%" class-name="allowDrag"/>
      <el-table-column
        label="功能模式"
        prop="functionMode"
        v-if="false"
      />
      <el-table-column
        label="定位坐标标识"
        prop="coordinate"
        v-if="false"
      />
      <el-table-column
        label="描述"
        prop="remark"
        v-if="false"
      />

      <el-table-column
        label="功能名称"
        prop="functionName"
        min-width="10%"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="标识符"
        prop="functionIdentifier"
        min-width="10%"
        :show-overflow-tooltip="true"
      />

      <el-table-column prop="dataType" label="调用方式" min-width="10%">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hw_mode_function_invoke_method" :value="scope.row.invokeMethod"/>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" min-width="10%">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateService(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteService(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>


    <!-- 添加或修改设备模型服务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="modeFunctionForm" :model="modeFunctionForm" :rules="modeFunctionRules" label-width="80px">
        <el-form-item label="功能模式" prop="functionMode" v-show="false">
          <el-input v-model="modeFunctionForm.functionMode" placeholder="请输入功能模式"/>
        </el-form-item>

        <el-form-item label="功能名称" prop="functionName">
          <el-input v-model="modeFunctionForm.functionName" placeholder="请输入功能名称"/>
        </el-form-item>
        <el-form-item label="标识符" prop="functionIdentifier">
          <el-input v-model="modeFunctionForm.functionIdentifier" placeholder="请输入标识符"/>
        </el-form-item>

        <el-form-item label="调用方式" prop="invokeMethod">
          <el-radio-group v-model="modeFunctionForm.invokeMethod">
            <el-radio
              v-for="dict in dict.type.hw_mode_function_invoke_method"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>

        </el-form-item>

        <el-form-item label="输入参数" prop="inputParametersData">
          <el-table ref="inputParametersTable" :data="modeFunctionForm.inputParameters" row-key="columnId">
            <el-table-column
              label="参数名称"
              prop="parameterName"
              min-width="10%"
              height="10px"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="标识符"
              prop="parameterIdentifier"
              min-width="10%"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="操作" align="center" min-width="10%">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateInputParameter(scope.row)"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteInputParameter(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="" prop="inputParameterBtn">
          <el-button type="primary" @click="handleAddInputParameter" size="mini">添加输入参数</el-button>
        </el-form-item>

        <el-form-item label="输出参数" prop="outputParametersData">
          <el-table ref="outputParametersTable" :data="modeFunctionForm.outputParameters" row-key="columnId">
            <el-table-column
              label="参数名称"
              prop="parameterName"
              min-width="10%"
              height="10px"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="标识符"
              prop="parameterIdentifier"
              min-width="10%"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="操作" align="center" min-width="10%">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateOutputParameter(scope.row)"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteOutputParameter(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="" prop="outputParameterBtn">
          <el-button type="primary" @click="handleAddOutputParameter" size="mini">添加输出参数</el-button>
        </el-form-item>


        <el-form-item label="描述" prop="remark">
          <el-input v-model="modeFunctionForm.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDeviceModeServiceForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改设备模型服务参数对话框(输入和输出参数复用此对话框) -->
    <el-dialog :title="inputParameterTitle" :visible.sync="inputParameterOpen" width="500px" append-to-body>
      <el-form ref="inputParameterForm" :model="inputParameterForm" :rules="inputParameterRules" label-width="80px">
        <el-form-item label="参数类型" prop="parameterType" v-show="false">
          <el-input v-model="inputParameterForm.parameterType"/>
        </el-form-item>

        <el-form-item label="参数名称" prop="parameterName">
          <el-input v-model="inputParameterForm.parameterName" placeholder="请输入参数名称"/>
        </el-form-item>
        <el-form-item label="标识符" prop="parameterIdentifier">
          <el-input v-model="inputParameterForm.parameterIdentifier" placeholder="请输入标识符"/>
        </el-form-item>

        <el-form-item label="数据类型" prop="dataType">
          <el-select v-model="inputParameterForm.dataType" placeholder="请选择数据类型">
            <el-option
              v-for="dict in dict.type.hw_mode_function_data_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="取值范围" prop="minMaxValue" v-show="false">
          <el-input v-model="inputParameterForm.minValue" placeholder="请输入最小值" style="width:150px;"/>
          ——
          <el-input v-model="inputParameterForm.maxValue" placeholder="请输入最大值" style="width:150px;"/>
        </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="请输入最大长度" :min="10" :max="1000"
                           style="width:150px;"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInputParameterForm">确 定</el-button>
        <el-button @click="cancelParameter">取 消</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>

import {
  addDeviceModeFunction,
  updateDeviceModeFunction,
  getDeviceModeParameters,
  delDeviceModeFunction
} from "@/api/business/deviceModeFunction";

export default {
  name: 'servicesDataEdit',
  dicts: ['hw_mode_function_invoke_method', 'hw_mode_function_data_type'],
  props: {
    servicesData: {
      type: Array,
      default: []
    },
    deviceModeId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 弹出层标题
      title: "",

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

      deviceModeId: '',

      servicesData: [],
      serviceDataIndex: -1,
      inputParameterDataIndex: -1,
      outputParameterDataIndex: -1,

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

      outputParametersData: [],

      modeFunctionRules: {
        functionType: [
          {required: true, message: "请选择功能类型", trigger: "blur"},
        ],
        functionName: [
          {required: true, message: "请输入功能名称", trigger: "blur"}
        ],
        invokeMethod: [
          {required: true, message: "请选择调用方式", trigger: "change"}
        ],
        functionIdentifier: [
          {required: true, message: "请输入标识符", trigger: "blur"},
          {
            pattern: /^[a-zA-Z][a-z0-9_]+$/,
            message: "2-20个字符，由大小写字母、数字或下划线组成，开头必须为小写字母",
            trigger: "blur"
          }
        ],

      },

      inputParameterRules: {
        parameterName: [
          {required: true, message: "请输入功能名称", trigger: "blur"}
        ],
        parameterIdentifier: [
          {required: true, message: "请输入标识符", trigger: "blur"},
          {
            pattern: /^[a-z][a-z0-9_]+$/,
            message: "2-20个字符，由小写字母、数字或下划线组成，开头必须为小写字母",
            trigger: "blur"
          }
        ],
        dataType: [
          {required: true, message: "请选择数据类型", trigger: "blur"},
        ],
      },

    };
  },
  created() {

  },
  methods: {
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备模型服务";
    },
    // 表单重置
    reset() {
      this.modeFunctionForm = {
        functionMode: '2',
        functionName: null,
        functionIdentifier: null,
        inputParameters: [],
        outputParameters: [],
        invokeMethod: '1',
        remark: null,
      };
      //this.resetForm("modeFunctionForm");
    },

    handleUpdateService(row) {
      // this.reset();
      this.serviceDataIndex = this.servicesData.indexOf(row);
      this.modeFunctionForm = JSON.parse(JSON.stringify(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 = "添加设备模型服务";
      // alert(this.servicesData.indexOf(row))
      // const modeParameterId = row.modeParameterId || this.ids
      // alert(modeParameterId)
      //const deviceModeName = row.deviceModeName || this.tableNames[0];
      //const params = { pageNum: this.queryParams.pageNum };
    },

    handleDeleteService(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 servicesData = this.servicesData;

      if (row.modeFunctionId !== undefined) {
        delDeviceModeFunction(row.modeFunctionId).then(res => {
          this.$modal.msgSuccess(res.msg);
          if (res.code === 200) {
            this.servicesData = servicesData.splice(servicesData.indexOf(row), 1);
          }
        });
      } else {
        this.servicesData = servicesData.splice(servicesData.indexOf(row), 1);
      }
    },


    submitDeviceModeServiceForm() {
      this.$refs['modeFunctionForm'].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;
                  this.pushData();
                }
              });
            } 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 {
            this.open = false;
            this.pushData();
          }
        }
      })
    },

    pushData() {
      let serviceDataIndex = this.serviceDataIndex;
      if (serviceDataIndex > -1) {
        this.serviceDataIndex = -1;
        this.servicesData.splice(serviceDataIndex, 1, this.modeFunctionForm);
      } else {
        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.inputParameterDataIndex = this.modeFunctionForm.inputParameters.indexOf(row);
      this.convertParameterDefinition(row);
      this.inputParameterForm = JSON.parse(JSON.stringify(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(() => {});

      this.modeFunctionForm.inputParameters.splice(this.modeFunctionForm.inputParameters.indexOf(row), 1);

    },

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

    handleUpdateOutputParameter(row) {
      this.outputParameterDataIndex = this.modeFunctionForm.outputParameters.indexOf(row);
      this.convertParameterDefinition(row);
      this.inputParameterForm = JSON.parse(JSON.stringify(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 inputParameterDataIndex = this.inputParameterDataIndex;
            if (inputParameterDataIndex > -1) {
              this.inputParameterDataIndex = -1;
              this.modeFunctionForm.inputParameters.splice(inputParameterDataIndex, 1, inputParameters);
            } else {
              this.modeFunctionForm.inputParameters.push(inputParameters);
            }

          } else {//输出参数
            let outputParameterDataIndex = this.outputParameterDataIndex;
            if (outputParameterDataIndex > -1) {
              this.outputParameterDataIndex = -1;
              this.modeFunctionForm.outputParameters.splice(outputParameterDataIndex, 1, inputParameters);
            } else {
              this.modeFunctionForm.outputParameters.push(inputParameters)
            }
          }
        }
      })
    }
  }
};
</script>
