<template>
  <div class="app-container">
    <TableSearch
        :queryParams="queryParams"
        :showSearch="showSearch"
        queryRef="queryRef"
        @refresh="resetQuery"
        @search="handleQuery"
    >
      <template #one>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item :inline="true" label="设备类型" prop="deviceModel">
            <el-select
                v-model="queryParams.deviceModel"
                :disabled="edit"
                placeholder="请选择设备类型"
                @change="handleQuery"
            >
              <el-option
                  v-for="item in controlModuleList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item :inline="true" label="设备id" prop="idDeDeviceRegistration">
            <el-input
                v-model="queryParams.idDeDeviceRegistration"
                clearable
                placeholder="请输入设备id"
                style="width:100%"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item label="备注" prop="remark">
            <el-input
                v-model="queryParams.remark"
                clearable
                placeholder="请输入参数名称"
                style="width:100%"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </template>

    </TableSearch>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['device:profile:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['device:profile:edit']"
            :disabled="single"
            icon="Edit"
            plain
            type="success"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            v-hasPermi="['device:profile:remove']"-->
      <!--            :disabled="multiple"-->
      <!--            icon="Delete"-->
      <!--            plain-->
      <!--            type="danger"-->
      <!--            @click="handleDelete"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="warning"-->
      <!--            plain-->
      <!--            icon="Download"-->
      <!--            @click="handleExport"-->
      <!--            v-hasPermi="['device:profile:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="profileList" @selection-change="handleSelectionChange">
      <!--      <el-table-column align="center" type="selection" width="55"/>-->
      <el-table-column type="expand">
        <template #default="props">
          <el-table :data="props.row.parameters" :height="240">
            <el-table-column align="center" label="参数名" prop="paramName" show-overflow-tooltip/>
            <el-table-column align="center" label="参数值" prop="defaultValue" show-overflow-tooltip/>
            <el-table-column align="center" label="参数类型" prop="paramType" show-overflow-tooltip/>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作" show-overflow-tooltip>
              <template #default="scope">
                <el-button v-hasPermi="['device:profile:edit']"
                           :disabled="scope.row.paramName==='idDeDeviceRegistration' || scope.row.paramName==='deviceModel'"
                           icon="Edit" link
                           type="primary"
                           @click="handleOpenSingleParamsDialog(scope.row)"
                >修改
                </el-button>
                <!--                <el-button v-hasPermi="['device:profile:remove']" icon="Delete" link type="primary"-->
                <!--                           @click="handleDelete(scope.row)">删除-->
                <!--                </el-button>-->
              </template>
            </el-table-column>
          </el-table>

        </template>
      </el-table-column>
      <el-table-column align="center" label="设备id" prop="idDeDeviceRegistration" show-overflow-tooltip/>
      <el-table-column align="center" label="设备名称" prop="deviceName" show-overflow-tooltip/>
      <el-table-column align="center" label="设备类型" prop="deviceModel">
        <template #default="scope">
          {{ controlModuleList.find(item => item.value === scope.row.deviceModel)?.label }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="终端名称" prop="terminalName" show-overflow-tooltip/>
      <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template #default="scope">
          <el-button v-hasPermi="['device:profile:edit']" icon="Edit" link type="primary"
                     @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-hasPermi="['device:profile:remove']" icon="Delete" link type="primary"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <!-- 添加或修改设备配置信息对话框 -->
    <el-drawer v-model="open" :title="title" append-to-body size="580" @close="()=>edit=false"
               @open="getDeviceList">
      <el-form ref="profileRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备id" prop="idDeDeviceRegistration">
          <el-select
              v-model="form.idDeDeviceRegistration"
              :disabled="edit"
              placeholder="请选择设备类型"
              @change="handleDeviceModelChange"
          >
            <el-option
                v-for="item in deviceList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceModel">
          <el-select
              v-model="form.deviceModel"
              disabled
              placeholder="请选择设备类型"
          >
            <el-option
                v-for="item in controlModuleList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark"
                    :rows="2" placeholder="请输入备注" type="textarea"/>
        </el-form-item>

        <template v-if="form?.deviceModel==='mechanical_arm'">
          <el-form-item v-for="item in deviceParamsMap['mechanical_arm']" :label="item.label" :prop="item.key" :rules="[
              { required: true, message: item.label + '为必填项', trigger: 'blur' }
          ]">
            <template v-if="item.formType==='select'">
              <el-select v-model="form[item.key]">
                <el-option v-for="option in item.options" :key="option.value" :label="option.label"
                           :value="option.value">
                </el-option>
              </el-select>
            </template>
            <template v-if="item.formType==='input_number'">
              <el-input-number v-model="form[item.key]" style="width:100%"/>
            </template>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 添加或修改任务流程编排对话框 -->
    <el-dialog v-model="editSingleParamsDialog" :align-center="true" :title="selectSingleParams.paramName+' 修改'"
               width="500px"
    >
      <template
          v-if="!['remark'].includes(selectSingleParams.paramName)">
        <el-input-number v-model="selectSingleParams.defaultValue" style="width:100%"/>
      </template>
      <template v-else>
        <el-input v-model="selectSingleParams.defaultValue"
                  :rows="2" placeholder="请输入备注" type="textarea"/>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleEditParams">修 改</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="Profile" setup>
import {addProfile, delProfile, getProfile, listProfile, updateProfile} from "@/api/device/profile"
import TableSearch from "@/components/TableSearch/index.vue"
import {controlModuleList, deviceParamsMap} from "@/enum/index.js";
import {convertNumbersToStrings} from "@/views/device/register/components/index.js";
import {listRegister} from "@/api/device/register.js";


const {proxy} = getCurrentInstance()

const profileList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    remark: null,
    idDeDeviceRegistration: null,
    paramName: null,
    paramType: null
  },
  rules: {
    idDeDeviceRegistration: [
      {required: true, message: '请输入设备id', trigger: 'blur'}
    ],
    deviceModel: [
      {required: true, message: '请输入设备类型', trigger: 'blur'}
    ],
  }
})

const {queryParams, form, rules} = toRefs(data)

/** 查询设备配置信息列表 */
function getList() {
  loading.value = true
  listProfile(queryParams.value).then(response => {
    profileList.value = response.rows?.sort((a, b) => {
      if (a.remark < b.remark) {
        return -1; // 如果 a.remark 小于 b.remark，返回负数，表示 a 应该排在 b 前面
      } else if (a.remark > b.remark) {
        return 1; // 如果 a.remark 大于 b.remark，返回正数，表示 a 应该排在 b 后面
      } else {
        return 0; // 如果 a.remark 等于 b.remark，返回 0，表示顺序不变
      }
    })
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  edit.value = false
  editSingleParamsDialog.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    // id: null,
    // createBy: null,
    // createTime: null,
    // updateBy: null,
    // updateTime: null,
    // remark: null,
    // idDeDeviceRegistration: null,
    // paramName: null,
    // paramType: null
  }
  proxy.resetForm("profileRef")
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加设备配置信息"
}

const formatData = (obj) => {
//遍历对象
  let res = []
  for (let key in obj) {
    if (edit.value) {
      res.push({
        remark: obj.remark,
        idDeDeviceRegistration: obj.idDeDeviceRegistration,
        paramName: key,
        deviceModel: obj.deviceModel,
        id: idParamsMap.value[key],
        paramType: "float",
        defaultValue: obj[key]
      })
    } else {
      res.push({
        remark: obj.remark,
        idDeDeviceRegistration: obj.idDeDeviceRegistration,
        paramName: key,
        deviceModel: obj.deviceModel,
        paramType: "float",
        defaultValue: obj[key]
      })
    }
  }
  return res
}


const formInit = (arr) => {
  const res = {}
  res['remark'] = arr[0]['remark']
  res['idDeDeviceRegistration'] = arr[0]['idDeDeviceRegistration']
  res['paramType'] = arr[0]['paramType']
  res['deviceModel'] = arr[0]['deviceModel']

  for (let i = 0; i < arr.length; i++) {
    res[arr[i]['paramName']] = arr[i]['defaultValue']
  }
  for (let key in res) {
    if (!["remark", "idDeDeviceRegistration", "deviceModel", "workModule", "paramType"].includes(key)) {
      res[key] = Number(res[key])
    } else {
      res[key] = res[key]
    }
  }

  return res
}

const edit = ref(false)
const idParamsMap = ref({})

const formatIdParamMap = (arr) => {
  const map = {}
  for (let i = 0; i < arr.length; i++) {
    map[arr[i]['paramName']] = arr[i]['id']
  }
  return map
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  // const _id = row.id || ids.value
  getProfile({id: row.idDeDeviceRegistration, remark: row.remark}).then(response => {
    idParamsMap.value = formatIdParamMap(response.data)
    form.value = formInit(response.data)
    console.log(form.value, 'form.value')
    edit.value = true
    open.value = true
    title.value = "修改设备配置信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["profileRef"].validate(valid => {
    if (valid) {
      const temp = convertNumbersToStrings(form.value)
      const res = formatData(temp)
      if (edit.value) {
        updateProfile(res).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          edit.value = false
          getList()
        })
      } else {
        addProfile(res).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row?.parameters?.map(item => item.id)

  proxy.$modal.confirm('是否确认删除该配置信息？').then(function () {
    return delProfile(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('device/profile/export', {
    ...queryParams.value
  }, `profile_${new Date().getTime()}.xlsx`)
}

getList()


const deviceList = ref([])

const getDeviceList = () => {
  listRegister({pageSize: 10000, pageNum: 1}).then(response => {
    deviceList.value = response.rows?.map(item => ({
      label: `${item.deviceName} ( ${item.deviceCode} )`,
      value: item.id,
      deviceModel: item.deviceModel,
    }))
  })
}
getDeviceList()

const handleDeviceModelChange = () => {
  form.value.deviceModel = deviceList.value.find(item => item.value === form.value.idDeDeviceRegistration)["deviceModel"]
}

const editSingleParamsDialog = ref(false)
const selectSingleParams = ref({})

const handleOpenSingleParamsDialog = (row) => {
  editSingleParamsDialog.value = true
  selectSingleParams.value = JSON.parse(JSON.stringify(row))
}

const handleEditParams = () => {
  console.log(selectSingleParams.value)
  updateProfile([{
    id: selectSingleParams.value.id,
    defaultValue: String(selectSingleParams.value.defaultValue)
  }]).then(response => {
    proxy.$modal.msgSuccess("修改成功")
    editSingleParamsDialog.value = false
    getList()
  })
}
</script>
