<template>
  <div class="plan-form-page" v-loading="formLoading">
    <header class="page-header">
      <div class="page-header__main">
        <div class="page-header__icon"><Icon icon="ep:calendar" /></div>
        <div>
          <h1>{{ pageTitle }}</h1>
          <p>配置巡检周期、首次执行时间及设备路线顺序</p>
        </div>
      </div>
      <el-button size="default" @click="close">
        <Icon icon="ep:arrow-left" class="mr-5px" />返回
      </el-button>
    </header>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      size="default"
      label-width="110px"
      class="plan-form">
      <section class="form-section">
        <header class="section-heading"><span></span>计划信息</header>
        <div class="form-grid">
          <el-form-item :label="t('main.planName')" prop="planTitle">
            <el-input v-model="formData.planTitle" :placeholder="t('main.nameHolder')" />
          </el-form-item>
          <el-form-item :label="t('workOrderMaterial.unit')" prop="planUnit">
            <el-select
              v-model="formData.planUnit"
              :placeholder="t('route.unitHolder')"
              :disabled="formType === 'update'"
              clearable>
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PMS_INSPECT_UNIT)"
                :key="dict.label"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('route.cycle')" prop="planCycle">
            <el-input-number
              v-model="formData.planCycle"
              :precision="0"
              :min="1"
              :max="99999"
              controls-position="right" />
          </el-form-item>
          <el-form-item :label="t('route.beginCreateTime')" prop="beginCreateTime">
            <el-date-picker
              v-model="formData.beginCreateTime"
              type="datetime"
              value-format="x"
              placeholder="请选择首次执行时间" />
          </el-form-item>
          <el-form-item :label="t('form.remark')" prop="remark" class="form-grid__wide">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注" />
          </el-form-item>
        </div>
      </section>

      <section class="form-section route-section">
        <header class="section-heading section-heading--actions">
          <div class="section-heading__title"><span></span>巡检设备路线</div>
          <el-button size="default" type="primary" @click="openForm">
            <Icon icon="ep:plus" class="mr-5px" />
            {{ t('route.SelectInspectionDevice') }}
          </el-button>
        </header>

        <el-empty v-if="list.length === 0" description="暂未选择巡检设备路线" :image-size="72" />
        <draggable
          v-else
          v-model="list"
          item-key="id"
          tag="div"
          class="sortable-container"
          handle=".sortable-item"
          :animation="150"
          @start="dragStart"
          @end="dragEnd">
          <template #item="{ element, index }">
            <div class="sortable-item">
              <div class="order-number">{{ index + 1 }}</div>
              <span class="drag-handle"><Icon icon="ep:rank" /></span>
              <div class="component-content">
                <div class="item-field">
                  <span class="item-field__label">{{ t('iotDevice.code') }}</span>
                  <span class="item-field__value">{{ element.deviceCode || '-' }}</span>
                </div>
                <div class="item-field">
                  <span class="item-field__label">{{ t('iotDevice.name') }}</span>
                  <span class="item-field__value">{{ element.deviceName || '-' }}</span>
                </div>
                <div class="item-field">
                  <span class="item-field__label">{{ t('route.RouteName') }}</span>
                  <span class="item-field__value">{{ element.routeName || '-' }}</span>
                </div>
              </div>
              <div class="item-actions">
                <el-button link type="primary" @click="viewRoute(element.itemJson)">
                  <Icon icon="ep:view" class="mr-5px" />{{ t('route.InspectionRoute') }}
                </el-button>
                <el-button link type="danger" @click="handleDelete(element.id, element.deviceId)">
                  <Icon icon="ep:delete" class="mr-5px" />{{ t('form.delete') }}
                </el-button>
              </div>
            </div>
          </template>
        </draggable>
      </section>
    </el-form>

    <footer class="action-bar">
      <el-button size="default" @click="close">{{ t('iotMaintain.cancel') }}</el-button>
      <el-button size="default" type="primary" :loading="formLoading" @click="submitForm">
        <Icon icon="ep:check" class="mr-5px" />{{ t('iotMaintain.save') }}
      </el-button>
    </footer>

    <InspectItemList
      ref="inspectItemFormRef"
      :classify="formData.deviceClassify"
      :deviceId="formData.deviceId"
      @choose="inspectItemChoose" />
    <InspectRouteList ref="deviceFormRef" @choose="deviceChoose" />
    <RouteInspectItemDrawer
      ref="showDrawer"
      :model-value="drawerVisible"
      @update:model-value="(val) => (drawerVisible = val)" />
  </div>
</template>
<script setup lang="ts">
import * as UserApi from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'
import { ref } from 'vue'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import InspectItemList from '@/views/pms/inspect/route/InspectItemList.vue'
import InspectRouteList from '@/views/pms/inspect/plan/InspectRouteList.vue'
import { IotInspectRouteVO } from '@/api/pms/inspect/route'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { IotInspectPlanApi, IotInspectPlanVO } from '@/api/pms/inspect/plan'
import RouteInspectItemDrawer from '@/views/pms/inspect/plan/RouteInspectItemDrawer.vue'
import draggable from 'vuedraggable'

/** 维修工单 表单 */
defineOptions({ name: 'InspectPlanAdd' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { currentRoute, push } = useRouter()
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const pageTitle = computed(() => (formType.value === 'update' ? '编辑巡检计划' : '新增巡检计划'))
const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const list = ref<IotInspectRouteVO[]>([]) // 列表的数据
const { params, name } = useRoute() // 查询参数
const id = params.id
const productClassifyList = ref<Tree[]>([]) // 树形结构
const deptUsers = ref<UserApi.UserVO[]>([]) // 用户列表
const formData = ref({
  id: undefined,
  planTitle: undefined,
  planCode: undefined,
  planCycle: undefined,
  beginCreateTime: undefined,
  planUnit: undefined,
  charge: undefined,
  charges: [],
  deviceIds: undefined,
  remark: undefined,
  deptId: undefined
})
const formRules = reactive({
  planTitle: [{ required: true, message: '巡检计划标题不能为空', trigger: 'blur' }],
  planCode: [{ required: true, message: '巡检计划编号不能为空', trigger: 'blur' }],
  planCycle: [{ required: true, message: '周期不能为空', trigger: 'blur' }],
  beginCreateTime: [{ required: true, message: '首次执行时间不能为空', trigger: 'blur' }],
  planUnit: [{ required: true, message: '单位不能为空', trigger: 'blur' }]
  // charges: [{ required: true, message: '负责人不能为空', trigger: 'blur' }]
})
// 拖动状态管理
const items = ref([])
const deviceChoose = (rows) => {
  debugger
  rows.forEach((it) => {
    const ifExist = list.value.find((item) => item.id === it.id && item.deviceId === it.deviceId)
    if (!ifExist) {
      list.value.push(it)
      console.log(JSON.stringify(it))
    }
  })
  // list.value = rows
}
const dragStart = () => {
  document.body.style.cursor = 'grabbing'
}
const dragEnd = (event) => {
  document.body.style.cursor = ''
  console.log(
    '新顺序:',
    items.value.map((c) => c.id)
  )
  console.log('拖拽后的新位置:', event.newIndex + 1)
}
const viewRoute = (itemJson) => {
  drawerVisible.value = true
  showDrawer.value.openDrawer(JSON.parse(itemJson))
}
const formRef = ref() // 表单 Ref
const inspectItemChoose = (rows) => {
  items.value = []
  items.value = rows
}
const deviceFormRef = ref()
const openForm = () => {
  deviceFormRef.value.open()
}

const close = () => {
  delView(unref(currentRoute))
  push({ name: 'IotInspectPlan', params: {} })
  // delView(unref(currentRoute))
  // push({
  //   name: 'IotInspectPlan',
  //   query: {
  //     date: new Date().getTime()
  //   }
  // })
}
const itemsWithIndex = computed(() => {
  return list.value.map((item, index) => ({
    ...item,
    index: index + 1 // 序号从1开始
  }))
})
const { wsCache } = useCache()
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const user = wsCache.get(CACHE_KEY.USER)
    const data = formData.value as unknown as IotInspectPlanVO
    if (formType.value === 'create') {
      //校验是否是已有计划
      const newitems = itemsWithIndex
      formData.value.deviceIds = JSON.stringify(newitems.value)
      if (!formData.value.deptId) {
        formData.value.deptId = user.user.deptId
      }
      await IotInspectPlanApi.createIotInspectPlan(data).then((res) => {})
      message.success(t('common.createSuccess'))
      close()
    } else {
      const newitems = itemsWithIndex
      formData.value.deviceIds = JSON.stringify(newitems.value)
      await IotInspectPlanApi.updateIotInspectPlan(data)
      message.success(t('common.updateSuccess'))
      close()
    }
    //创建定时任务
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
onMounted(async () => {
  const route = useRoute()
  const deptId = useUserStore().getUser.deptId
  formData.value.deptId = Number(route.query.deptId)
  if (route.query.deptName) {
    formData.value.planTitle = `${route.query.deptName} - 巡检计划`
  }
  deptUsers.value = await UserApi.getDeptUsersByDeptId(deptId)
  if (id) {
    formType.value = 'update'
    const iotInspectPlan = await IotInspectPlanApi.getIotInspectPlan(id)
    formData.value = iotInspectPlan
    list.value = JSON.parse(iotInspectPlan.deviceIds)
  } else {
    formType.value = 'create'
  }
})
const handleDelete = async (id: number, deviceId: number) => {
  try {
    debugger
    const index = list.value.findIndex((item) => item.id === id && item.deviceId === deviceId)
    if (index !== -1) {
      // 通过 splice 删除元素
      list.value.splice(index, 1)
    }
  } catch {}
}
</script>
<style scoped>
@media (width <= 1400px) {
  .plan-form-page .form-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .plan-form-page .component-content {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (width <= 768px) {
  .plan-form-page .page-header {
    align-items: flex-start;
  }

  .plan-form-page .page-header p {
    display: none;
  }

  .plan-form-page .form-grid {
    grid-template-columns: minmax(0, 1fr);
    padding: 14px 14px 0;
  }

  .plan-form-page .form-grid__wide {
    grid-column: auto;
  }

  .plan-form-page .section-heading--actions {
    height: auto;
    min-height: 44px;
    padding-top: 6px;
    padding-bottom: 6px;
  }

  .plan-form-page .sortable-item {
    align-items: flex-start;
  }

  .plan-form-page .drag-handle {
    padding-right: 8px;
    padding-left: 8px;
  }

  .plan-form-page .component-content {
    grid-template-columns: minmax(0, 1fr);
    gap: 6px;
  }

  .plan-form-page .item-actions {
    flex-direction: column;
    align-items: flex-end;
  }

  .plan-form-page .item-actions :deep(.el-button + .el-button) {
    margin-left: 0;
  }
}

.plan-form-page {
  display: flex;
  min-height: calc(
    100vh - 20px - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)
  );
  flex-direction: column;
  gap: 12px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 66px;
  padding: 12px 16px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.page-header__main {
  display: flex;
  align-items: center;
  min-width: 0;
}

.page-header__icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 38px;
  height: 38px;
  margin-right: 12px;
  font-size: 18px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 8px;
}

.page-header h1 {
  margin: 0;
  font-size: 17px;
  font-weight: 600;
  line-height: 24px;
  color: var(--el-text-color-primary);
}

.page-header p {
  margin: 1px 0 0;
  font-size: 12px;
  line-height: 18px;
  color: var(--el-text-color-secondary);
}

.plan-form {
  display: flex;
  min-height: 0;
  flex: 1;
  flex-direction: column;
  gap: 12px;
}

.form-section {
  overflow: hidden;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-lighter);
}

.section-heading {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 16px;
  font-size: 15px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  background: var(--el-fill-color-extra-light);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.section-heading > span,
.section-heading__title > span {
  width: 4px;
  height: 17px;
  margin-right: 9px;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.section-heading--actions {
  justify-content: space-between;
}

.section-heading__title {
  display: flex;
  align-items: center;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  column-gap: 24px;
  padding: 18px 18px 2px;
}

.form-grid__wide {
  grid-column: 1 / -1;
}

.plan-form :deep(.el-form-item) {
  margin-bottom: 16px;
}

.plan-form :deep(.el-input),
.plan-form :deep(.el-input-number),
.plan-form :deep(.el-select),
.plan-form :deep(.el-date-editor) {
  width: 100%;
}

.route-section {
  display: flex;
  min-height: 280px;
  flex: 1;
  flex-direction: column;
}

.route-section :deep(.el-empty) {
  flex: 1;
}

.sortable-container {
  display: flex;
  min-height: 0;
  padding: 14px;
  overflow-y: auto;
  cursor: default;
  flex: 1;
  flex-direction: column;
  gap: 10px;
}

.sortable-item {
  display: flex;
  min-height: 60px;
  padding: 10px 12px;
  cursor: grab;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  align-items: center;
  transition:
    border-color 0.2s ease,
    box-shadow 0.2s ease;
  user-select: none;
}

.sortable-item:hover {
  border-color: var(--el-color-primary-light-7);
  box-shadow: 0 3px 10px rgb(0 0 0 / 6%);
}

.sortable-item:active {
  cursor: grabbing;
}

.order-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  height: 26px;
  margin-right: 2px;
  font-size: 13px;
  font-weight: 600;
  color: #fff;
  background: var(--el-color-primary);
  border-radius: 50%;
  flex: 0 0 auto;
}

.drag-handle {
  display: flex;
  padding: 8px 12px;
  font-size: 18px;
  color: var(--el-text-color-placeholder);
  cursor: grab;
}

.component-content {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  min-width: 0;
  flex: 1;
  gap: 16px;
}

.item-field {
  display: flex;
  min-width: 0;
  align-items: flex-start;
}

.item-field__label {
  margin-right: 8px;
  font-weight: 600;
  color: var(--el-text-color-regular);
  white-space: nowrap;
}

.item-field__value {
  min-width: 0;
  color: var(--el-text-color-secondary);
  overflow-wrap: anywhere;
}

.item-actions {
  display: flex;
  align-items: center;
  margin-left: 16px;
  flex: 0 0 auto;
}

.action-bar {
  position: sticky;
  bottom: 0;
  z-index: 5;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  min-height: 56px;
  padding: 10px 16px;
  margin-top: auto;
  background: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 -4px 12px rgb(0 0 0 / 5%);
}
</style>
