<!-- 设备分组信息-编辑 -->
<script lang="ts" setup name="DeviceGroupEdit">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import tableList from './tableList.vue'
import { addGroup, detailGroup, updateGroup } from '@/api/eqpt/device/group'
import { getDictByCode } from '@/api/system/dict'
import useUserStore from '@/store/modules/user'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>() // from组件
const statusName = $route.query.statusName as string
const title = ref('')
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// 对话框类型：create,update
const dialogStatus = ref('create')
const ruleForm = ref({
  equipmentList: [],
  groupInfo: {
    createTime: '',
    createUserId: '',
    createUserName: '',
    groupName: '',
    id: '',
    updateTime: '',
    remark: '',
  },
}) // 表单
const rules = ref<FormRules>({
  groupName: [{ required: true, message: '分组名称必填', trigger: 'blur' }],
  remark: [{ required: true, message: '备注必填', trigger: 'blur' }],
}) // 表单验证规则
// 弹窗初始化
const initDialog = () => {
  dialogStatus.value = $route.params.type as string
  ruleFormRef.value?.resetFields()
  if ($route.params.type === 'create') {
    ruleForm.value.groupInfo.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    ruleForm.value.groupInfo.createUserId = userStore.id
    ruleForm.value.groupInfo.createUserName = userStore.name
  }
  else {
    console.log($route.query.row, 'data')
    const data = JSON.parse($route.query.row as string)
    detailGroup({ groupId: data.id }).then((res) => {
      ruleForm.value = res.data
    })
  }
}
onMounted(() => {
  initDialog()
})
// 关闭弹窗
const close = () => {
  $router.back()
}
const tableRef = ref()
// 保存
const saveForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid && tableRef.value.checkCertificateList()) {
      if (!tableRef.value.list.length) {
        ElMessage.warning('请先选择设备')
        return
      }
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        ruleForm.value.equipmentList = tableRef.value.list
        if ($route.params.type === 'create') {
          addGroup(ruleForm.value).then((res) => {
            ElMessage.success('添加成功')
            close()
          })
        }
        else {
          updateGroup(ruleForm.value).then((res) => {
            ElMessage.success('修改成功')
            close()
          })
        }
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}
</script>

<template>
  <app-container style="overflow: hidden;">
    <approval-dialog ref="approvalDialogRef" @on-success="() => { $router.back() }" />
    <detail-page :title="`设备分组管理-${textMap[dialogStatus]}`">
      <template #btns>
        <el-button v-if="dialogStatus !== 'detail'" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
    </detail-page>
    <detail-block-com>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm.groupInfo"
        :rules="rules" label-position="right" label-width="110px" class="form"
        :disabled="dialogStatus === 'detail'"
        :class="$route.path.includes('detail') ? 'isDetail' : ''"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="分组名称" prop="groupName">
              <el-input v-model.trim="ruleForm.groupInfo.groupName" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人">
              <el-input v-model.trim="ruleForm.groupInfo.createUserName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间">
              <el-input v-model.trim="ruleForm.groupInfo.createTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="18">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="ruleForm.groupInfo.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
    <detail-block-com>
      <table-list ref="tableRef" :data="ruleForm.equipmentList" :status="dialogStatus" />
    </detail-block-com>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
