<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <div class="filter-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input v-model="queryParams.equipmentName" placeholder="请输入设备名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="使用状态" prop="usageStatus">
          <el-select v-model="queryParams.usageStatus" placeholder="请选择使用状态" clearable style="width: 200px">
            <el-option v-for="dict in equipment_usage_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="最近定/自检日期" prop="inspectionSelfCheckDate">
          <el-date-picker v-model="queryParams.inspectionSelfCheckDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" style="width: 200px" />
        </el-form-item>
        <el-form-item label="检查成员" prop="inspectionTeamUserName">
          <el-input v-model="queryParams.inspectionTeamUserName" placeholder="请输入检查成员" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-container">
      <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['equipment:ledger:add']">新增</el-button>
      <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleBatchDelete" v-hasPermi="['equipment:ledger:delete']">删除</el-button>
      <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['equipment:ledger:export']">导出</el-button>
      <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['equipment:ledger:import']">导入</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" prop="rowIndex" width="70" align="center">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="设备编号" prop="equipmentCode" align="center" min-width="120">
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{ scope.row.equipmentCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" prop="equipmentName" align="center" min-width="150" show-overflow-tooltip />
      <el-table-column label="设备序列号" prop="equipmentSerialNumber" align="center" min-width="150" show-overflow-tooltip />
      <el-table-column label="安装位置" prop="installationLocation" align="center" min-width="150" show-overflow-tooltip />
      <el-table-column label="使用状态" prop="usageStatus" align="center" min-width="100">
        <template #default="scope">
          <dict-tag :options="equipment_usage_status" :value="scope.row.usageStatus" />
          
        </template>
      </el-table-column>
      <el-table-column label="定/自检小组组长" prop="inspectionTeamLeaderName" align="center" min-width="120" show-overflow-tooltip />
      <el-table-column label="定/自检小组组员1" prop="inspectionTeamMember1Name" align="center" min-width="120" show-overflow-tooltip />
      <el-table-column label="定/自检小组组员2" prop="inspectionTeamMember2Name" align="center" min-width="120" show-overflow-tooltip />
      <el-table-column label="最近定检/自检日期" prop="inspectionSelfCheckDate" align="center" min-width="120" />
      <el-table-column label="操作" align="center" width="220" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 编辑/详情弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000px" :close-on-click-modal="false">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="160px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" placeholder="请输入设备名称" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备种类" prop="equipmentType">
              <el-input v-model="form.equipmentType" placeholder="请输入设备种类" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类别" prop="equipmentCategory">
              <el-input v-model="form.equipmentCategory" placeholder="请输入设备类别" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备品牌" prop="equipmentBrand">
              <el-input v-model="form.equipmentBrand" placeholder="请输入设备品牌" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="equipmentModel">
              <el-input v-model="form.equipmentModel" placeholder="请输入设备型号" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备序列号" prop="equipmentSerialNumber">
              <el-input v-model="form.equipmentSerialNumber" placeholder="请输入设备序列号" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出厂日期" prop="manufacturingDate">
              <el-date-picker v-model="form.manufacturingDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择出厂日期" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验收日期" prop="acceptanceDate">
              <el-date-picker v-model="form.acceptanceDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择验收日期" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用日期" prop="commissioningDate">
              <el-date-picker v-model="form.commissioningDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择启用日期" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用状态" prop="usageStatus">
              <el-select v-model="form.usageStatus" placeholder="请选择使用状态" :disabled="formDisabled">
                <el-option v-for="dict in equipment_usage_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报废日期" prop="scrappingDate">
              <el-date-picker v-model="form.scrappingDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择报废日期" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装位置" prop="installationLocation">
              <el-input v-model="form.installationLocation" placeholder="请输入安装位置" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定/自检日期" prop="inspectionSelfCheckDate">
              <el-date-picker v-model="form.inspectionSelfCheckDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择定/自检日期" :disabled="formDisabled" @change="calculateDueDate" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定/自检周期" prop="inspectionSelfCheckCycle">
              <el-input-number v-model="form.inspectionSelfCheckCycle" placeholder="请输入定/自检周期" :min="0" :precision="0" :disabled="formDisabled" @change="calculateDueDate" />&nbsp;月
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最近定/自检到期日期" prop="nextInspectionDueDate">
              <el-date-picker v-model="form.nextInspectionDueDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择最近定/自检到期日期" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定/自检小组组长" prop="inspectionTeamLeaderId">
              <UserSelect v-model="form.inspectionTeamLeaderId" :disabled="formDisabled" width="100%" placeholder="请选择组长" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定/自检小组组员1" prop="inspectionTeamMember1Id">
              <UserSelect v-model="form.inspectionTeamMember1Id" :disabled="formDisabled" width="100%" placeholder="请选择组员1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定/自检小组组员2" prop="inspectionTeamMember2Id">
              <UserSelect v-model="form.inspectionTeamMember2Id" :disabled="formDisabled" width="100%" placeholder="请选择组员2" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="首次验收情况" prop="initialAcceptanceStatus">
              <el-input v-model="form.initialAcceptanceStatus" type="textarea" :rows="3" placeholder="请输入首次验收情况" :disabled="formDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设备图片" prop="baseAttachmentList">
              <ImageUpload v-model="form.baseAttachmentList" :disabled="formDisabled" :limit="3" result-type="object" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 定检记录表格 -->
        <el-divider content-position="left">定检记录</el-divider>
        <el-button type="primary" plain icon="Plus" @click="addCheckRecord" v-if="!formDisabled">新增定检记录</el-button>
        <el-table :data="form.equipmentInspectionRecordList" border style="margin-top: 10px">
          <el-table-column label="定检日期" prop="inspectionDate">
            <template #default="scope">
              <el-date-picker v-model="scope.row.inspectionDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" :disabled="formDisabled" @change="handleInspectionDateChange(scope.row, scope.$index)" />
            </template>
          </el-table-column>
          <el-table-column label="定检小组" prop="inspectionTeamName">
            <template #default="scope">
              <UserSelect v-model="scope.row.inspectionTeamIds" :multiple="true" :disabled="formDisabled" width="100%" placeholder="请选择" />
            </template>
          </el-table-column>
          <el-table-column label="定检结论" prop="inspectionResult">
            <template #default="scope">
              <el-input v-model="scope.row.inspectionResult" placeholder="定检结论" :disabled="formDisabled" />
            </template>
          </el-table-column>
          <el-table-column label="定检性质" prop="inspectionNature">
            <template #default="scope">
              <el-select v-model="scope.row.inspectionNature" placeholder="请选择" :disabled="formDisabled">
                <el-option v-for="dict in equipment_inspection_nature" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" v-if="!formDisabled">
            <template #default="scope">
              <el-button type="danger" link icon="Delete" @click="removeCheckRecord(scope.$index)" v-hasPermi="['equipment:ledger:delete']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" v-if="!formDisabled">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import UserSelect from '@/components/UserSelect/index.vue'
import { listEquipLedger, getEquipLedger, addEquipLedger, updateEquipLedger, delEquipLedger, exportEquipLedger } from '@/api/equipManage/equipLedger'
import { getUser } from '@/api/system/user'
import { getToken } from '@/utils/auth'

const { proxy } = getCurrentInstance()

const { equipment_usage_status, equipment_inspection_nature } = proxy.useDict('equipment_usage_status', 'equipment_inspection_nature')

const loading = ref(false)

const queryFormRef = ref()
const formRef = ref()
const tableData = ref([])
const total = ref(0)
const single = ref(true)
const multiple = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  equipmentName: '',
  usageStatus: '',
  inspectionSelfCheckDate: '',
  inspectionTeamUserName: ''
})
const dialog = reactive({
  visible: false,
  title: ''
})
const formDisabled = ref(false)
const form = reactive({
  id: null,
  equipmentName: '',
  equipmentType: '',
  equipmentCategory: '',
  equipmentBrand: '',
  equipmentModel: '',
  equipmentSerialNumber: '',
  manufacturer: '',
  manufacturingDate: '',
  acceptanceDate: '',
  commissioningDate: '',
  usageStatus: '',
  scrappingDate: '',
  installationLocation: '',
  inspectionSelfCheckDate: '',
  inspectionSelfCheckCycle: 0,
  nextInspectionDueDate: '',
  inspectionTeamLeaderId: '',
  inspectionTeamMember1Id: '',
  inspectionTeamMember2Id: '',
  initialAcceptanceStatus: '',
  baseAttachmentList: [],
  equipmentInspectionRecordList: []
})
const baseAttachmentListInternal = ref([])

watch(() => form.baseAttachmentList, (newVal) => {
  if (newVal && Array.isArray(newVal)) {
    baseAttachmentListInternal.value = newVal.map(item => ({
      attachmentName: item.name || item.originalFilename || '',
      attachmentUrl: item.url || ''
    }))
  }
}, { deep: true, immediate: true })
const rules = {
  equipmentName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  equipmentSerialNumber: [{ required: true, message: '设备序列号不能为空', trigger: 'blur' }]
}
const selectedIds = ref([])

const upload = reactive({
  open: false,
  title: '',
  isUploading: false,
  updateSupport: 0,
  headers: { Authorization: 'Bearer ' + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + '/equipment/ledger/importData'
})

function getList() {
  loading.value = true
  listEquipLedger(queryParams).then(response => {
    tableData.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

function handleSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

function handleAdd() {
  resetForm()
  formDisabled.value = false
  dialog.title = '新增设备'
  dialog.visible = true
}

function handleEdit(row) {
  getEquipLedger(row.id).then(response => {
    Object.assign(form, response.data)
    if (form.baseAttachmentList && Array.isArray(form.baseAttachmentList)) {
      form.baseAttachmentList = form.baseAttachmentList.map(item => ({
        name: item.attachmentName || item.name || '',
        url: item.attachmentUrl || item.url || ''
      }))
    } else {
      form.baseAttachmentList = []
    }
    if (!form.equipmentInspectionRecordList || !Array.isArray(form.equipmentInspectionRecordList)) {
      form.equipmentInspectionRecordList = []
    }
    formDisabled.value = false
    dialog.title = '编辑设备'
    dialog.visible = true
  })
}

function handleDetail(row) {
  getEquipLedger(row.id).then(response => {
    Object.assign(form, response.data)
    if (form.baseAttachmentList && Array.isArray(form.baseAttachmentList)) {
      form.baseAttachmentList = form.baseAttachmentList.map(item => ({
        name: item.attachmentName || item.name || '',
        url: item.attachmentUrl || item.url || ''
      }))
    } else {
      form.baseAttachmentList = []
    }
    if (!form.equipmentInspectionRecordList || !Array.isArray(form.equipmentInspectionRecordList)) {
      form.equipmentInspectionRecordList = []
    }
    formDisabled.value = true
    dialog.title = '设备详情'
    dialog.visible = true
  })
}

function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除该设备？').then(function () {
    return delEquipLedger(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => { })
}

function handleBatchDelete() {
  proxy.$modal.confirm('是否确认删除选中的设备？').then(function () {
    return delEquipLedger(selectedIds.value.join(','))
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => { })
}

function handleExport() {
  proxy.download('equipment/ledger/export', {
    ...queryParams
  }, `equipLedger_${new Date().getTime()}.xlsx`)
}

function handleImport() {
  upload.title = '设备台账导入'
  upload.open = true
}

function importTemplate() {
  proxy.download('equipment/ledger/importTemplate', {}, `equipLedger_template_${new Date().getTime()}.xlsx`)
}

function resetForm() {
  Object.assign(form, {
    id: null,
    equipmentName: '',
    equipmentType: '',
    equipmentCategory: '',
    equipmentBrand: '',
    equipmentModel: '',
    equipmentSerialNumber: '',
    manufacturer: '',
    manufacturingDate: '',
    acceptanceDate: '',
    commissioningDate: '',
    usageStatus: '1',
    scrappingDate: '',
    installationLocation: '',
    inspectionSelfCheckDate: '',
    inspectionSelfCheckCycle: 0,
    nextInspectionDueDate: '',
    inspectionTeamLeaderId: '',
    inspectionTeamMember1Id: '',
    inspectionTeamMember2Id: '',
    initialAcceptanceStatus: '',
    baseAttachmentList: [],
    equipmentInspectionRecordList: []
  })
}

async function submitForm() {
  formRef.value?.validate(async valid => {
    if (valid) {
      const submitData = { ...form }
      submitData.baseAttachmentList = baseAttachmentListInternal.value
      
      try {
        if (submitData.inspectionTeamLeaderId) {
          const leaderRes = await getUser(submitData.inspectionTeamLeaderId)
          submitData.inspectionTeamLeaderName = leaderRes.data?.nickName || ''
        }
        if (submitData.inspectionTeamMember1Id) {
          const member1Res = await getUser(submitData.inspectionTeamMember1Id)
          submitData.inspectionTeamMember1Name = member1Res.data?.nickName || ''
        }
        if (submitData.inspectionTeamMember2Id) {
          const member2Res = await getUser(submitData.inspectionTeamMember2Id)
          submitData.inspectionTeamMember2Name = member2Res.data?.nickName || ''
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }

      if (submitData.id != null) {
        updateEquipLedger(submitData).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          dialog.visible = false
          getList()
        })
      } else {
        addEquipLedger(submitData).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          dialog.visible = false
          getList()
        })
      }
    }
  })
}

function addCheckRecord() {
  const teamIds = []
  if (form.inspectionTeamLeaderId) {
    teamIds.push(form.inspectionTeamLeaderId)
  }
  if (form.inspectionTeamMember1Id) {
    teamIds.push(form.inspectionTeamMember1Id)
  }
  if (form.inspectionTeamMember2Id) {
    teamIds.push(form.inspectionTeamMember2Id)
  }
  form.equipmentInspectionRecordList.push({
    inspectionDate: '',
    inspectionTeamIds: teamIds,
    inspectionTeamName: '',
    inspectionResult: '',
    inspectionNature: ''
  })
}

function removeCheckRecord(index) {
  form.equipmentInspectionRecordList.splice(index, 1)
}

function handleInspectionDateChange(row, index) {
  if (row.inspectionDate) {
    const recordDate = new Date(row.inspectionDate)
    const checkDate = form.inspectionSelfCheckDate ? new Date(form.inspectionSelfCheckDate) : null
    
    if (!checkDate || recordDate > checkDate) {
      form.inspectionSelfCheckDate = row.inspectionDate
      calculateDueDate()
    }
  }
}

function calculateDueDate() {
  if (form.inspectionSelfCheckDate && form.inspectionSelfCheckCycle && form.inspectionSelfCheckCycle > 0) {
    const checkDate = new Date(form.inspectionSelfCheckDate)
    checkDate.setMonth(checkDate.getMonth() + form.inspectionSelfCheckCycle)
    const year = checkDate.getFullYear()
    const month = String(checkDate.getMonth() + 1).padStart(2, '0')
    const day = String(checkDate.getDate()).padStart(2, '0')
    form.nextInspectionDueDate = `${year}-${month}-${day}`
  }
}

function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true
}

function handleFileSuccess(response, file, fileList) {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].handleRemove(file)
  proxy.$alert('<div style="overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;">' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
  getList()
}

function submitFileForm() {
  proxy.$refs['uploadRef'].submit()
}

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

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
}

.operation-container {
  margin-bottom: 15px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>