<template>
  <el-table
      :data="tableData"
      style="width: 100%"
  >
    <el-table-column fixed prop="fieldname" label="字段名" style="width: 25%" />
    <el-table-column prop="fieldsize" label="字段长度" style="width: 25%" />
    <el-table-column prop="value" label="默认值" style="width: 25%" />
    <el-table-column fixed="right"  style="width: 25%">
      <template #default="{row}">
        <div style="display: flex;">
          <el-button  type="primary" @click="open('delete', row)">删除字段</el-button>
          <el-button  type="primary" @click="editField(row)">修改字段</el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>

  <el-button
      style="width: 100%; border: 1px dashed"
      class="mt-4"
      @click="addField"
  >+</el-button>

  <el-dialog v-model="dialogVisible" @close="resetForm">
    <template #title>{{flag ? '新增' : '编辑'}}字段</template>
    <el-form
        ref="ruleFormRef"
        label-position="right"
        label-width="150px"
        :model="fields"
        :rules="rules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="命令名">
            <el-input v-model="fields.cmd_name" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="指令类型">
            <el-input v-model="fields.cmd_type" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="序号">
            <el-input v-model="fields.fieldindex" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="fieldname">
            <el-input v-model="fields.fieldname"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="长度" prop="fieldsize">
            <el-input v-model="fields.fieldsize"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="值" prop="value">
            <el-input v-model="fields.value"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="指令最大值">
            <el-input v-model="fields.maxvalue"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="指令最小值">
            <el-input v-model="fields.minvalue"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="字段类型" prop="datatype">
            <el-select v-model="fields.datatype">
              <el-option v-for="item in fieldTypes" :label="item.label" :value="item.value" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="Lua对输入数据的操作">
            <el-input v-model="fields.lua_script_in"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Lua对输出数据的操作">
            <el-input v-model="fields.lua_script_out"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="12">
          <el-form-item >
            <el-button class="mr-0" @click="more = !more">更多操作</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="more">
        <el-col :span="12">
          <el-form-item label="输入数据操作">
            <el-input v-model="fields.operation_in"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="输入数据操作参数">
            <el-input v-model="fields.operation_in_num"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="more">
        <el-col :span="12">
          <el-form-item label="输出数据操作">
            <el-input v-model="fields.operation_out"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="输出数据操作参数">
            <el-input v-model="fields.operation_out_num"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="more">
        <el-col :span="12">
          <el-form-item label="输入数据字节操作">
            <el-input v-model="fields.operabo_in"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="输出数据字节操作">
            <el-input v-model="fields.operabo_out"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="open">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref,toRefs} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {AddProtocolCMd, DeleteProtocolCmd, EditProtocolCmd} from "../dao/device";

const flag = ref(false)
const dialogVisible = ref(false)
const more = ref(false)

const props = defineProps({
  //子组件接收父组件传递过来的值
  info: String,
  type: String,
  message: Object
})
const cmdName = ref(toRefs(props).info.value)
const cmdFields = ref(toRefs(props).message.value[cmdName.value])
const tableData = ref([])
const rules = ref({
  fieldname: [
    {required: true, message: "请输入名称", trigger: 'blur'}
  ],
  fieldsize: [
    {required: true, message: "请输入长度", trigger: 'blur'}
  ],
  value: [
    {required: true, message: "请输入值", trigger: 'blur'}
  ],
  datatype: [
    {required: true, message: "请选择字段类型", trigger: 'change'}
  ],
})
const ruleFormRef = ref()
for (const item of cmdFields.value){
  tableData.value.push(item)
}

const fields = ref({
  cmd_name: '',
  cmd_type: '',
  fieldindex: '',
  fieldname: '',
  fieldsize: '',
  value: '',
  minvalue: '',
  maxvalue: '',
  datatype: '',
  operation_in: '',
  operation_in_num: '',
  operation_out: '',
  operation_out_num: '',
  operabo_in: '',
  operabo_out: '',
  lua_script_in: '',
  lua_script_out: ''
})
const fieldTypes = [
  { value: 0, label: 'DATATYPE_DEFAULT'},
  { value: 1, label: 'DATATYPE_STR '},
  { value: 2, label: 'DATATYPE_UINT_STR '},
  { value: 3, label: 'DATATYPE_INT_STR '},
  { value: 4, label: 'DATATYPE_FLOAT_STR '},
  { value: 5, label: 'DATATYPE_DOUBLE_STR '},
  { value: 6, label: 'DATATYPE_HEX '},
  { value: 7, label: 'DATATYPE_STR_HEX '},
  { value: 8, label: 'DATATYPE_UINT_HEX '},
  { value: 9, label: 'DATATYPE_INT_HEX '},
  { value: 10, label: 'DATATYPE_FLOAT_HEX '},
  { value: 11, label: 'DATATYPE_DOUBLE_HEX '},
  { value: 12, label: 'DATATYPE_DOUBLE '},
  { value: 13, label: 'DATATYPE_PAYLOAD '},
  { value: 14, label: 'DATATYPE_INT8 '},
  { value: 15, label: 'DATATYPE_TIMESTR '},
  { value: 16, label: 'DATATYPE_MAX'},
]

let operation = ''

const addField = () => {
  flag.value = true;
  more.value = false
  for(const key in fields.value){
    fields.value[key] = '';
  }
  fields.value['cmd_name'] = toRefs(props).info.value
  fields.value['cmd_type'] = toRefs(props).type.value
  fields.value['fieldindex'] = tableData.value.length + 1
  fields.value['minvalue'] = 'null'
  fields.value['maxvalue'] = 'null'
  fields.value['lua_script_in'] = 'null'
  fields.value['lua_script_out'] = 'null'
  fields.value['operation_in'] = 0
  fields.value['operation_in_num'] = 0
  fields.value['operation_out'] = 0
  fields.value['operation_out_num'] = 0
  fields.value['operabo_in'] = 0
  fields.value['operabo_out'] = 0
  dialogVisible.value = true;
  if (ruleFormRef.value){
    ruleFormRef.value.clearValidate()
  }
}

function editField(data){
  dialogVisible.value = true
  flag.value = false
  more.value = false
  for (const key in data){
    fields.value[key] = data[key]
  }

}

const resetForm = () => {
  for (const key in fields.value){
    fields.value[key] = ''
  }
  ruleFormRef.value.clearValidate()
}

async function Edit(id, params){
  await EditProtocolCmd(id, params)
}

async function Delete(id){
  await DeleteProtocolCmd(id)
}

async function Add(params){
  await AddProtocolCMd(params)
}

function confirm(str, data){
  if (str === 'delete'){
    operation = '删除'
  } else if(flag.value){
    operation = '增加'
  }else if (!flag.value){

    operation = '修改'
  }
  ElMessageBox.confirm(
      '是否确认' + operation + '?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        ElMessage({
          type: 'success',
          message: operation + '成功',
        })
        dialogVisible.value = false
        more.value = false
        if (operation === '修改'){
          let params = fields.value
          for (const key in params){
            if (params[key] === null){
              params[key] = 'none'
            }
          }
          Edit(params['id'], params)
          for (const item of Object.keys(fields.value)){
            tableData.value[fields.value['fieldindex'] -1 ][item] = fields.value[item]
          }
        }else if (operation === '删除'){
          Delete(data['id'])
          tableData.value.splice(data['fieldindex'] -1 , 1)
        }else if (operation === '增加'){
          Add(fields.value)
          let params = {}
          for (const item of Object.keys(fields.value)){
            params[item] = fields.value[item]
          }
          tableData.value.push(params)
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

const cancel = () => {
  dialogVisible.value = false
  more.value = false
  ruleFormRef.value.clearValidate()
  // ruleFormRef.value.resetFields()
}

async function open(str, data){
  if (str === 'delete'){
    confirm(str, data)
    return
  }
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid) => {
    if (valid){
      confirm(str, data)
      // ruleFormRef.value.resetFields()
    }else {
      // ruleFormRef.value.resetFields()
      return false
    }
  })

}

</script>

<style>
.el-row:not(:last-child) {
  margin-bottom: 10px; /* 添加间距 */
}
</style>