<template>
  <div style="padding: 6px">
    <!-- 添加或修改通用物模型对话框 -->
    <el-dialog title="编辑参数" v-model="openEdit" append-to-body width="900px">
      <div style="margin: -30px 0 30px; background-color: #ddd; height: 1px"></div>
      <el-row>
        <el-col
          :span="12"
          style="border: 1px solid #ddd; border-radius: 5px; padding: 10px; background-color: #eee"
        >
          <el-form :inline="true" :model="queryParams" label-width="48px" size="small">
            <el-form-item label="" prop="templateName">
              <el-input
                v-model="queryParams.templateName"
                placeholder="请输入物模型名称"
                clearable
                size="small"
                style="width: 160px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                :icon="Search"
                size="small"
                style="padding: 5px"
                type="info"
                @click="handleQuery"
                >搜索</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-link
                :underline="false"
                :icon="InfoFilled"
                style="margin-left: 20px"
                type="primary"
                >单击应用模板</el-link
              >
            </el-form-item>
          </el-form>

          <el-table
            :border="false"
            v-loading="loading"
            :data="templateList"
            :row-style="{ backgroundColor: '#eee' }"
            :show-header="false"
            highlight-current-row
            size="small"
            @row-click="rowClick"
          >
            <el-table-column label="选择" align="center" width="30">
              <template #default="scope">
                <input
                  :checked="scope.row.isSelect"
                  :disabled="scope.row.datatype == 'array' || scope.row.datatype == 'object'"
                  name="template"
                  type="radio"
                />
              </template>
            </el-table-column>
            <el-table-column label="名称" align="left" prop="templateName" />
            <el-table-column label="标识符" align="left" prop="identifier" />
            <el-table-column label="数据类型" align="center" prop="datatype" width="60">
              <template #default="scope">
                <dict-tag :options="dict.type.iot_data_type" :value="scope.row.datatype" />
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNum"
            :total="total"
            layout="prev, pager, next"
            small
            style="margin: 0 0 10px; background-color: #eee"
            @pagination="getList"
          />
        </el-col>

        <el-col :offset="1" :span="11">
          <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="参数名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="例如：温度"
                size="small"
                style="width: 270px"
              />
            </el-form-item>
            <el-form-item label="参数标识" prop="id">
              <el-input
                v-model="form.id"
                placeholder="例如：temperature"
                size="small"
                style="width: 270px"
              />
            </el-form-item>
            <el-form-item label="参数排序" prop="order">
              <el-input-number
                v-model="form.order"
                placeholder="请输入排序"
                controls-position="right"
                size="small"
                style="width: 270px"
                type="number"
              />
            </el-form-item>

            <el-form-item label="参数特性" prop="property">
              <el-checkbox
                v-model="form.isChart"
                :false-label="0"
                label="图表展示"
                :true-label="1"
                name="isChart"
                @change="isChartChange"
              />
              <el-checkbox
                v-model="form.isMonitor"
                :false-label="0"
                label="实时监测"
                :true-label="1"
                name="isMonitor"
                @change="isMonitorChange"
              />
              <el-checkbox
                v-model="form.isReadonly"
                :false-label="0"
                label="只读数据"
                :true-label="1"
                name="isReadonly"
                @change="isReadonlyChange"
              />
              <el-checkbox
                v-model="form.isHistory"
                :false-label="0"
                label="历史存储"
                :true-label="1"
                name="isHistory"
              />
              <el-checkbox
                v-model="form.isSharePerm"
                :false-label="0"
                label="分享权限"
                :true-label="1"
                name="isSharePerm"
              />
            </el-form-item>

            <div style="margin-bottom: 20px; background-color: #ddd; height: 1px"></div>
            <el-form-item label="数据类型" prop="datatype">
              <el-select
                v-model="form.datatype"
                placeholder="请选择数据类型"
                size="small"
                style="width: 125px"
              >
                <el-option key="integer" label="整数" value="integer" />
                <el-option key="decimal" label="小数" value="decimal" />
                <el-option
                  key="bool"
                  :disabled="form.isChart == 1"
                  label="布尔"
                  value="bool"
                />
                <el-option
                  key="enum"
                  :disabled="form.isChart == 1"
                  label="枚举"
                  value="enum"
                />
                <el-option
                  key="string"
                  :disabled="form.isChart == 1"
                  label="字符串"
                  value="string"
                />
              </el-select>
            </el-form-item>
            <div v-if="form.datatype == 'integer' || form.datatype == 'decimal'">
              <el-form-item label="取值范围">
                <el-row>
                  <el-col :span="10">
                    <el-input
                      v-model="form.specs.min"
                      placeholder="最小值"
                      size="small"
                      type="number"
                    />
                  </el-col>
                  <el-col :span="4" align="center">到</el-col>
                  <el-col :span="10">
                    <el-input
                      v-model="form.specs.max"
                      placeholder="最大值"
                      size="small"
                      type="number"
                    />
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="单位">
                <el-input
                  v-model="form.specs.unit"
                  placeholder="例如：℃"
                  size="small"
                  style="width: 308px"
                />
              </el-form-item>
              <el-form-item label="步长">
                <el-input-number
                  v-model="form.specs.step"
                  placeholder="例如：1"
                  controls-position="right"
                  size="small"
                  style="width: 308px"
                  type="number"
                />
              </el-form-item>
            </div>
            <div v-if="form.datatype == 'bool'">
              <el-form-item label="布尔值" prop="">
                <el-row style="margin-bottom: 10px">
                  <el-col :span="10">
                    <el-input
                      v-model="form.specs.falseText"
                      placeholder="例如：关闭"
                      size="small"
                    />
                  </el-col>
                  <el-col :offset="1" :span="10">（0 值对应文本）</el-col>
                </el-row>
                <el-row>
                  <el-col :span="10">
                    <el-input
                      v-model="form.specs.trueText"
                      placeholder="例如：打开"
                      size="small"
                    />
                  </el-col>
                  <el-col :offset="1" :span="10">（1 值对应文本）</el-col>
                </el-row>
              </el-form-item>
            </div>
            <div v-if="form.datatype == 'enum'">
              <el-form-item label="展示方式">
                <el-select
                  v-model="form.specs.showWay"
                  placeholder="请选择展示方式"
                  style="width: 175px"
                >
                  <el-option
                    key="select"
                    label="下拉框"
                    value="select"
                  />
                  <el-option
                    key="button"
                    label="按钮"
                    value="button"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="枚举项" prop="">
                <el-row
                  v-for="(item, index) in form.specs.enumList"
                  :key="'enum' + index"
                  style="margin-bottom: 10px"
                >
                  <el-col :span="8">
                    <el-input
                      v-model="item.value"
                      placeholder="例如：0"
                      size="small"
                    />
                  </el-col>
                  <el-col :offset="1" :span="11">
                    <el-input
                      v-model="item.text"
                      placeholder="例如：中速挡位"
                      size="small"
                    />
                  </el-col>
                  <el-col v-if="index != 0" :offset="1" :span="3">
                    <a style="color: #f56c6c" @click="removeEnumItem(index)">删除</a>
                  </el-col>
                </el-row>
                <div>
                  +
                  <a style="color: #409eff" @click="addEnumItem()">添加枚举项</a>
                </div>
              </el-form-item>
            </div>
            <div v-if="form.datatype == 'string'">
              <el-form-item label="最大长度" prop="">
                <el-row>
                  <el-col :span="10">
                    <el-input
                      v-model="form.specs.maxLength"
                      placeholder="例如：1024"
                      size="small"
                      type="number"
                    />
                  </el-col>
                </el-row>
              </el-form-item>
            </div>
          </el-form>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { Search, InfoFilled } from '@element-plus/icons-vue'
import { listTemplate } from '@/api/pms/video/template'

// 组件名称
defineOptions({
  name: 'things_parameter'
})

// 定义 props
const props = defineProps({
  data: {
    type: Object,
    default: null
  }
})

// 定义 emits
const emit = defineEmits(['dataEvent'])

// 字典数据（需要从合适的位置引入）
const dict = {
  type: {
    iot_things_type: [],
    iot_data_type: [],
    iot_yes_no: []
  }
}

// refs
const formRef = ref()
const productId = ref()

// 数据状态
const loading = ref(true)
const total = ref(0)
const templateList = ref([])
const openEdit = ref(false)
const index = ref(-1)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  type: null
})

// 表单参数
const form = reactive({
  name: null,
  id: null,
  order: 0,
  datatype: 'integer',
  isChart: 0,
  isHistory: 1,
  isSharePerm: 0,
  isMonitor: 0,
  isReadonly: 0,
  specs: {
    enumList: [
      {
        value: '',
        text: ''
      }
    ],
    showWay: 'select' // 显示方式select=下拉选择框，button=按钮
  }
})

// 表单校验规则
const rules = {
  name: [
    {
      required: true,
      message: '参数名称不能为空',
      trigger: 'blur'
    }
  ],
  id: [
    {
      required: true,
      message: '参数标识符不能为空',
      trigger: 'blur'
    }
  ],
  order: [
    {
      required: true,
      message: '参数顺序不能为空',
      trigger: 'blur'
    }
  ],
  datatype: [
    {
      required: true,
      message: '数据类型不能为空',
      trigger: 'change'
    }
  ]
}

// 监听 data 变化
watch(
  () => props.data,
  (newVal, oldVal) => {
    index.value = newVal.index
    if (newVal && newVal.parameter.name && newVal.parameter.name != '') {
      form.name = newVal.parameter.name
      form.id = newVal.parameter.id
      form.order = newVal.parameter.order
      form.isChart = newVal.parameter.isChart ? newVal.parameter.isChart : 0
      form.isHistory = newVal.parameter.isHistory ? newVal.parameter.isHistory : 1
      form.isSharePerm = newVal.parameter.isSharePerm ? newVal.parameter.isSharePerm : 0
      form.isMonitor = newVal.parameter.isMonitor ? newVal.parameter.isMonitor : 0
      form.isReadonly = newVal.parameter.isReadonly ? newVal.parameter.isReadonly : 0
      form.specs = newVal.parameter.datatype
      form.datatype = form.specs.type
      if (!form.specs.enumList) {
        form.specs.enumList = [
          {
            value: '',
            text: ''
          }
        ]
      }
      if (!form.specs.arrayType) {
        form.specs.arrayType = 'integer'
      }
    }
    openEdit.value = true
    getList()
  }
)

/** 查询通用物模型列表 */
const getList = () => {
  loading.value = true
  listTemplate(queryParams).then((response) => {
    
    //模板列表初始化isSelect值，用于单选
    for (let i = 0; i < response.list.length; i++) {
      response.list[i].isSelect = false
    }
    templateList.value = response.list
    total.value = response.total
    setRadioSelected(productId.value)
    loading.value = false
  })
}

/** 单选数据 */
const rowClick = (item) => {
  if (item != null && item.datatype != 'array' && item.datatype != 'object') {
    form.name = item.templateName
    form.id = item.identifier
    form.order = item.modelOrder
    form.isChart = item.isChart ? item.isChart : 0
    form.isHistory = item.isHistory ? item.isHistory : 1
    form.isSharePerm = item.isSharePerm ? item.isSharePerm : 0
    form.isReadonly = item.isReadonly ? item.isReadonly : 0
    form.isMonitor = item.isMonitor ? item.isMonitor : 0
    form.datatype = item.datatype
    // Json转对象
    form.specs = JSON.parse(item.specs)
    if (!form.specs.enumList) {
      form.specs.enumList = [
        {
          value: '',
          text: ''
        }
      ]
    }
    if (!form.specs.arrayType) {
      form.specs.arrayType = 'integer'
    }
    setRadioSelected(item.templateId)
  }
}

/** 设置单选按钮选中 */
const setRadioSelected = (templateId) => {
  for (let i = 0; i < templateList.value.length; i++) {
    if (templateList.value[i].templateId == templateId) {
      templateList.value[i].isSelect = true
    } else {
      templateList.value[i].isSelect = false
    }
  }
}

// 取消按钮
const cancel = () => {
  openEdit.value = false
  reset()
}

// 表单重置
const reset = () => {
  index.value = -1
  Object.assign(form, {
    name: null,
    id: null,
    order: 0,
    datatype: 'integer',
    isChart: 0,
    isHistory: 1,
    isSharePerm: 0,
    isMonitor: 0,
    isReadonly: 0,
    specs: {
      enumList: [
        {
          value: '',
          text: ''
        }
      ],
      showWay: 'select' // 显示方式select=下拉选择框，button=按钮
    }
  })
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 格式化datatype
      const datatype = formatThingsSpecs()
      // 清空不需要存储数据
      delete form.specs
      openEdit.value = false
      // 返回参数对象
      let data = {
        parameter: JSON.parse(JSON.stringify({ ...form, datatype })),
        index: index.value
      }
      console.log('data', data)
      emit('dataEvent', data)
      reset()
    }
  })
}

// 是否图表展示改变
const isChartChange = () => {
  if (form.isChart == 1) {
    form.isReadonly = 1
  } else {
    form.isMonitor = 0
  }
}

// 是否实时监测改变
const isMonitorChange = () => {
  if (form.isMonitor == 1) {
    form.isReadonly = 1
    form.isChart = 1
  }
}

// 是否只读数据改变
const isReadonlyChange = () => {
  if (form.isReadonly == 0) {
    form.isMonitor = 0
    form.isChart = 0
  }
}

// 格式化物模型
const formatThingsSpecs = () => {
  var data = {}
  data.type = form.datatype
  if (form.datatype == 'integer' || form.datatype == 'decimal') {
    data.min = Number(form.specs.min ? form.specs.min : 0)
    data.max = Number(form.specs.max ? form.specs.max : 100)
    data.unit = form.specs.unit ? form.specs.unit : ''
    data.step = Number(form.specs.step ? form.specs.step : 1)
  } else if (form.datatype == 'string') {
    data.maxLength = Number(form.specs.maxLength ? form.specs.maxLength : 1024)
  } else if (form.datatype == 'bool') {
    data.falseText = form.specs.falseText
      ? form.specs.falseText
      : '关闭'
    data.trueText = form.specs.trueText
      ? form.specs.trueText
      : '开启'
  } else if (form.datatype == 'array') {
    data.arrayType = form.specs.arrayType
  } else if (form.datatype == 'enum') {
    data.showWay = form.specs.showWay
    if (form.specs.enumList && form.specs.enumList[0].text != '') {
      data.enumList = form.specs.enumList
    } else {
      data.showWay = 'select'
      data.enumList = [
        {
          value: '0',
          text: '低'
        },
        {
          value: '1',
          text: '高'
        }
      ]
    }
  }
  return data
}

/** 添加枚举项 */
const addEnumItem = () => {
  form.specs.enumList.push({
    value: '',
    text: ''
  })
}

/** 删除枚举项 */
const removeEnumItem = (index) => {
  form.specs.enumList.splice(index, 1)
}

// 组件创建时执行
onMounted(() => {
  getList()
  reset()
})
</script>

<style>
.specsColor {
  background-color: #fcfcfc;
}
</style>