<template>
  <ContentWrap v-loading="formLoading">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
      style="margin-top: 1em; margin-right: 4em; margin-left: 0.5em"
      label-width="130px">
      <div class="base-expandable-content">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="t('bomList.name')" prop="name">
              <!--              <el-input type="text" v-model="formData.name" />-->
              <lang-input v-model="formData.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="填报人" prop="applicant">
              <el-input v-model="formData.applicant" placeholder="请输入填报人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('mainPlan.MaintenanceMethod')" prop="type">
              <el-select
                v-model="formData.outsourcingFlag"
                :placeholder="t('faultForm.choose')"
                clearable>
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.PMS_ORDER_PROCESS_MODE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('mainPlan.MaintenanceCost')" prop="cost">
              <el-input v-model="formData.cost" placeholder="根据物料消耗自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('fault.start')" prop="actualStartTime">
              <el-date-picker
                style="width: 150%"
                v-model="formData.actualStartTime"
                type="datetime"
                value-format="x"
                :placeholder="t('fault.start')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('fault.end')" prop="actualEndTime">
              <el-date-picker
                style="width: 150%"
                v-model="formData.actualEndTime"
                type="datetime"
                value-format="x"
                :placeholder="t('fault.end')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('mainPlan.otherCost')" prop="otherCost">
              <el-input
                v-model="formData.otherCost"
                @input="handleInput(formData.otherCost, 'otherCost')"
                placeholder="其他费用" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="t('faultForm.remark')" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :placeholder="t('faultForm.rHolder')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="附件">
              <FileUpload
                class="work-order-attachment-upload"
                :device-id="undefined"
                :show-folder-button="false"
                @upload-success="handleUploadSuccess" />

              <div
                v-if="formData.attachments && formData.attachments.length > 0"
                class="attachment-container">
                <div class="attachment-list">
                  <div
                    v-for="(attachment, index) in formData.attachments"
                    :key="attachment.id || index"
                    class="attachment-item">
                    <a class="attachment-name" @click="inContent(attachment)">
                      {{ attachment.filename }}
                    </a>
                    <el-button type="danger" link size="small" @click="removeAttachment(index)">
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
              <div
                v-else-if="!formData.attachments || formData.attachments.length === 0"
                class="no-attachment">
                无附件
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px">
        <el-form-item>
          <el-button @click="openForm" type="warning">
            <Icon icon="ep:plus" class="mr-5px" />
            {{ t('maintain.added') }}</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 type="index" :label="t('maintain.serial')" width="70" align="center" />
        <el-table-column
          :label="t('bomList.bomNode')"
          align="center"
          prop="bomNodeId"
          v-if="false" />
        <el-table-column :label="t('iotDevice.code')" align="center" prop="deviceCode" />
        <el-table-column :label="t('iotDevice.name')" align="center" prop="deviceName" />
        <el-table-column
          :label="t('operationFillForm.sumTime')"
          align="center"
          prop="totalRunTime"
          :formatter="erpPriceTableColumnFormatter" />
        <el-table-column
          :label="t('operationFillForm.sumKil')"
          align="center"
          prop="totalMileage"
          :formatter="erpPriceTableColumnFormatter" />
        <el-table-column :label="t('mainPlan.MaintItems')" align="center" prop="name" />
        <el-table-column :label="t('iotMaintain.numberOfMaterials')" align="center" width="100">
          <template #default="scope">
            {{ getMaterialCount(scope.row.bomNodeId) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('iotMaintain.operation')" align="center" min-width="120px">
          <template #default="scope">
            <div style="display: flex; justify-content: center; align-items: center; width: 100%">
              <div>
                <Icon style="color: #ea3434; vertical-align: middle" icon="ep:zoom-out" />
                <el-button
                  style="vertical-align: middle"
                  link
                  type="danger"
                  @click="handleDelete(scope.row.deviceId + '-' + scope.row.bomNodeId)">
                  {{ t('iotMaintain.remove') }}
                </el-button>
              </div>
              <div style="margin-left: 12px">
                <el-button link type="primary" @click="openMaterialForm(scope.row)">
                  {{ t('iotMaintain.selectMaterials') }}
                </el-button>
              </div>
              <div style="margin-left: 12px">
                <el-button link type="primary" @click="handleView(scope.row.bomNodeId)">
                  {{ t('bomList.materialDetail') }}
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>

    <!-- 选择的物料列表 -->
    <ContentWrap>
      <el-table
        v-loading="false"
        :data="materialList"
        :stripe="true"
        :show-overflow-tooltip="true"
        v-if="false">
        <el-table-column :label="t('bomList.bomNode')" align="center" prop="bomNodeId" />
        <el-table-column
          :label="t('workOrderMaterial.materialCode')"
          align="center"
          prop="materialCode" />
        <el-table-column
          :label="t('workOrderMaterial.materialName')"
          align="center"
          prop="materialName" />
        <el-table-column :label="t('workOrderMaterial.unit')" align="center" prop="unit" />
        <el-table-column
          :label="t('workOrderMaterial.unitPrice')"
          align="center"
          prop="unitPrice"
          :formatter="erpPriceTableColumnFormatter" />
        <el-table-column
          :label="t('workOrderMaterial.ConsumptionQuantity')"
          align="center"
          prop="quantity" />
        <el-table-column
          :label="t('workOrderMaterial.total')"
          align="center"
          prop="totalInventoryQuantity" />
      </el-table>
    </ContentWrap>
  </ContentWrap>
  <ContentWrap>
    <el-form>
      <el-form-item style="float: right">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">{{
          t('common.save')
        }}</el-button>
        <el-button @click="close">{{ t('common.cancel') }}</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <MainPlanDeviceList ref="deviceFormRef" @choose="deviceChoose" />
  <!-- 新增配置对话框 -->
  <el-dialog
    v-model="configDialog.visible"
    :title="`设备 ${configDialog.current?.deviceCode + '-' + configDialog.current?.name} 保养配置`"
    width="600px">
    <!-- 使用header插槽自定义标题 -->
    <template #header>
      <span
        >设备
        <strong>{{ configDialog.current?.deviceCode }}-{{ configDialog.current?.name }}</strong>
        保养项配置</span
      >
    </template>
    <el-form
      :model="configDialog.form"
      label-width="200px"
      :rules="configFormRules"
      ref="configFormRef">
      <!-- 里程配置 -->
      <el-form-item
        v-if="configDialog.current?.mileageRule === 0"
        label="上次保养里程数(KM)"
        prop="lastRunningKilometers">
        <el-input-number
          v-model="configDialog.form.lastRunningKilometers"
          :precision="2"
          :min="0"
          controls-position="right"
          :disabled="true" />
      </el-form-item>
      <!-- 推迟公里数 -->
      <el-form-item
        v-if="configDialog.current?.mileageRule === 0"
        label="推迟公里数(KM)"
        prop="delayKilometers">
        <el-input-number
          v-model="configDialog.form.delayKilometers"
          :precision="2"
          :min="0"
          controls-position="right" />
      </el-form-item>
      <!-- 运行时间配置 -->
      <el-form-item
        v-if="configDialog.current?.runningTimeRule === 0"
        label="上次保养运行时间(H)"
        prop="lastRunningTime">
        <el-input-number
          v-model="configDialog.form.lastRunningTime"
          :precision="1"
          :min="0"
          controls-position="right"
          :disabled="true" />
      </el-form-item>
      <!-- 推迟时长 -->
      <el-form-item
        v-if="configDialog.current?.runningTimeRule === 0"
        label="推迟时长(H)"
        prop="delayDuration">
        <el-input-number
          v-model="configDialog.form.delayDuration"
          :precision="2"
          :min="0"
          controls-position="right" />
      </el-form-item>
      <!-- 自然日期配置 -->
      <el-form-item
        v-if="configDialog.current?.naturalDateRule === 0"
        label="上次保养自然日期(D)"
        prop="lastNaturalDate">
        <el-date-picker
          v-model="configDialog.form.lastNaturalDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled="true" />
      </el-form-item>
      <!-- 推迟自然日期 -->
      <el-form-item
        v-if="configDialog.current?.naturalDateRule === 0"
        label="推迟自然日期(D)"
        prop="delayNaturalDate">
        <el-input-number
          v-model="configDialog.form.delayNaturalDate"
          :precision="2"
          :min="0"
          controls-position="right" />
      </el-form-item>
      <!-- 保养规则周期值 + 提前量 -->
      <el-form-item
        v-if="configDialog.current?.mileageRule === 0"
        label="运行里程周期(KM)"
        prop="nextRunningKilometers">
        <el-input-number
          v-model="configDialog.form.nextRunningKilometers"
          :precision="2"
          :min="0"
          controls-position="right"
          :disabled="true" />
      </el-form-item>
      <el-form-item
        v-if="configDialog.current?.mileageRule === 0"
        label="运行里程周期-提前量(KM)"
        prop="kiloCycleLead">
        <el-input-number
          v-model="configDialog.form.kiloCycleLead"
          :precision="2"
          :min="0"
          controls-position="right"
          :disabled="true" />
      </el-form-item>
      <el-form-item
        v-if="configDialog.current?.runningTimeRule === 0"
        label="运行时间周期(H)"
        prop="nextRunningTime">
        <el-input-number
          v-model="configDialog.form.nextRunningTime"
          :precision="1"
          :min="0"
          controls-position="right"
          :disabled="true" />
      </el-form-item>
      <el-form-item
        v-if="configDialog.current?.runningTimeRule === 0"
        label="运行时间周期-提前量(H)"
        prop="timePeriodLead">
        <el-input-number
          v-model="configDialog.form.timePeriodLead"
          :precision="1"
          :min="0"
          controls-position="right"
          :disabled="true" />
      </el-form-item>
      <el-form-item
        v-if="configDialog.current?.naturalDateRule === 0"
        label="自然日周期(D)"
        prop="nextNaturalDate">
        <el-input-number
          v-model="configDialog.form.nextNaturalDate"
          :min="0"
          controls-position="right"
          :disabled="true" />
      </el-form-item>
      <el-form-item
        v-if="configDialog.current?.naturalDateRule === 0"
        label="自然日周期-提前量(D)"
        prop="naturalDatePeriodLead">
        <el-input-number
          v-model="configDialog.form.naturalDatePeriodLead"
          :min="0"
          controls-position="right"
          :disabled="true" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="configDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="saveConfig">保存</el-button>
    </template>
  </el-dialog>
  <!-- 表单弹窗：添加/修改 -->
  <WorkOrderMaterial ref="materialFormRef" @choose="selectChoose" />
  <!-- 抽屉组件 展示已经选择的物料 并编辑物料消耗 -->
  <MaterialListDrawer
    :model-value="drawerVisible"
    @update:model-value="(val) => (drawerVisible = val)"
    :node-id="currentBomNodeId"
    :materials="materialList.filter((item) => item.bomNodeId === currentBomNodeId)"
    @delete="handleMaterialDelete" />
</template>
<script setup lang="ts">
import { IotDeviceApi } from '@/api/pms/device'
import * as UserApi from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'
import { ref } from 'vue'
import { IotMaintenanceBomVO } from '@/api/pms/iotmaintenancebom'
import { IotMainWorkOrderBomVO } from '@/api/pms/iotmainworkorderbom'
import { IotMainWorkOrderBomMaterialVO } from '@/api/pms/iotmainworkorderbommaterial'
import { IotMainWorkOrderApi } from '@/api/pms/iotmainworkorder'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import MainPlanDeviceList from '@/views/pms/maintenance/maintenance-device-list.vue'
import * as DeptApi from '@/api/system/dept'
import { erpPriceTableColumnFormatter } from '@/utils'
import dayjs from 'dayjs'
import MaterialListDrawer from '@/views/pms/iotmainworkorder/SelectedMaterialDrawer.vue'
import WorkOrderMaterial from '@/views/pms/iotmainworkorder/WorkOrderMaterial.vue'
import { IotDevicePersonApi } from '@/api/pms/iotdeviceperson'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import FileUpload from '@/components/UploadFile/src/FileUpload.vue'
import { Base64 } from 'js-base64'

/** 保养计划 表单 */
defineOptions({ name: 'IotMainWorkOrderAdd' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { currentRoute, push } = useRouter()
const deptUsers = ref<UserApi.UserVO[]>([]) // 用户列表
const dept = ref() // 当前登录人所属部门对象
const configFormRef = ref() // 配置弹出框对象
const bomNodeId = ref() // 最新的bomNodeId
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const deviceLabel = ref('') // 表单的类型：create - 新增；update - 修改
const drawerVisible = ref<boolean>(false)
const currentBomNodeId = ref() // 当前选中的bom节点
const showDrawer = ref()
const list = ref<IotMainWorkOrderBomVO[]>([]) // 保养工单bom关联列表的数据
const materialList = ref<IotMainWorkOrderBomMaterialVO[]>([]) // 保养工单bom关联物料列表
const deviceIds = ref<number[]>([]) // 已经选择的设备id数组
const { params, name } = useRoute() // 查询参数
const id = params.id
const devicePersonsMap = ref<Map<number, Set<string>>>(new Map()) // 存储设备-责任人映射

const formData = ref({
  id: undefined,
  deptId: undefined,
  name: '',
  applicant: undefined,
  orderNumber: undefined,
  responsiblePerson: undefined,
  actualStartTime: undefined,
  actualEndTime: undefined,
  cost: undefined,
  otherCost: undefined,
  outsourcingFlag: 0,
  remark: undefined,
  status: undefined,
  devicePersons: '',
  attachments: [] as any[]
})

const getFileType = (filename: string) => {
  const ext = filename.split('.').pop()?.toLowerCase()
  if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext || '')) {
    return 'image'
  } else if (['pdf'].includes(ext || '')) {
    return 'pdf'
  } else if (['doc', 'docx'].includes(ext || '')) {
    return 'word'
  } else if (['xls', 'xlsx'].includes(ext || '')) {
    return 'excel'
  }
  return 'other'
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleUploadSuccess = (result: any) => {
  try {
    if (!result.response) {
      message.error('上传响应数据异常')
      return
    }

    if (result.response.code !== 0) {
      message.error(result.response.msg || '文件上传失败')
      return
    }

    const responseData = result.response.data

    if (!responseData) {
      message.error('上传数据为空')
      return
    }

    if (responseData.files && Array.isArray(responseData.files) && responseData.files.length > 0) {
      responseData.files.forEach((file: any) => {
        if (!file.filePath) {
          return
        }

        const attachment = {
          id: undefined,
          category: 'main_work_order',
          bizId: formData.value.id,
          type: 'attachment',
          filename: file.name || '未知文件',
          fileType: getFileType(file.name),
          filePath: file.filePath,
          fileSize: formatFileSize(file.size || 0),
          remark: ''
        }

        if (!formData.value.attachments) {
          formData.value.attachments = []
        }
        formData.value.attachments.push(attachment)
      })

      message.success(`成功上传 ${responseData.files.length} 个文件`)
    } else {
      message.warning('上传成功但未获取到文件信息')
    }
  } catch (error) {
    message.error('处理上传结果失败')
  }
}

const removeAttachment = (index: number) => {
  if (formData.value.attachments && formData.value.attachments.length > index) {
    formData.value.attachments.splice(index, 1)
  }
}

const inContent = async (attachment: any) => {
  if (!attachment || !attachment.filePath) {
    message.error('附件路径不存在')
    return
  }

  try {
    const encodedPath = encodeURIComponent(Base64.encode(attachment.filePath))
    window.open(`http://doc.deepoil.cc:8012/onlinePreview?url=${encodedPath}`)
  } catch (error) {
    message.error('预览附件失败')
  }
}

/** 获取当前所有设备ID集合 */
const getCurrentDeviceIds = (): number[] => {
  return [...new Set(list.value.map((item) => item.deviceId))]
}

const formRules = reactive({
  name: [{ required: true, message: '工单名称不能为空', trigger: 'blur' }],
  applicant: [{ required: true, message: '填报人不能为空', trigger: 'blur' }],
  actualStartTime: [
    {
      required: true,
      message: t('fault.start') + '不能为空',
      trigger: 'change'
    },
    {
      validator: (rule, value, callback) => {
        const now = dayjs()
        const start = value ? dayjs(Number(value)) : null

        // 验证开始时间 <= 当前日期
        if (start && start.isAfter(now)) {
          callback(new Error(t('fault.start') + '不能超过当前日期'))
          return
        }

        const end = formData.value.actualEndTime
          ? dayjs(Number(formData.value.actualEndTime))
          : null

        // 只有当结束时间有效时，才比较开始和结束时间
        if (end && end.isValid() && !end.isAfter(now)) {
          if (start && start.isAfter(end)) {
            callback(new Error(t('fault.start') + '不能超过' + t('fault.end')))
            return
          }
        }

        // 触发结束时间的重新校验
        if (formRef.value) {
          formRef.value.validateField('actualEndTime', () => {})
        }

        callback()
      },
      trigger: 'change'
    }
  ],
  actualEndTime: [
    {
      required: true,
      message: t('fault.end') + '不能为空',
      trigger: 'change'
    },
    {
      validator: (rule, value, callback) => {
        const now = dayjs()
        const end = value ? dayjs(Number(value)) : null

        // 验证结束时间 <= 当前日期
        if (end && end.isAfter(now)) {
          callback(new Error(t('fault.end') + '不能超过当前日期'))
          return
        }

        const start = formData.value.actualStartTime
          ? dayjs(Number(formData.value.actualStartTime))
          : null

        // 验证结束时间 >= 开始时间（仅当开始时间存在时）
        if (start && end && end.isBefore(start)) {
          callback(new Error(t('fault.end') + '必须大于等于' + t('fault.start')))
          return
        }

        callback()
      },
      trigger: 'change'
    }
  ]
})

const formRef = ref() // 表单 Ref

interface MaterialFormExpose {
  open: (deptId: number, bomNodeId: number, row: any, type: string) => void
}

const materialFormRef = ref<MaterialFormExpose>()

// 新增配置相关状态
const configDialog = reactive({
  visible: false,
  current: null as IotMaintenanceBomVO | null,
  form: {
    lastRunningKilometers: 0,
    delayKilometers: 0,
    lastRunningTime: 0,
    delayDuration: 0,
    lastNaturalDate: '',
    delayNaturalDate: 0,
    // 保养规则 周期
    nextRunningKilometers: 0,
    nextRunningTime: 0,
    nextNaturalDate: 0,
    // 提前量
    kiloCycleLead: 0,
    timePeriodLead: 0,
    naturalDatePeriodLead: 0
  }
})

// 监听物料列表变化
watch(
  () => materialList.value,
  () => {
    calculateTotalCost()
  },
  { deep: true }
)

// 计算保养金额
const calculateTotalCost = () => {
  // 物料总金额 = ∑(单价 * 消耗数量)
  const materialTotal = materialList.value.reduce((sum, item) => {
    const price = Number(item.unitPrice) || 0
    const quantity = Number(item.quantity) || 0
    return sum + price * quantity
  }, 0)

  // 保养 = 物料总金额
  formData.value.cost = materialTotal.toFixed(2)
}

// 打开配置对话框
const openConfigDialog = (row: IotMainWorkOrderBomVO) => {
  configDialog.current = row

  // 处理日期初始化（核心修改）
  let initialDate = ''
  if (row.lastNaturalDate) {
    // 如果已有值：时间戳 -> 日期字符串
    initialDate = dayjs(row.lastNaturalDate).format('YYYY-MM-DD')
  } else {
    // 如果无值：设置默认值避免1970问题
    initialDate = ''
  }

  configDialog.form = {
    lastRunningKilometers: row.lastRunningKilometers || 0,
    delayKilometers: row.delayKilometers || 0,
    lastRunningTime: row.lastRunningTime || 0,
    delayDuration: row.delayDuration || 0,
    lastNaturalDate: initialDate,
    delayNaturalDate: row.delayNaturalDate || 0,
    // 保养规则 周期值
    nextRunningKilometers: row.nextRunningKilometers || 0,
    nextRunningTime: row.nextRunningTime || 0,
    nextNaturalDate: row.nextNaturalDate || 0,
    // 提前量
    kiloCycleLead: row.kiloCycleLead || 0,
    timePeriodLead: row.timePeriodLead || 0,
    naturalDatePeriodLead: row.naturalDatePeriodLead || 0
  }
  configDialog.visible = true
}

// const materialFormRef = ref()
const openMaterialForm = (row: any) => {
  bomNodeId.value = row.bomNodeId
  console.log('这是一个对象：', row.bomNodeId)
  const type = 'maintenance'
  materialFormRef.value.open(formData.value.deptId, bomNodeId.value, row, type)
}

// 获取指定bomNodeId的物料数量
const getMaterialCount = (bomNodeId: number) => {
  return materialList.value.filter((item) => item.bomNodeId === bomNodeId).length
}

const selectChoose = (selectedMaterial) => {
  selectedMaterial.bomNodeId = bomNodeId.value
  // 关联 bomNodeId
  const processedMaterials = selectedMaterial.map((material) => ({
    ...material,
    bomNodeId: bomNodeId.value // 统一关联当前行的 bomNodeId
  }))

  // 避免重复添加
  processedMaterials.forEach((newMaterial) => {
    // 检查是否已存在相同 bomNodeId + materialCode 的条目
    const isExist = materialList.value.some(
      (item) => item.bomNodeId === bomNodeId.value && item.materialCode === newMaterial.materialCode
    )

    if (!isExist) {
      materialList.value.push(newMaterial)
    }
  })
}

// 新增方法：动态更新工单名称
function updateWorkOrderName() {
  if (list.value.length > 0) {
    const firstDevice = list.value[0]
    const currentDate = dayjs().format('YYYY-MM-DD')
    formData.value.name = `${firstDevice.deviceCode} - ${firstDevice.deviceName} - ${currentDate} 保养工单`
  } else {
    formData.value.name = `${dept.value.name} - 保养工单`
  }
}

const deviceChoose = async (selectedDevices) => {
  const newIds = selectedDevices.map((device) => device.id)
  deviceIds.value = [...new Set([...deviceIds.value, ...newIds])]
  const params = {
    deviceIds: deviceIds.value.join(',') // 明确传递数组参数
  }
  queryParams.deviceIds = JSON.parse(JSON.stringify(params.deviceIds))
  queryParams.bomFlag = 'b'
  // 根据选择的设备筛选出设备关系的分类BOM中与保养相关的节点项
  const res = await IotDeviceApi.deviceAssociateBomList(queryParams)
  const rawData = res || []
  if (rawData.length === 0) {
    message.error('选择的设备不存在待保养BOM项')
  }
  if (!Array.isArray(rawData)) {
    console.error('接口返回数据结构异常:', rawData)
    return
  }
  // 转换数据结构（根据你的接口定义调整）
  const newItems = rawData.map((device) => ({
    assetClass: device.assetClass,
    deviceCode: device.deviceCode,
    deviceName: device.deviceName,
    deviceStatus: device.deviceStatus,
    deptName: device.deptName,
    name: device.name,
    code: device.code,
    assetProperty: device.assetProperty,
    remark: null, // 初始化备注
    deviceId: device.id, // 移除操作需要
    bomNodeId: device.bomNodeId,
    totalRunTime: device.totalRunTime,
    totalMileage: device.totalMileage,
    nextRunningKilometers: 0,
    nextRunningTime: 0,
    nextNaturalDate: 0,
    lastNaturalDate: null, // 初始化为null而不是0
    // 保养规则 提前量
    kiloCycleLead: 0,
    timePeriodLead: 0,
    naturalDatePeriodLead: 0
  }))
  // 获取选择的设备相关的id数组
  newItems.forEach((item) => {
    deviceIds.value.push(item.deviceId)
  })
  // 合并到现有列表（去重）
  newItems.forEach((item) => {
    const exists = list.value.some(
      (existing) => existing.deviceId === item.deviceId && existing.bomNodeId === item.bomNodeId
    )
    if (!exists) {
      list.value.push(item)
    }
  })
  // 更新工单名称
  updateWorkOrderName()
}

/** 查看已经选择的物料 并编辑 */
const handleView = (nodeId) => {
  currentBomNodeId.value = nodeId
  drawerVisible.value = true
  // showDrawer.value.openDrawer()
  console.log('当前bom节点：', currentBomNodeId.value)
}

const deviceFormRef = ref<InstanceType<typeof MainPlanDeviceList>>()
const openForm = () => {
  deviceFormRef.value?.open()
}

const hasMaterial = (bomNodeId: number) => {
  return materialList.value.some((item) => item.bomNodeId === bomNodeId)
}

// 保存配置
const saveConfig = () => {
  ;(configFormRef.value as any).validate((valid: boolean) => {
    if (!valid) return
    if (!configDialog.current) return

    // 动态校验逻辑
    const requiredFields = []
    if (configDialog.current.mileageRule === 0) {
      requiredFields.push('nextRunningKilometers', 'kiloCycleLead')
    }
    if (configDialog.current.runningTimeRule === 0) {
      requiredFields.push('nextRunningTime', 'timePeriodLead')
    }
    if (configDialog.current.naturalDateRule === 0) {
      requiredFields.push('nextNaturalDate', 'naturalDatePeriodLead')
    }

    const missingFields = requiredFields.filter(
      (field) => !configDialog.form[field as keyof typeof configDialog.form]
    )

    if (missingFields.length > 0) {
      message.error('请填写所有必填项')
      return
    }

    // 强制校验逻辑
    if (configDialog.current.naturalDateRule === 0) {
      if (!configDialog.form.lastNaturalDate) {
        message.error('必须选择 上次保养自然日期')
        return
      }

      // 验证日期有效性
      const dateValue = dayjs(configDialog.form.lastNaturalDate)
      if (!dateValue.isValid()) {
        message.error('日期格式不正确')
        return
      }
    }

    // 转换逻辑（关键修改）
    const finalDate = configDialog.form.lastNaturalDate
      ? dayjs(configDialog.form.lastNaturalDate).valueOf()
      : null // 改为null而不是0

    // 更新当前行的数据
    Object.assign(configDialog.current, {
      ...configDialog.form,
      lastNaturalDate: finalDate
    })
    configDialog.visible = false
  })
}

const handleInput = (value, obj) => {
  // 1. 过滤非法字符（只允许数字和小数点）
  let filtered = value.replace(/[^\d.]/g, '')

  // 2. 处理多个小数点的情况
  filtered = filtered.replace(/\.{2,}/g, '.')

  // 3. 限制小数点后最多两位
  let decimalParts = filtered.split('.')
  if (decimalParts.length > 1) {
    decimalParts = decimalParts.slice(0, 2)
    filtered = decimalParts.join('.')
  }

  // 4. 处理以小数点开头的情况（自动补0）
  if (filtered.startsWith('.')) {
    filtered = '0' + filtered
  }

  // 5. 更新绑定值（同时处理连续输入多个0的情况）
  formData.value[obj] = filtered.replace(/^0+(?=\d)/, '')
}

const queryParams = reactive({
  deviceIds: undefined,
  workOrderId: id,
  bomFlag: 'b'
})

const close = () => {
  delView(unref(currentRoute))
  push({ name: 'IotMainWorkOrder', params: {} })
}

// 添加处理物料删除的方法
const handleMaterialDelete = (row: any) => {
  // 找到要删除的物料索引
  const index = materialList.value.findIndex(
    (item) => item.bomNodeId === row.bomNodeId && item.materialCode === row.materialCode
  )

  if (index !== -1) {
    // 从物料列表中删除
    materialList.value.splice(index, 1)
    message.success('物料删除成功')

    // 重新计算总成本
    calculateTotalCost()
  }
}

/** 更新责任人显示 */
function updateDevicePersonsDisplay() {
  const allNames = new Set<string>()
  devicePersonsMap.value.forEach((names) => {
    names.forEach((name) => allNames.add(name))
  })
  formData.value.devicePersons = Array.from(allNames).join(', ')
}

/**
 * 根据选择的设备查询所有设备关联的 责任人姓名 逗号分隔
 */
async function getDevicePersons() {
  // 获取当前已经选择的设备ID集合
  const existDeviceIds = getCurrentDeviceIds()
  if (existDeviceIds.length === 0) {
    formData.value.devicePersons = ''
    return
  }
  try {
    // 调用接口获取数据
    const params = {
      deviceIds: existDeviceIds.join(',') // 明确传递数组参数
    }
    const res = await IotDevicePersonApi.getPersonsByDeviceIds(params)
    const personsData = res || []
    // 清空旧数据
    devicePersonsMap.value.clear()
    // 处理接口数据
    personsData.forEach((item: { deviceId: number; personName: string }) => {
      if (!devicePersonsMap.value.has(item.deviceId)) {
        devicePersonsMap.value.set(item.deviceId, new Set())
      }
      devicePersonsMap.value.get(item.deviceId)?.add(item.personName)
    })
    // 生成展示字符串
    updateDevicePersonsDisplay()
  } catch (error) {
    console.error('获取设备责任人失败:', error)
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验表格数据
  const isValid = validateTableData()
  if (!isValid) return

  // 新增：校验物料选择
  const hasMaterial = validateMaterialSelection()
  if (!hasMaterial) return

  // 提交请求
  formLoading.value = true
  try {
    const data = {
      mainWorkOrder: formData.value,
      mainWorkOrderBom: list.value,
      mainWorkOrderMaterials: materialList.value
    }
    await IotMainWorkOrderApi.addWorkOrder(data)
    message.success(t('common.createSuccess'))
    close()

    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 新增表单校验规则
const configFormRules = reactive({
  nextRunningKilometers: [
    {
      required: true,
      message: '里程周期必须填写',
      trigger: 'blur'
    }
  ],
  kiloCycleLead: [
    {
      required: true,
      message: '提前量必须填写',
      trigger: 'blur'
    }
  ],
  nextRunningTime: [
    {
      required: true,
      message: '时间周期必须填写',
      trigger: 'blur'
    }
  ],
  timePeriodLead: [
    {
      required: true,
      message: '提前量必须填写',
      trigger: 'blur'
    }
  ],
  nextNaturalDate: [
    {
      required: true,
      message: '自然日周期必须填写',
      trigger: 'blur'
    }
  ],
  naturalDatePeriodLead: [
    {
      required: true,
      message: '提前量必须填写',
      trigger: 'blur'
    }
  ]
})

/** 校验表格数据 */
const validateTableData = (): boolean => {
  let isValid = true
  const errorMessages: string[] = []

  if (list.value.length === 0) {
    errorMessages.push('请至少添加一条设备保养明细')
    isValid = false
    // 直接返回无需后续校验
    message.error('请至少添加一条设备保养明细')
    return isValid
  }
  return isValid
}

/** 检查每个保养项是否都有物料 */
const validateMaterialSelection = (): boolean => {
  let isValid = true
  const errorMessages: string[] = []

  // 遍历所有保养项
  list.value.forEach((item) => {
    const hasMaterial = materialList.value.some((material) => material.bomNodeId === item.bomNodeId)

    if (!hasMaterial) {
      isValid = false
      errorMessages.push(
        `设备 ${item.deviceCode}-${item.deviceName} 的保养项【${item.name}】未添加物料`
      )
    }
  })

  // 显示错误信息
  if (!isValid) {
    let displayMessage

    if (errorMessages.length > 3) {
      // 超过3条错误时显示前3条+总结
      const firstThree = errorMessages.slice(0, 3)
      displayMessage =
        firstThree.join('<br/>') + `<br/>...等共 ${errorMessages.length} 个保养项未添加物料`
    } else {
      // 3条及以内直接显示全部
      displayMessage = errorMessages.join('<br/>')
    }

    message.error({
      message: displayMessage,
      dangerouslyUseHTMLString: true
    })
  }

  return isValid
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    status: undefined,
    description: undefined,
    pic: undefined,
    remark: undefined,
    applicant: undefined,
    deviceName: undefined,
    processInstanceId: undefined,
    auditStatus: undefined,
    deptId: undefined,
    attachments: []
  }
  formRef.value?.resetFields()
}
onMounted(async () => {
  materialList.value = []
  const deptId = useUserStore().getUser.deptId
  // 查询当前登录人所属部门名称
  dept.value = await DeptApi.getDept(deptId)
  // formData.value.name = dept.value.name + ' - 保养工单'
  deptUsers.value = await UserApi.getDeptUsersByDeptId(deptId)
  formData.value.deptId = deptId
  try {
    formType.value = 'create'
    const { wsCache } = useCache()
    const userInfo = wsCache.get(CACHE_KEY.USER)
    // 手工新增保养工单 责任人为当前登录人
    formData.value.responsiblePerson = userInfo.user.id

    // 初始化工单名称
    updateWorkOrderName()
  } catch (error) {
    console.error('数据加载失败:', error)
    message.error('数据加载失败，请重试')
  }
})

const handleDelete = async (str: string) => {
  try {
    const [deviceIdStr, bomNodeId] = str.split('-')
    const deviceId = parseInt(deviceIdStr)
    // 删除列表项
    const index = list.value.findIndex((item) => item.deviceId + '-' + item.bomNodeId === str)
    if (index !== -1) {
      list.value.splice(index, 1)
      deviceIds.value = []
    }
    // 更新设备ID列表（需要检查是否还有该设备的其他项）
    const hasOtherItems = list.value.some((item) => item.deviceId === deviceId)
    if (!hasOtherItems) {
      deviceIds.value = deviceIds.value.filter((id) => id !== deviceId)
      devicePersonsMap.value.delete(deviceId) // 移除对应设备的责任人
      updateDevicePersonsDisplay() // 立即更新显示
    }
    // 更新工单名称
    updateWorkOrderName()
  } catch (error) {
    console.error('移除失败:', error)
    message.error('移除失败')
  }
}
</script>
<style scoped>
.base-expandable-content {
  overflow: hidden; /* 隐藏溢出的内容 */
  transition: max-height 0.3s ease; /* 平滑过渡效果 */
}

:deep(.el-input-number .el-input__inner) {
  padding-left: 10px; /* 保持左侧间距 */
  text-align: left !important;
}

/* 分组容器样式 */
.form-group {
  position: relative;
  padding: 20px 15px 10px;
  margin-bottom: 18px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.2s;
}

/* 分组标题样式 */
.group-title {
  position: absolute;
  top: -10px;
  left: 20px;
  padding: 0 8px;
  font-size: 12px;
  font-weight: 500;
  color: #606266;
  background: white;
}

.attachment-container {
  width: 100%;
}

.work-order-attachment-upload :deep(.upload-list-card) {
  display: none;
}

.attachment-list {
  width: 100%;
  padding: 10px;
  margin-top: 5px;
  background-color: #fafafa;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  box-sizing: border-box;
}

.attachment-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
}

.attachment-item:last-child {
  border-bottom: none;
}

.attachment-name {
  flex: 1;
  font-size: 12px;
  color: #606266;
  cursor: pointer;
}

.no-attachment {
  padding: 10px;
  margin-top: 5px;
  font-style: italic;
  color: #909399;
}
</style>
