<template>
  <div class="mold-maintain-page">
    <div class="mold-maintain-page__header">
      <el-button @click="emit('back')">
        <Icon icon="ep:arrow-left" class="mr-5px" /> {{ t('MoldManagement.MoldBrandPage.back') }}
      </el-button>
    </div>

    <div class="mold-maintain-page__body">
      <!-- 左侧模具信息区域 -->
      <div class="mold-maintain-page__sidebar" v-if="mold">
        <div class="mold-maintain-page__info-card">
          <div class="mold-maintain-page__info-header">
            <span class="mold-maintain-page__info-num">1</span>
            <span class="mold-maintain-page__info-title">{{ t('MoldManagement.MoldBrandPage.moldInfo') }}</span>
          </div>
          <div class="mold-maintain-page__info-image-wrap">
            <el-image v-if="getImageList(mold.images).length" :src="getImageList(mold.images)[0]"
              fit="cover" class="mold-maintain-page__info-image" />
            <el-empty v-else :description="t('MoldManagement.MoldBrandDetail.noImage')" />
          </div>
          <div class="mold-maintain-page__info-item">
            <span class="mold-maintain-page__info-label">{{ t('MoldManagement.MoldBrandPage.moldGroupCode') }}</span>
            <span class="mold-maintain-page__info-value">{{ mold.code }}</span>
          </div>
          <div class="mold-maintain-page__info-item">
            <span class="mold-maintain-page__info-label">{{ t('MoldManagement.MoldBrandPage.moldGroupName') }}</span>
            <span class="mold-maintain-page__info-value">{{ mold.name }}</span>
          </div>
          <div class="mold-maintain-page__info-item">
            <span class="mold-maintain-page__info-label">{{ t('MoldManagement.MoldBrandPage.productName') }}</span>
            <span class="mold-maintain-page__info-value">{{ mold.productName }}</span>
          </div>
          <div class="mold-maintain-page__info-item">
            <span class="mold-maintain-page__info-label">{{ t('MoldManagement.MoldBrandPage.moldSize') }}</span>
            <span class="mold-maintain-page__info-value">{{ mold.moldSize }}</span>
          </div>
          <div class="mold-maintain-page__info-item">
            <span class="mold-maintain-page__info-label">{{ t('MoldManagement.MoldBrandPage.status') }}</span>
            <dict-tag :type="DICT_TYPE.ERP_MOLD_STATUS" :value="mold.status" />
          </div>
          <div class="mold-maintain-page__info-item">
            <span class="mold-maintain-page__info-label">{{ t('MoldManagement.MoldBrandPage.currentDevice') }}</span>
            <span class="mold-maintain-page__info-value">{{ mold.currentDevice || '-' }}</span>
          </div>
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="mold-maintain-page__form">
        <div class="mold-maintain-page__form-header">
          <span class="mold-maintain-page__info-num">2</span>
          <span class="mold-maintain-page__info-title">{{ t('MoldManagement.MoldBrandPage.maintainInfo') }}</span>
        </div>
        <el-form ref="maintainFormRef" :model="formModel" :rules="formRules" label-width="100px">
          <!-- 维护类型 -->
          <el-form-item :label="t('MoldManagement.MoldBrandPage.maintainType')" prop="maintainType">
            <div class="mold-maintain-type-card">
              <div
                v-for="type in maintainTypes"
                :key="type.value"
                class="mold-maintain-type-card__item"
                :class="{ 'is-active': maintainFormData.maintainType === type.value }"
                @click="selectMaintainType(type.value)"
              >
                <div class="mold-maintain-type-card__icon">
                  <el-icon :size="26">
                    <component :is="type.icon" />
                  </el-icon>
                </div>
                <span class="mold-maintain-type-card__label">{{ type.label }}</span>
              </div>
            </div>
          </el-form-item>

          <!-- 点检/保养表单 -->
          <template v-if="isInspectOrMaintain">
            <div class="mold-maintain-inspect-layout">
              <div class="mold-maintain-inspect-layout__form">
                <el-form-item :label="t('EquipmentManagement.TaskManagement.name')" prop="name">
                  <el-input v-model="taskFormData.name" :placeholder="t('EquipmentManagement.TaskManagement.placeholderName')" />
                </el-form-item>
                <el-form-item :label="t('EquipmentManagement.TaskManagement.projectForm')" prop="projectForm">
                  <div class="flex items-center gap-2 w-full">
                    <el-input
                      v-model="projectFormDisplayText"
                      readonly
                      :placeholder="t('EquipmentManagement.TaskManagement.placeholderProjectForm')"
                      class="flex-1"
                    />
                    <el-button @click="openProjectFormDialog">{{ t('common.select') }}</el-button>
                  </div>
                </el-form-item>
              </div>
              <el-divider content-position="left">{{ t('MoldManagement.MoldBrandPage.inspectionResult') }}</el-divider>
              <div class="mold-maintain-ticket-results">
                <div class="mold-maintain-ticket-results__header">
                  <el-button
                    type="primary"
                    link
                    :disabled="!ticketResultList.length"
                    @click="handleTicketResultEditToggle"
                  >
                    <Icon :icon="ticketResultEditable ? 'ep:lock' : 'ep:edit-pen'" class="mr-4px" />
                    {{ ticketResultEditable ? t('common.cancel') : t('action.edit') }}
                  </el-button>
                </div>
                <el-table
                  :data="ticketResultPageData"
                  :stripe="true"
                  :show-overflow-tooltip="true"
                  size="small"
                  max-height="420"
                  row-key="id"
                >
                  <el-table-column type="index" :label="t('MoldManagement.MoldBrandPage.index')" align="center" width="58" />
                  <el-table-column :label="t('MoldManagement.MoldBrandPage.inspectionItemName')" align="center" prop="inspectionItemName" min-width="140" />
                  <el-table-column label="检验方式" align="center" prop="inspectionMethod" min-width="120">
                    <template #default="scope">
                      <dict-tag type="Inspection_method" :value="scope.row.inspectionMethod" />
                    </template>
                  </el-table-column>
                  <el-table-column :label="t('MoldManagement.MoldBrandPage.judgmentCriteria')" align="center" prop="judgmentCriteria" min-width="140" />
                  <el-table-column :label="t('MoldManagement.MoldBrandPage.inspectionResult')" align="center" prop="inspectionResult" width="100">
                    <template #default="scope">
                      <el-tag v-if="String(scope.row.inspectionResult) === '0'" type="info">{{ t('MoldManagement.MoldBrandPage.pendingInspection') }}</el-tag>
                      <el-tag v-else-if="String(scope.row.inspectionResult) === '1'" type="success">{{ t('MoldManagement.MoldBrandPage.pass') }}</el-tag>
                      <el-tag v-else-if="String(scope.row.inspectionResult) === '2'" type="danger">{{ t('MoldManagement.MoldBrandPage.notPass') }}</el-tag>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column :label="t('MoldManagement.MoldBrandPage.image')" align="center" prop="images" min-width="180">
                    <template #default="scope">
                      <div
                        v-if="ticketResultEditable"
                        v-loading="isTicketResultImageUploading(scope.row)"
                        element-loading-text="上传中"
                        class="ticket-result-images"
                        :class="{ 'is-full': getTicketResultImages(scope.row).length >= 3 }"
                      >
                        <UploadImgs
                          v-model="scope.row.images"
                          :limit="3"
                          width="56px"
                          height="56px"
                          @uploading-change="setTicketResultImageUploading(scope.row, $event)"
                        />
                      </div>
                      <el-image
                        v-else-if="parseImages(scope.row.images).length"
                        :src="parseFirstImage(scope.row.images)"
                        :preview-src-list="parseImages(scope.row.images)"
                        preview-teleported
                        fit="cover"
                        style="width: 56px; height: 56px"
                      />
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column :label="t('EquipmentManagement.DvSubject.valueType')" align="center" prop="valueType" width="100">
                    <template #default="scope">
                      <dict-tag type="value_types" :value="scope.row.valueType" />
                    </template>
                  </el-table-column>
                  <el-table-column :label="t('MoldManagement.MoldBrandPage.inputValue')" align="center" min-width="150">
                    <template #default="scope">
                      <el-input
                        v-if="String(scope.row.valueType) === '0' || String(scope.row.valueType) === '2'"
                        v-model="scope.row.textInput"
                        :disabled="!ticketResultEditable"
                        clearable
                        :placeholder="t('common.inputText')"
                      />
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                  <el-table-column :label="t('MoldManagement.MoldBrandPage.remark')" align="center" prop="remark" min-width="100">
                    <template #default="scope">
                      <el-input v-model="scope.row.remark" :disabled="!ticketResultEditable" clearable :placeholder="t('common.inputText')" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="150" fixed="right">
                    <template #default="scope">
                      <el-radio-group v-if="ticketResultEditable" v-model="scope.row.inspectionResult">
                        <el-radio :label="'1'">通过</el-radio>
                        <el-radio :label="'2'">不通过</el-radio>
                      </el-radio-group>
                      <span v-else>-</span>
                    </template>
                  </el-table-column>
                </el-table>
                <Pagination
                  v-if="ticketResultList.length"
                  :total="ticketResultList.length"
                  v-model:page="ticketResultPageNo"
                  :limit="ticketResultPageSize"
                  @pagination="handleTicketResultPageChange"
                />
                <el-empty
                  v-if="!ticketResultList.length"
                  :description="selectedProjectFormId ? t('MoldManagement.MoldBrandPage.noInspectionItems') : t('MoldManagement.MoldBrandPage.pleaseSelectProjectForm')"
                  :image-size="80"
                />
              </div>
            </div>
          </template>

          <!-- 维修表单 -->
          <template v-if="isRepair">
            <section class="dv-repair-section">
              <div class="dv-repair-section__title">{{ t('MoldManagement.MoldRepair.basicInfo') }}</div>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item :label="t('MoldManagement.MoldRepair.repairCode')" prop="repairCode">
                    <div class="dv-repair-code-row">
                      <el-input
                        :disabled="repairCodeDisabled"
                        v-model="repairFormData.repairCode"
                        :placeholder="t('common.code')"
                      />
                      <el-switch
                        v-model="repairFormData.isCode"
                      />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="t('MoldManagement.MoldRepair.repairName')" prop="repairName">
                    <el-input
                      v-model="repairFormData.repairName"
                      :placeholder="t('MoldManagement.MoldRepair.placeholderRepairName')"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="t('MoldManagement.MoldRepair.requireDate')" prop="requireDate">
                    <el-date-picker
                      v-model="repairFormData.requireDate"
                      type="date"
                      value-format="x"
                      :placeholder="t('MoldManagement.MoldRepair.placeholderRequireDate')"
                      class="!w-full"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item :label="t('MoldManagement.MoldRepair.repairReporter')" prop="repairReporter">
                    <el-select
                      v-model="repairFormData.repairReporter" filterable clearable
                      :placeholder="t('MoldManagement.MoldRepair.placeholderRepairReporter')"
                      class="!w-full">
                      <el-option v-for="item in users" :key="String(item.id)" :label="item.nickname" :value="String(item.id)" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="t('MoldManagement.MoldRepair.repairUser')" prop="acceptedBy">
                    <el-select
                      v-model="repairFormData.acceptedBy" filterable clearable
                      :placeholder="t('MoldManagement.MoldRepair.placeholderAcceptUser')"
                      class="!w-full">
                      <el-option v-for="item in users" :key="String(item.id)" :label="item.nickname" :value="String(item.id)" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="t('MoldManagement.MoldRepair.confirmUser')" prop="confirmBy">
                    <el-select
                      v-model="repairFormData.confirmBy" filterable clearable
                      :placeholder="t('MoldManagement.MoldRepair.placeholderConfirmUser')"
                      class="!w-full">
                      <el-option v-for="item in users" :key="String(item.id)" :label="item.nickname" :value="String(item.id)" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item :label="t('MoldManagement.MoldRepair.faultLevel')" prop="faultLevel">
                    <el-radio-group v-model="repairFormData.faultLevel">
                      <el-radio
                        v-for="dict in failureLevelOptions"
                        :key="String(dict.value)"
                        :label="String(dict.value)"
                      >
                        {{ dict.label }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="t('MoldManagement.MoldRepair.isShutdown')" prop="shutdown">
                    <el-radio-group v-model="repairFormData.shutdown">
                      <el-radio :label="true">{{ t('common.yes') }}</el-radio>
                      <el-radio :label="false">{{ t('common.no') }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </section>

            <section class="dv-repair-section">
              <div class="dv-repair-section__title">{{ t('MoldManagement.MoldRepair.faultInfo') }}</div>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item :label="t('MoldManagement.MoldRepair.faultPhenomenon')" prop="faultPhenomenon">
                    <el-input
                      v-model="repairFormData.faultPhenomenon"
                      :placeholder="t('MoldManagement.MoldRepair.placeholderFaultPhenomenon')"
                    />
                  </el-form-item>
                  <el-form-item :label="t('MoldManagement.MoldRepair.faultDescription')" prop="faultDescription">
                    <el-input
                      v-model="repairFormData.faultDescription"
                      type="textarea"
                      :rows="4"
                      :placeholder="t('MoldManagement.MoldRepair.placeholderFaultDescription')"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item :label="t('MoldManagement.MoldRepair.faultImages')">
                    <UploadImgs
                      v-model="faultImagesValue"
                      :limit="9"
                      width="120px"
                      height="120px"
                      class="dv-repair-upload"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </section>

            <section class="dv-repair-section">
              <div class="dv-repair-section__title">{{ t('MoldManagement.MoldRepair.remark') }}</div>
              <el-form-item prop="remark" label-width="0">
                <el-input
                  v-model="repairFormData.remark"
                  type="textarea"
                  :rows="3"
                  maxlength="300"
                  show-word-limit
                  :placeholder="t('MoldManagement.MoldRepair.placeholderRemark')"
                />
              </el-form-item>
            </section>
          </template>

          <!-- 更换压网表单 -->
          <template v-if="isReplaceNet">
            <section class="dv-repair-section">
              <div class="dv-repair-section__title">{{ t('MoldManagement.MoldBrandPage.maintainTypeReplaceNet') }}</div>
              <el-form-item :label="t('MoldManagement.MoldBrandPage.subMold')" prop="moldIds">
                <el-select
                  v-model="replaceNetFormData.moldIds"
                  filterable
                  clearable
                  multiple
                  :loading="subMoldLoading"
                  :placeholder="t('MoldManagement.MoldBrandPage.placeholderSubMold')"
                  class="!w-full"
                >
                  <el-option
                    v-for="item in subMoldList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item :label="t('MoldManagement.MoldBrandPage.pressureNetTime')" prop="pressureNetTime">
                <el-date-picker
                  v-model="replaceNetFormData.pressureNetTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="t('MoldManagement.MoldBrandPage.placeholderPressureNetTime')"
                  class="!w-full"
                  :disabled-date="(date: Date) => date.getTime() > Date.now()"
                />
              </el-form-item>
              <el-form-item :label="t('MoldManagement.MoldBrandPage.replaceNetRemark')" prop="replaceNetRemark">
                <el-input
                  v-model="replaceNetFormData.remark"
                  type="textarea"
                  :rows="3"
                  maxlength="300"
                  show-word-limit
                  :placeholder="t('MoldManagement.MoldBrandPage.placeholderReplaceNetRemark')"
                />
              </el-form-item>
            </section>
          </template>
        </el-form>

        <div class="mold-maintain-page__form-actions">
          <el-button @click="emit('back')">{{ t('MoldManagement.MoldBrandPage.cancel') }}</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading" :disabled="isInspectOrMaintain && hasTicketResultImageUploading">{{ t('MoldManagement.MoldBrandPage.submit') }}</el-button>
        </div>
      </div>
    </div>

    <!-- 项目表单选择弹框 -->
    <Dialog v-model="projectFormDialogVisible" :title="t('EquipmentManagement.TaskManagement.projectForm')" width="1200px">
      <div class="project-form-dialog-content">
        <el-table
          ref="projectFormTableRef"
          v-loading="projectFormLoading"
          :data="projectFormList"
          row-key="id"
          @expand-change="handleProjectFormExpandChange"
        >
          <el-table-column width="55" align="center">
            <template #default="scope">
              <el-radio
                v-model="tempSelectedProjectFormId"
                :value="String(scope.row.id)"
                @change="handleProjectFormRadioChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column type="expand" width="48">
            <template #default="scope">
              <div class="p-12px">
                <el-table
                  v-loading="subjectLoadingMap[String(scope.row.id)]"
                  :data="subjectListMap[String(scope.row.id)] ?? []"
                  :stripe="true"
                  :show-overflow-tooltip="true"
                  size="small"
                >
                  <el-table-column :label="t('MoldManagement.MoldInspectionPlan.index')" align="center" width="80">
                    <template #default="s2">
                      {{ s2.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column :label="t('MoldManagement.MoldInspectionPlan.subjectCode')" align="center" prop="subjectCode" />
                  <el-table-column :label="t('MoldManagement.MoldInspectionPlan.subjectName')" align="center" prop="subjectName" />
                  <el-table-column :label="t('MoldManagement.MoldInspectionPlan.inspectionMethod')" align="center" prop="inspectionMethod" width="120">
                    <template #default="scope">
                      <el-tag
                        effect="light"
                        :type="getTagType('Inspection_method', scope.row.inspectionMethod)"
                        :color="getTagColor('Inspection_method', scope.row.inspectionMethod)"
                        :style="getTagStyle('Inspection_method', scope.row.inspectionMethod)"
                        disable-transitions
                      >
                        {{ getTagLabel('Inspection_method', scope.row.inspectionMethod) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column :label="t('MoldManagement.MoldInspectionPlan.judgmentCriteria')" align="center" prop="judgmentCriteria" />
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="t('MoldManagement.MoldInspectionPlan.index')" align="center" width="80">
            <template #default="scope">
              {{ (projectFormPageParams.pageNo - 1) * projectFormPageParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="t('MoldManagement.MoldInspectionPlan.planName')" prop="planName" min-width="160" />
          <el-table-column :label="t('MoldManagement.MoldInspectionPlan.planType')" width="110">
            <template #default="scope">
              <el-tag effect="light" :type="scope.row.planType === 1 ? 'success' : 'primary'" size="small">
                {{ scope.row.planType === 1 ? t('MoldManagement.MoldInspectionPlan.planTypeMaintain') : t('MoldManagement.MoldInspectionPlan.planTypeInspect') }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="t('MoldManagement.MoldInspectionPlan.description')" prop="description" min-width="200" />
          <el-table-column :label="t('MoldManagement.MoldInspectionPlan.creatorName')" prop="creatorName" width="140" />
          <el-table-column :label="t('MoldManagement.MoldInspectionPlan.createTime')" prop="createTime" :formatter="dateFormatter" width="180" />
          <el-table-column :label="t('MoldManagement.MoldInspectionPlan.updateTime')" prop="updateTime" :formatter="dateFormatter" width="180" />
        </el-table>
        <Pagination
          :total="projectFormTotal"
          v-model:page="projectFormPageParams.pageNo"
          v-model:limit="projectFormPageParams.pageSize"
          @pagination="loadProjectFormList"
        />
      </div>
      <template #footer>
        <el-button @click="projectFormDialogVisible = false">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="confirmProjectFormSelection">{{ t('common.ok') }}</el-button>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { EditPen, RefreshRight, Search, Tools } from '@element-plus/icons-vue'
import { MoldBrandApi, type MoldBrandVO } from '@/api/erp/mold'
import { DeviceLedgerApi, type DeviceLedgerVO } from '@/api/mes/deviceledger'
import { TaskManagementApi } from '@/api/mold/taskManagement'
import { MoldRepairApi, type MoldRepairVO } from '@/api/mold/moldrepair'
import { PlanMaintenanceApi } from '@/api/mold/planmaintenance'
import { getSimpleUserList, type UserVO } from '@/api/system/user'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { isHexColor } from '@/utils/color'
import { dateFormatter } from '@/utils/formatTime'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'MoldMaintainView' })

const props = defineProps<{
  mold: MoldBrandVO | null
  deviceOptions: DeviceLedgerVO[]
}>()

const emit = defineEmits<{
  (e: 'back'): void
  (e: 'success'): void
}>()

const { t } = useI18n()
const message = useMessage()
const userStore = useUserStore()

const submitLoading = ref(false)
const maintainFormRef = ref()

// 表单验证规则
const formRules = reactive({
  maintainType: [{ required: true, message: t('MoldManagement.MoldBrandPage.placeholderMaintainType'), trigger: 'change' }],
  // 点检/保养表单规则
  name: [{ required: true, message: t('EquipmentManagement.TaskManagement.placeholderName'), trigger: 'blur' }],
  taskType: [{ required: true, message: t('EquipmentManagement.TaskManagement.placeholderTaskType'), trigger: 'change' }],
  projectForm: [{ required: true, message: t('EquipmentManagement.TaskManagement.placeholderProjectForm') }],
  // 维修表单规则
  repairName: [{ required: true, message: t('MoldManagement.MoldRepair.validatorRepairNameRequired'), trigger: 'blur' }],
  requireDate: [{ required: true, message: t('MoldManagement.MoldRepair.validatorRequireDateRequired'), trigger: 'change' }],
  faultLevel: [{ required: true, message: t('MoldManagement.MoldRepair.validatorFaultLevelRequired'), trigger: 'blur' }],
  shutdown: [{ required: true, message: t('MoldManagement.MoldRepair.validatorIsShutdownRequired'), trigger: 'blur' }],
  faultPhenomenon: [{ required: true, message: t('MoldManagement.MoldRepair.validatorFaultPhenomenonRequired'), trigger: 'blur' }],
  // 压网表单规则
  moldIds: [{ required: true, message: t('MoldManagement.MoldBrandPage.validatorSubMoldRequired'), trigger: 'change' }],
  pressureNetTime: [{ required: true, message: t('MoldManagement.MoldBrandPage.validatorPressureNetTimeRequired'), trigger: 'blur' }],
})

// 合并表单模型，用于 el-form 验证
const formModel = computed(() => ({
  maintainType: maintainFormData.maintainType,
  name: taskFormData.name,
  taskType: taskFormData.taskType,
  projectForm: taskFormData.projectForm,
  repairName: repairFormData.repairName,
  requireDate: repairFormData.requireDate,
  repairReporter: repairFormData.repairReporter,
  faultLevel: repairFormData.faultLevel,
  shutdown: repairFormData.shutdown,
  faultPhenomenon: repairFormData.faultPhenomenon,
  moldIds: replaceNetFormData.moldIds,
  pressureNetTime: replaceNetFormData.pressureNetTime,
}))

// 维护类型
const maintainFormData = reactive({
  maintainType: 1 as number
})

// 点检/保养表单数据
const taskFormData = reactive({
  name: undefined as string | undefined,
  taskType: 1 as number,
  projectForm: '' as string
})

// 维修表单数据
const repairFormData = reactive({
  repairCode: undefined as string | undefined,
  repairName: undefined as string | undefined,
  requireDate: undefined as number | string | undefined,
  repairReporter: undefined as string | undefined,
  acceptedBy: undefined as string | undefined,
  confirmBy: undefined as string | undefined,
  faultLevel: undefined as string | undefined,
  shutdown: undefined as boolean | undefined,
  faultPhenomenon: undefined as string | undefined,
  faultDescription: undefined as string | undefined,
  faultImages: '' as string,
  remark: undefined as string | undefined,
  isCode: true as boolean
})

// 更换压网表单数据
const replaceNetFormData = reactive({
  moldIds: [] as number[],
  pressureNetTime: undefined as string | undefined,
  remark: undefined as string | undefined
})

const getCurrentDateTime = () => {
  const date = new Date()
  const pad = (value: number) => String(value).padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

// 子模具下拉选项
const subMoldList = ref<any[]>([])
const subMoldLoading = ref(false)

const loadSubMoldList = async () => {
  if (!props.mold?.id) return
  subMoldLoading.value = true
  try {
    const data = await MoldBrandApi.getMoldList({ brandId: props.mold.id })
    subMoldList.value = data ?? []
  } finally {
    subMoldLoading.value = false
  }
}

// 计算属性
const isInspectOrMaintain = computed(() => [1, 2].includes(maintainFormData.maintainType ?? 0))
const isRepair = computed(() => maintainFormData.maintainType === 3)
const isReplaceNet = computed(() => maintainFormData.maintainType === 4)
const repairCodeDisabled = computed(() => repairFormData.isCode === true)
const failureLevelOptions = computed(() => getStrDictOptions(DICT_TYPE.FAILURE_LEVEL))

const getTagDict = (dictType: string, value: any) => {
  const v = value === '' || value === null || value === undefined ? undefined : String(value)
  if (!v) return undefined
  return getStrDictOptions(dictType).find((d) => d.value === v)
}

const getTagLabel = (dictType: string, value: any) => {
  const found = getTagDict(dictType, value)
  return found?.label ?? (value ?? '')
}

const getTagType = (dictType: string, value: any) => {
  const found = getTagDict(dictType, value)
  const type = found?.colorType
  if (type + '' === 'primary' || type + '' === 'default') return '' as any
  return (type ?? '') as any
}

const getTagColor = (dictType: string, value: any) => {
  const found = getTagDict(dictType, value)
  if (found?.cssClass && isHexColor(found.cssClass)) return found.cssClass
  return ''
}

const getTagStyle = (dictType: string, value: any) => {
  const color = getTagColor(dictType, value)
  if (!color) return ''
  return 'color: #fff'
}

// 维护类型配置
const maintainTypes = computed(() => [
  { value: 1, label: t('MoldManagement.MoldBrandPage.maintainTypeInspect'), icon: Search },
  { value: 2, label: t('MoldManagement.MoldBrandPage.maintainTypeMaintain'), icon: Tools },
  { value: 3, label: t('MoldManagement.MoldBrandPage.maintainTypeRepair'), icon: EditPen },
  { value: 4, label: t('MoldManagement.MoldBrandPage.maintainTypeReplaceNet'), icon: RefreshRight }
])

// 项目表单下拉选项（用于旧逻辑兼容，不再使用 select 下拉展示）
const planOptions = ref<{ id: number | string; planName: string }[]>([])
const users = ref<UserVO[]>([])

// 项目表单弹框相关
const projectFormDialogVisible = ref(false)
const projectFormLoading = ref(false)
const projectFormList = ref<any[]>([])
const projectFormTotal = ref(0)
const projectFormTableRef = ref()
const tempSelectedProjectForm = ref<any>(null) // 弹框中临时选中的行
const tempSelectedProjectFormId = ref<string>('') // 弹框中 radio 绑定的 id
const selectedProjectFormId = ref<string>('') // 已确认选中的 id
const selectedProjectFormName = ref<string>('') // 已确认选中的名称
const subjectListMap = ref<Record<string, any[]>>({})
const subjectLoadingMap = ref<Record<string, boolean>>({})
const ticketResultList = ref<any[]>([])
const ticketResultEditable = ref(false)
const ticketResultBackup = ref<any[] | null>(null)
const ticketResultImageUploadingMap = reactive<Record<string, boolean>>({})
const hasTicketResultImageUploading = computed(() => Object.values(ticketResultImageUploadingMap).some(Boolean))

const getTicketResultImageKey = (row: any) => String(row?.id ?? row?.subjectId ?? row?.sort ?? '')

const setTicketResultImageUploading = (row: any, value: boolean) => {
  const key = getTicketResultImageKey(row)
  if (!key) return
  if (value) {
    ticketResultImageUploadingMap[key] = true
  } else {
    delete ticketResultImageUploadingMap[key]
  }
}

const isTicketResultImageUploading = (row: any) => {
  const key = getTicketResultImageKey(row)
  return !!ticketResultImageUploadingMap[key]
}

const clearTicketResultImageUploading = () => {
  for (const key of Object.keys(ticketResultImageUploadingMap)) {
    delete ticketResultImageUploadingMap[key]
  }
}

const handleTicketResultEditToggle = () => {
  if (ticketResultEditable.value) {
    // 取消编辑，恢复备份
    if (ticketResultBackup.value) {
      ticketResultList.value = JSON.parse(JSON.stringify(ticketResultBackup.value))
      ticketResultBackup.value = null
    }
    ticketResultEditable.value = false
  } else {
    // 进入编辑，保存备份
    ticketResultBackup.value = JSON.parse(JSON.stringify(ticketResultList.value))
    ticketResultEditable.value = true
  }
}
const ticketResultPageNo = ref(1)
const ticketResultPageSize = 5
const ticketResultPageData = computed(() => {
  const start = (ticketResultPageNo.value - 1) * ticketResultPageSize
  return ticketResultList.value.slice(start, start + ticketResultPageSize)
})
const handleTicketResultPageChange = () => {
  // 分页切换，数据由 computed 自动计算
}

const projectFormPageParams = reactive({
  pageNo: 1,
  pageSize: 10
})

const projectFormDisplayText = computed(() => {
  return selectedProjectFormName.value || ''
})

const loadProjectFormList = async () => {
  projectFormLoading.value = true
  try {
    const res = await PlanMaintenanceApi.getPlanMaintenancePage({
      pageNo: projectFormPageParams.pageNo,
      pageSize: projectFormPageParams.pageSize
    })
    projectFormList.value = res?.list ?? []
    projectFormTotal.value = res?.total ?? 0
  } finally {
    projectFormLoading.value = false
  }
}

const openProjectFormDialog = async () => {
  projectFormPageParams.pageNo = 1
  tempSelectedProjectForm.value = null
  tempSelectedProjectFormId.value = selectedProjectFormId.value || ''
  projectFormDialogVisible.value = true
  await loadProjectFormList()
}

const handleProjectFormRadioChange = (row: any) => {
  tempSelectedProjectForm.value = row
}

const confirmProjectFormSelection = async () => {
  if (!tempSelectedProjectForm.value) return
  selectedProjectFormId.value = String(tempSelectedProjectForm.value.id)
  selectedProjectFormName.value = tempSelectedProjectForm.value.planName ?? String(tempSelectedProjectForm.value.id)
  taskFormData.projectForm = selectedProjectFormId.value
  if (Array.isArray(tempSelectedProjectForm.value.subjectList)) {
    subjectListMap.value[selectedProjectFormId.value] = tempSelectedProjectForm.value.subjectList
  } else {
    await ensureSubjectListLoaded(selectedProjectFormId.value)
  }
  setTicketResultList(subjectListMap.value[selectedProjectFormId.value] ?? [])
  ticketResultEditable.value = false
  projectFormDialogVisible.value = false
}

const ensureSubjectListLoaded = async (planId: number | string) => {
  const key = String(planId)
  if (!key) return
  if (subjectListMap.value[key]) return
  subjectLoadingMap.value[key] = true
  try {
    const res = await PlanMaintenanceApi.getSubjectList(planId)
    const data = Array.isArray(res) ? res : res?.list ?? res ?? []
    subjectListMap.value[key] = (data ?? [])
  } finally {
    subjectLoadingMap.value[key] = false
  }
}

const setTicketResultList = (subjectList: any[]) => {
  clearTicketResultImageUploading()
  ticketResultList.value = (subjectList ?? []).map((item: any, index: number) => ({
    id: item.id,
    subjectId: item.id,
    inspectionItemName: item.subjectName ?? item.inspectionItemName ?? '',
    inspectionMethod: item.inspectionMethod ?? '',
    judgmentCriteria: item.judgmentCriteria ?? item.subjectStandard ?? '',
    valueType: item.valueType ?? '',
    textInput: item.textInput ?? '',
    inspectionResult: item.inspectionResult ?? '0',
    images: parseImages(item.images).slice(0, 3),
    remark: item.remark ?? '',
    sort: index + 1
  }))
  ticketResultPageNo.value = 1
}

const parseImages = (value: any): string[] => {
  if (!value) return []
  if (Array.isArray(value)) return value.map(String).filter(Boolean)
  return String(value)
    .split(',')
    .map((v) => v.trim())
    .filter(Boolean)
}

const parseFirstImage = (value: any): string => {
  return parseImages(value)[0] || ''
}

const getTicketResultImages = (row: any): string[] => {
  return parseImages(row?.images)
}

const handleProjectFormExpandChange = async (row: any, expandedRows: any[]) => {
  const isExpanded = expandedRows.some((r) => String(r.id) === String(row.id))
  if (!isExpanded) return
  if (row?.id === undefined || row?.id === null || row?.id === '') return
  await ensureSubjectListLoaded(row.id)
}

const ensureUsersLoaded = async () => {
  if (users.value.length) return
  users.value = (await getSimpleUserList()) ?? []
}

const normalizeUserId = (value: any) => {
  if (value === undefined || value === null || value === '') return undefined
  const str = String(value)
  if (/^\d+$/.test(str)) return str
  const matched = users.value.find((u) => u.nickname === str)
  return matched ? String(matched.id) : str
}

const splitImageValue = (value: unknown) => {
  if (Array.isArray(value)) return value.map((item) => String(item).trim()).filter(Boolean)
  if (typeof value !== 'string') return []
  return value
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean)
}

const normalizeImageString = (value: unknown) => splitImageValue(value).join(',')

const faultImagesValue = computed<string[]>({
  get: () => splitImageValue(repairFormData.faultImages),
  set: (value) => { repairFormData.faultImages = value.join(',') }
})

const getImageList = (images?: string) => {
  if (!images) return []
  return String(images)
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean)
}

const initOptions = async () => {
  const [planRes, userRes] = await Promise.all([
    PlanMaintenanceApi.getPlanMaintenancePage({}),
    getSimpleUserList()
  ])
  planOptions.value = (planRes?.list ?? []) as { id: number | string; planName: string }[]
  users.value = userRes ?? []
}

const handleMaintainTypeChange = () => {
  // 切换维护类型时同步 taskType
  if (isInspectOrMaintain.value) {
    taskFormData.taskType = maintainFormData.maintainType
  }
}

const selectMaintainType = async (type: number) => {
  maintainFormData.maintainType = type
  if (type === 3 && !repairFormData.requireDate) {
    repairFormData.requireDate = Date.now()
  }
  if (type === 3 && !repairFormData.repairReporter) {
    const currentUserId = userStore.getUser?.id
    if (currentUserId !== undefined && currentUserId !== null && Number(currentUserId) > 0) {
      repairFormData.repairReporter = String(currentUserId)
    }
  }
  handleMaintainTypeChange()
  // 切换类型时刷新对应下拉框选项
  await initOptions()
  // 切换到压网时加载子模具列表
  if (type === 4) {
    if (!replaceNetFormData.pressureNetTime) {
      replaceNetFormData.pressureNetTime = getCurrentDateTime()
    }
    await loadSubMoldList()
  }
}

const submitForm = async () => {
  // 表单验证
  try {
    await maintainFormRef.value?.validate()
  } catch {
    return
  }
  submitLoading.value = true
  try {
    if (isInspectOrMaintain.value) {
      // 提交点检/保养任务
      await TaskManagementApi.createMoldTicketDirect({
        name: taskFormData.name,
        taskType: String(taskFormData.taskType),
        moldList: props.mold?.id ? String(props.mold.id) : undefined,
        projectForm: taskFormData.projectForm,
        ticketResultsList: ticketResultList.value.map((item: any) => ({
          ...item,
          images: normalizeImageString(item.images)
        }))
      })
      message.success(t('common.createSuccess'))
      // 清空已提交的表单数据
      taskFormData.name = undefined
      taskFormData.projectForm = ''
      selectedProjectFormId.value = ''
      selectedProjectFormName.value = ''
      ticketResultList.value = []
      ticketResultEditable.value = false
      clearTicketResultImageUploading()
    } else if (isRepair.value) {
      // 提交维修单
      const payload: any = {
        repairCode: repairFormData.isCode ? undefined : repairFormData.repairCode,
        repairName: repairFormData.repairName,
        moldId: props.mold?.id,
        moldCode: props.mold?.code ?? '',
        moldName: props.mold?.name ?? '',
        machinerySpec: '',
        requireDate: repairFormData.requireDate,
        repairResult: '',
        repairStatus: '',
        repairReporter: normalizeUserId(repairFormData.repairReporter),
        acceptedBy: normalizeUserId(repairFormData.acceptedBy),
        confirmBy: normalizeUserId(repairFormData.confirmBy),
        faultLevel: repairFormData.faultLevel,
        shutdown: repairFormData.shutdown,
        faultPhenomenon: repairFormData.faultPhenomenon,
        faultDescription: repairFormData.faultDescription,
        faultImages: normalizeImageString(repairFormData.faultImages),
        isCode: repairFormData.isCode,
        repairedImages: '',
        remark: repairFormData.remark
      }
      await MoldRepairApi.createMoldRepair(payload)
      message.success(t('common.createSuccess'))
      // 先清除校验，再清空数据，避免触发必填校验
      maintainFormRef.value?.clearValidate()
      repairFormData.repairCode = undefined
      repairFormData.repairName = undefined
      repairFormData.requireDate = Date.now()
      repairFormData.repairReporter = undefined
      repairFormData.acceptedBy = undefined
      repairFormData.confirmBy = undefined
      repairFormData.faultLevel = undefined
      repairFormData.shutdown = undefined
      repairFormData.faultPhenomenon = undefined
      repairFormData.faultDescription = undefined
      repairFormData.faultImages = ''
      repairFormData.remark = undefined
      repairFormData.isCode = true
    } else if (isReplaceNet.value) {
      // 提交更换压网记录（批量）
      const createReqVOList = replaceNetFormData.moldIds.map((moldId: number) => {
        const selected = subMoldList.value.find((item: any) => item.id === moldId)
        return {
          moldBrandId: props.mold?.id,
          moldBrandName: props.mold?.name ?? '',
          moldId: moldId,
          moldName: selected?.name ?? '',
          pressureNetTime: replaceNetFormData.pressureNetTime,
          remark: replaceNetFormData.remark
        }
      })
      await MoldBrandApi.batchCreatePressureNetRecord(createReqVOList)
      message.success(t('common.createSuccess'))
      // 清空已提交的表单数据
      replaceNetFormData.moldIds = []
      replaceNetFormData.pressureNetTime = getCurrentDateTime()
      replaceNetFormData.remark = undefined
      await nextTick()
      maintainFormRef.value?.clearValidate()
    }
    emit('success')
  } catch (error) {
    console.error(t('MoldManagement.MoldBrandPage.submitFailed'), error)
  } finally {
    submitLoading.value = false
  }
}

const open = async () => {
  maintainFormData.maintainType = 1
  repairFormData.requireDate = Date.now()
  replaceNetFormData.pressureNetTime = getCurrentDateTime()
  await initOptions()
  if (!userStore.getIsSetUser) {
    try {
      await userStore.setUserInfoAction()
    } catch (e) {}
  }
  const currentUserId = userStore.getUser?.id
  if (currentUserId !== undefined && currentUserId !== null && Number(currentUserId) > 0) {
    repairFormData.repairReporter = String(currentUserId)
  }
}

defineExpose({ open })
</script>

<style scoped>
.mold-maintain-page__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.mold-maintain-page__info-card {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  flex: 1;
}

.mold-maintain-page__info-header,
.mold-maintain-page__form-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.mold-maintain-page__info-num {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background: var(--el-color-primary);
  color: #fff;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.mold-maintain-page__info-title {
  font-size: 15px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.mold-maintain-page__info-image-wrap {
  display: flex;
  justify-content: left;
}

.mold-maintain-page__info-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
}

.mold-maintain-page__info-empty {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  border: 1px dashed var(--el-border-color-lighter);
}

.mold-maintain-page__info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.mold-maintain-page__info-label {
  color: var(--el-text-color-secondary);
  font-size: 13px;
  white-space: nowrap;
  flex-shrink: 0;
  width: 90px;
  text-align: left;
}

.mold-maintain-page__info-value {
  color: var(--el-text-color-primary);
  font-size: 14px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  text-align: left;
}

.mold-maintain-page__body {
  display: flex;
  gap: 20px;
  align-items: stretch;
}

.mold-maintain-page__sidebar {
  width: 260px;
  flex-shrink: 0;
  display: flex;
}

.mold-maintain-page__form {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  background: #fff;
  border-radius: 12px;
  padding: 24px 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

:deep(.el-form-item__label) {
  white-space: nowrap;
}

.mold-maintain-inspect-layout {
  display: flex;
  flex-direction: column;
  gap: 20px;
  align-items: stretch;
}

.mold-maintain-inspect-layout__form {
  min-width: 0;
}

.mold-maintain-ticket-results {
  min-width: 0;
  padding: 14px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  background: #fafafa;
}

.mold-maintain-ticket-results__header {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
  margin-bottom: 12px;
}

.mold-maintain-ticket-results__title {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.mold-maintain-ticket-results :deep(.el-upload) {
  margin: 0 auto;
}

.ticket-result-images {
  display: flex;
  justify-content: center;
  min-height: 56px;
}

.ticket-result-images :deep(.el-upload-list--picture-card) {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  gap: 8px;
}

.ticket-result-images.is-full :deep(.el-upload--picture-card) {
  display: none;
}

@media (max-width: 1400px) {
}

.mold-maintain-page__form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.dv-repair-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.dv-repair-section__title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.dv-repair-label {
  display: inline-flex;
  gap: 4px;
  align-items: center;

  &.is-required::before {
    color: var(--el-color-danger);
    content: '*';
  }
}

.dv-repair-code-row {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 维护类型卡片样式 */
.mold-maintain-type-card {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.mold-maintain-type-card__item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border-radius: 12px;
  border: 2px solid var(--el-border-color-lighter);
  cursor: pointer;
  transition: all 0.25s ease;
  background: #fff;

  &:hover {
    border-color: var(--el-color-primary);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &.is-active {
    border-color: var(--el-color-primary);
    background: rgba(64, 158, 255, 0.06);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  }
}

.mold-maintain-type-card__icon {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  transition: transform 0.25s ease;

  .mold-maintain-type-card__item:hover & {
    transform: scale(1.1);
  }
}

.mold-maintain-type-card__label {
  font-size: 14px;
  color: var(--el-text-color-primary);
  font-weight: 500;
}

.mold-maintain-type-card__item.is-active .mold-maintain-type-card__label {
  color: var(--el-color-primary);
}

.project-form-dialog-content {
  max-height: 500px;
  overflow-y: auto;
}
</style>
