<template>
  <doc-alert title="用户体系" url="https://doc.iocoder.cn/user-center/" />
  <doc-alert title="三方登陆" url="https://doc.iocoder.cn/social-user/" />
  <doc-alert title="Excel 导入导出" url="https://doc.iocoder.cn/excel-import-and-export/" />

  <el-row :gutter="20">
    <!-- 左侧 设备分类 树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeviceCategoryTree @node-click="handleDeviceCategoryTreeNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="模板名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入模板名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="模板编码" prop="code">
            <el-input
              v-model="queryParams.code"
              placeholder="请输入模板编码"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="属性模板状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['rq:iot-device-template:create']"
            >
              <Icon icon="ep:plus" /> 新增
            </el-button>
            <!--
            <el-button @click="handleAllQuery"><Icon icon="ep:search" />查询所有</el-button> -->
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="list">
          <el-table-column label="序号" width="60" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            label="模板编码"
            align="center"
            prop="code"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="模板名称"
            align="center"
            prop="name"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="设备分类名称"
            align="center"
            key="deviceCategoryName"
            prop="deviceCategoryName"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="状态" key="status">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"
                :disabled="!checkPermi(['rq:iot-device-template:update'])"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180"
          />
          <el-table-column label="操作" align="center" width="160">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <el-button
                  type="primary"
                  link
                  @click="openDetail(scope.row.deviceCategoryId)"
                >
                  <Icon icon="ep:edit" />查看
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['rq:iot-device-template:update']"
                >
                  <Icon icon="ep:edit" />修改
                </el-button>
                <el-dropdown
                  @command="(command) => handleCommand(command, scope.row)"
                  v-hasPermi="[
                    'rq:iot-device-template:delete'
                  ]"
                >
                  <el-button type="primary" link><Icon icon="ep:d-arrow-right" /> 更多</el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        command="handleDelete"
                        v-if="checkPermi(['rq:iot-device-template:delete'])"
                      >
                        <Icon icon="ep:delete" />删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 添加或修改 属性模板 对话框 -->
  <TemplateForm ref="formRef" :category_id="selectedId" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { checkPermi } from '@/utils/permission'
import { dateFormatter } from '@/utils/formatTime'
import { CommonStatusEnum } from '@/utils/constants'
import * as DeviceTemplateApi from '@/api/pms/devicetemplate'
import TemplateForm from './TemplateForm.vue'
import DeviceCategoryTree from './DeviceCategoryTree.vue'
import { useTreeStore } from '@/store/modules/attrTemplateTreeStore';

defineOptions({ name: 'DeviceAttrsTemplate' })

const treeStore = useTreeStore();
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { push } = useRouter()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
  status: undefined,
  deviceCategoryId: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

// 从 Store 中获取左侧 设备分类树 选中的 节点ID
const selectedId = computed(() => treeStore.selectedId);

/** 查询 设备属性模板 列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceTemplateApi.getDeviceTemplatePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

/** 搜索按钮操作 */
const handleAllQuery = () => {
  queryParams.pageNo = 1
  queryParams.deviceCategoryId = ''
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 处理 设备分类树 被点击 */
const handleDeviceCategoryTreeNodeClick = async (row) => {
  queryParams.deviceCategoryId = row.id
  await getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 打开详情 */
const openDetail = (id: number) => {
  push({ name: 'DeviceAttrTemplateModel', params: { id } })
}

/** 修改 设备属性模板 状态 */
const handleStatusChange = async (row: DeviceTemplateApi.DeviceAttrTemplateVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.name + '"属性模板吗?')
    // 发起修改状态
    await DeviceTemplateApi.updateDeviceTemplateStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: DeviceTemplateApi.DeviceAttrTemplateVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DeviceTemplateApi.deleteDeviceTemplate(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>
