<template>
  <el-row :gutter="20">
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="80px"
        >
          <el-form-item :label="t('main.planCode')" prop="serialNumber">
            <el-input
              v-model="queryParams.serialNumber"
              :placeholder="t('main.codeHolder')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item :label="t('operationFill.name')" prop="name">
            <el-input
              v-model="queryParams.name"
              :placeholder="t('devicePerson.filterDevicePlaceholder')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item :label="t('operationFill.createTime')" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              :start-placeholder="t('operationFill.start')"
              :end-placeholder="t('operationFill.end')"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-220px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />
              {{ t('operationFill.search') }}</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />  {{ t('operationFill.reset') }}</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['rq:iot-maintenance-plan:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> {{ t('operationFill.add') }}
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['rq:iot-maintenance-plan:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column :label="t('iotDevice.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="t('main.planCode')" align="center" prop="serialNumber" />
          <el-table-column :label="t('main.planName')" align="center" prop="name" />
          <el-table-column :label="t('iotMaintain.PersonInCharge')" align="center" prop="responsiblePersonName" />
          <el-table-column :label="t('maintain.status')" align="center" prop="status" >
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="t('operationFill.createTime')"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
          <el-table-column :label="t('maintain.operation')" align="center" min-width="120px">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['rq:iot-maintenance-plan:update']"
              >
                {{ t('info.edit') }}
              </el-button>
              <el-button
                link
                type="primary"
                @click="detail(scope.row.id)"
                v-hasPermi="['rq:iot-maintenance-plan:query']"
              >
                {{ t('maintain.view') }}
              </el-button>
            </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>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { IotMaintenancePlanApi, IotMaintenancePlanVO } from '@/api/pms/maintenance'
import DeptTree from "@/views/system/user/DeptTree.vue";
import {CommonStatusEnum} from "@/utils/constants";
const { push } = useRouter() // 路由跳转

/** 保养计划 列表 */
defineOptions({ name: 'IotMaintenancePlan' })

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

const loading = ref(true) // 列表的加载中
const list = ref<IotMaintenancePlanVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptId: undefined,
  serialNumber: undefined,
  name: undefined,
  responsiblePerson: undefined,
  responsiblePersonName: undefined,
  remark: undefined,
  status: undefined,
  createTime: [],
})

// 响应式变量存储选中的部门
const selectedDept = ref<{ id: number; name: string }>()
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  // 记录选中的部门信息
  selectedDept.value = { id: row.id, name: row.name }
  queryParams.deptId = row.id
  await getList()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotMaintenancePlanApi.getIotMaintenancePlanPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

const detail = (id?: number) => {
  push({ name: 'IotMaintenancePlanDetail', params:{id} })
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  //修改
  if (typeof id === 'number') {
    push({ name: 'IotMainPlanEdit', params: {id } })
    return
  }
  // 新增 保养计划
  push({
    name: 'IotAddMainPlan',
    query: {
      deptId: selectedDept.value?.id,
      deptName: selectedDept.value?.name
    }
  })
}

const handleStatusChange = async (row: IotMaintenancePlanVO) => {
  try {
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用';
    await message.confirm('确认要"' + text + '""' + row.name + '" 保养计划吗?');
    await IotMaintenancePlanApi.updatePlanStatus(row.id, row.status);
    await getList();
  } catch {
    row.status = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE;
  }
};

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

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await IotMaintenancePlanApi.exportIotMaintenancePlan(queryParams)
    download.excel(data, '保养计划.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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