<template>
  <el-row :gutter="20">
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />

    <el-col :xs="24" :span="isLeftContentCollapsed ? 24 : 20">
      <div
        style="border: none; background: #fff; display: flex; align-items: center"
        class="py-2 rounded-sm px-2"
      >
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item :label="t('main.planName')" prop="planTitle" style="margin-left: 25px">
            <el-input
              v-model="queryParams.planTitle"
              :placeholder="t('main.nameHolder')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-180px"
            />
          </el-form-item>
          <el-form-item :label="t('main.planCode')" prop="planCode">
            <el-input
              v-model="queryParams.planCode"
              :placeholder="t('main.codeHolder')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-180px"
            />
          </el-form-item>
          <el-form-item :label="t('common.createTime')" prop="createTime" label-width="100px">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              :start-placeholder="t('info.start')"
              :end-placeholder="t('info.end')"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-180px"
            />
          </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-inspect-plan:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.add') }}
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['rq:iot-inspect-plan:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 列表 -->
      <ContentWrap style="border: none; margin-top: 20px">
        <zm-table :loading="loading" :data="list" height="calc(85vh - 175px)">
          <el-table-column :label="t('iotDevice.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <zm-table-column :label="t('route.planTitle')" align="center" prop="planTitle" />
          <!--          <el-table-column :label="t('route.planNumber')" align="center" prop="planCode" min-width="200" />-->
          <zm-table-column
            :label="t('route.cycle')"
            align="center"
            prop="planCycle"
            min-width="80"
          />
          <zm-table-column
            :label="t('workOrderMaterial.unit')"
            align="center"
            prop="planUnit"
            min-width="80"
          >
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.PMS_INSPECT_UNIT" :value="scope.row.planUnit" />
            </template>
          </zm-table-column>
          <zm-table-column
            :label="t('bomList.status')"
            prop="status"
            column-key="status"
            min-width="80"
          >
            <template #default="scope">
              <el-switch
                :model-value="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                @change="(value) => handleStatusChange(scope.row, value)"
              />
            </template>
          </zm-table-column>
          <zm-table-column
            :label="t('route.beginCreateTime')"
            align="center"
            prop="beginCreateTime"
            :formatter="dateFormatter"
            min-width="180px"
          />
          <zm-table-column
            :label="t('route.lastCreateTime')"
            align="center"
            prop="lastCreateTime"
            :formatter="dateFormatter"
            min-width="180px"
          />
          <zm-table-column
            :label="t('iotDevice.dept')"
            align="center"
            prop="deptName"
            min-width="130"
          />
          <zm-table-column
            :label="t('inspect.createName')"
            align="center"
            prop="createName"
            min-width="130"
          />
          <zm-table-column
            :label="t('operationFill.operation')"
            align="center"
            min-width="120"
            fixed="right"
            action
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['rq:iot-operation-plan:update']"
              >
                {{ t('fault.edit') }}
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['rq:iot-operation-plan:delete']"
              >
                {{ t('fault.del') }}
              </el-button>
            </template>
          </zm-table-column>
        </zm-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>
  <!-- 表单弹窗：添加/修改 -->
  <IotOperationPlanForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { IotOperationPlanApi, IotOperationPlanVO } from '@/api/pms/iotopeationfill/plan'
import IotOperationPlanForm from './IotOperationPlanForm.vue'
import { CommonStatusEnum } from '@/utils/constants'
import { DICT_TYPE } from '@/utils/dict'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'

import { useTableComponents } from '@/components/ZmTable/useTableComponents'
const { ZmTable, ZmTableColumn } = useTableComponents()

defineOptions({ name: 'iotOperationPlan' })
const message = useMessage() // 消息弹窗

const { push } = useRouter()
const { t } = useI18n()

const loading = ref(true)
const list = ref<IotOperationPlanVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  planTitle: undefined,
  planCode: undefined,
  planCycle: undefined,
  planUnit: undefined,
  charge: undefined,
  deviceIds: undefined,
  remark: undefined,
  createTime: [],
  deptId: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

const isLeftContentCollapsed = ref(false)
const hoverText = ref('')
const selectedDept = ref<{ id: number; name: string }>()

const handleDeptNodeClick = async (row) => {
  selectedDept.value = { id: row.id, name: row.name }
  queryParams.deptId = row.id
  await getList()
}

const handleStatusChange = async (row: IotOperationPlanVO, value: number) => {
  // 如果还未初始化完成，直接返回
  if (!isInitialized.value) {
    return
  }
  const previousStatus = row.status
  if (previousStatus === value) {
    return
  }
  try {
    const text = value === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.planTitle + '"巡检计划吗?')
    row.status = value
    await IotOperationPlanApi.updateIotOperationStatus(row.id, value)
    await getList()
  } catch {
    row.status = previousStatus
  }
}

const isInitialized = ref(false)
const getList = async () => {
  loading.value = true
  try {
    const data = await IotOperationPlanApi.getIotOperationPlanPage(queryParams)
    list.value = data.list
    total.value = data.total
    setTimeout(() => {
      isInitialized.value = true
    }, 100)
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  selectedDept.value = undefined
  handleQuery()
}

const openForm = (type: string, id?: number) => {
  if (typeof id === 'number') {
    push({ name: 'OperationPlanEdit', params: { id } })
    return
  }
  push({
    name: 'OperationPlanAdd',
    query: {
      deptId: selectedDept.value?.id,
      deptName: selectedDept.value?.name
    }
  })
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await IotOperationPlanApi.deleteIotOperationPlan(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await IotOperationPlanApi.exportIotOperationPlan(queryParams)
    download.excel(data, '巡检计划.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const toggleLeftContent = () => {
  isLeftContentCollapsed.value = !isLeftContentCollapsed.value
}

const handleMouseOver = () => {
  hoverText.value = isLeftContentCollapsed.value ? '展开' : '收起'
}

const handleMouseOut = () => {
  hoverText.value = ''
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.leftcontent {
  transition: width 0.3s ease;
  position: relative;
}

.leftcontent.collapsed {
  width: 0;
  overflow: hidden;
}

.rightcontent {
  position: relative;
}

.toggle-button {
  position: absolute;
  top: 44%;
  transform: translate(-65%, -50%);
  width: 12px;
  height: 40px;
  background-color: #f0f0f0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
  clip-path: polygon(0 0, 100% 18%, 100% 85%, 0 100%);
  border-radius: 8px;
}

/* 添加鼠标悬停样式 */
.toggle-button:hover {
  background-color: #afafaf;
}

.triangle {
  width: 0;
  height: 0;
  border-top: 4px solid transparent;
  border-bottom: 4px solid transparent;
  transition: transform 0.4s ease;
  border-right: 5px solid gray; /* 修改为右边框显示颜色 */
  border-left: none; /* 移除左边框 */
}

.triangle.rotated {
  transform: rotate(180deg);
}
</style>
