<template>
  <el-dialog
    v-model="dialogVisible"
    title="修改后任务单详情"
    width="80%"
    draggable
    :close-on-click-modal="false"
    :before-close="handleClose"
    top="5vh"
  >
    <div v-if="!taskOrderData" class="loading-text">无法加载任务单详情。</div>
    <div v-else class="dialog-body">
      <!-- 受检信息 -->
      <ContentWrap title="受检信息">
        <el-form :model="formData" label-width="90px" disabled class="p-3">
          <div class="check-info-label-title">申请单位</div>
          <el-row class="form-group" :gutter="24">
            <el-col :span="8">
              <el-form-item label="申请单位名称" prop="unitName">
                <el-input v-model="formData.unitName" placeholder="请输入单位名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="统一社会信用代码" prop="socialCreditCode" label-width="120px">
                <el-input v-model="formData.socialCreditCode" placeholder="请输入统一社会信用代码" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申请单位地址" prop="unitAddress" label-width="120px">
                <el-input v-model="formData.unitAddress" placeholder="请输入申请单位地址" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="邮政编码" prop="zipCode">
                <el-input v-model="formData.zipCode" placeholder="请输入邮政编码" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="约检联系人" prop="unitContact">
                <el-input v-model="formData.unitContact" placeholder="请输入约检联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="约检联系人电话" prop="unitPhone" label-width="120px">
                <el-input v-model="formData.unitPhone" placeholder="请输入约检联系人电话" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电子报告接收人" prop="recipient" label-width="120px">
                <el-input v-model="formData.recipient" placeholder="请输入电子报告接收人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="接收人电话" prop="recipientPhone">
                <el-input v-model="formData.recipientPhone" placeholder="请输入接收人电话" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="接收人邮箱" prop="recipientEmail">
                <el-input v-model="formData.recipientEmail" placeholder="请输入接收人邮箱" />
              </el-form-item>
            </el-col>
          </el-row>

          <div class="check-info-label-title">使用单位</div>
          <el-row class="form-group" :gutter="24">
            <el-col :span="8">
              <el-form-item label="使用单位名称" prop="useUnitName">
                <el-input v-model="formData.useUnitName" placeholder="请输入使用单位名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="统一社会信用代码" prop="useUnitSocialCreditCode" label-width="120px">
                <el-input v-model="formData.useUnitSocialCreditCode" placeholder="请输入统一社会信用代码" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="使用单位地址" prop="useUnitAddress" label-width="120px">
                <el-input v-model="formData.useUnitAddress" placeholder="请输入使用单位地址" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="邮政编码" prop="useUnitZipcode">
                <el-input v-model="formData.useUnitZipcode" placeholder="请输入邮政编码" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位联系人" prop="useUnitContact" label-width="120px">
                <el-input v-model="formData.useUnitContact" placeholder="请输入单位联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人电话" prop="useUnitPhone" label-width="120px">
                <el-input v-model="formData.useUnitPhone" placeholder="请输入联系人电话" />
              </el-form-item>
            </el-col>
          </el-row>

          <div class="check-info-label-title">受理信息</div>
          <el-row class="form-group" :gutter="24">
            <el-col :span="8">
              <el-form-item label="检验部门" prop="deptId">
                <el-input v-model="formData.deptName" placeholder="检验部门" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话" prop="deptPhone" label-width="120px">
                <el-input v-model="formData.deptPhone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="约检时间" prop="checkDate" label-width="120px">
                <el-input v-model="formData.checkDate" placeholder="请选择约检时间" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="检验员" prop="teamList">
                <div v-if="formattedCheckers.length > 0" class="selected-checkers">
                  <el-tag
                    v-for="checker in formattedCheckers"
                    :key="checker.id"
                    effect="plain"
                  >
                    {{ checker.label }}
                  </el-tag>
                </div>
                <span v-else>-</span>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="check-info-label-title">检验收费</div>
          <el-row class="form-group" :gutter="24">
            <el-col :span="24">
              <el-form-item label="检验性质" prop="checkType" label-width="120px">
                <el-input :value="checkTypeLabel" disabled class="!w-120px" />
              </el-form-item>
              <el-form-item prop="feeNature" label-width="120px">
                <template #label>
                  <div class="flex flex-col text-right">
                    <span>收费性质</span>
                    <span>(行政事业收费)</span>
                  </div>
                </template>
                <el-radio-group v-model="formData.feeNature" disabled>
                  <el-radio v-for="(item, key) in PressureFeeNatureMap" :key="key" :value="key" :label="item" />
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="收费形式" prop="feeType" label-width="120px">
                <el-radio-group v-model="formData.feeType" disabled>
                  <el-radio v-for="(item, key) in PressureFeeTypeMap" :key="key" :value="key" :label="item" />
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <div class="flex items-center gap-32 ml-40px text-14px">
                <span>应收法定金额: {{ formData.shouldAmount }}</span>
                <span>服务收费金额: {{ formData.serviceAmount }}</span>
                <span>免征费用: {{ formData.reduceFee }}</span>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </ContentWrap>

      <!-- 设备清单 -->
      <div class="plan-section mt-4">
        <div class="section-title">
          <span>设备信息</span>
        </div>
        <ContentWrap>
          <el-table
            :data="taskOrderData.orderItems || []"
            border
            stripe
            empty-text="暂无设备信息"
          >
            <el-table-column label="区域" align="center" min-width="120">
              <template #default="{ row }">
                <div>{{ row.equipDistrictName || '-' }}</div>
                <div class="text-gray-400 text-sm">{{ row.equipStreetName || '' }}</div>
              </template>
            </el-table-column>
            <el-table-column label="设备注册代码" align="center" min-width="190">
              <template #default="{ row }">
                <el-tag type="primary" size="small">{{ row.equipCode || '-' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="是否租借" align="center" prop="isRent" min-width="80">
              <template #default="{ row }">
                {{ row.isRent ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column label="使用证编号" align="center" prop="useRegisterNo" min-width="120" />
            <el-table-column label="出厂编号" align="center" prop="factoryCode" min-width="120" />
            <el-table-column label="约检联系人" align="center" prop="contact" min-width="120" />
            <el-table-column label="约检联系人电话" align="center" prop="contactPhone" min-width="140" />
            <el-table-column label="蒸发量" align="center" prop="maxContinueEvapor" min-width="80" />
            <el-table-column label="型号" align="center" prop="boilerModel" min-width="120" />
          </el-table>
        </ContentWrap>
      </div>

      <!-- 备注 -->
      <ContentWrap title="备注" class="mt-4">
        <el-row>
          <el-col :span="12">
            <el-form-item class="!mb-0" label="上次退回原因" prop="reason">
              <el-input type="textarea" :rows="4" v-model="formData.reason" readonly disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </ContentWrap>
    </div>

    <template #footer>
      <div class="flex justify-center">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { formatArrayDate } from '@/utils/formatTime'
import {
  PressureFeeNatureMap,
  PressureFeeTypeMap,
  PressureBoilerCheckTypeMap
} from '@/utils/constants'

defineOptions({ name: 'BoilerTaskOrderDetailViewDialog' })

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  taskOrder: {
    type: Object as () => Record<string, any>,
    default: () => ({})
  }
})

const emit = defineEmits<{
  'update:visible': [value: boolean]
}>()

const dialogVisible = ref(props.visible)

watch(() => props.visible, (val) => {
  dialogVisible.value = val
})

watch(dialogVisible, (val) => {
  emit('update:visible', val)
})

const taskOrderData = computed(() => props.taskOrder)

const checkStatusMap: Record<number, string> = {
  100: '内检',
  200: '外检',
  300: '耐压检'
}

const checkTypeLabel = computed(() => {
  const ct = formData.value.checkType
  if (!ct) return '-'
  return PressureBoilerCheckTypeMap[ct] || checkStatusMap[ct] || ct
})

const formData = ref({
  unitName: '',
  socialCreditCode: '',
  unitAddress: '',
  zipCode: '',
  unitContact: '',
  unitPhone: '',
  recipient: '',
  recipientPhone: '',
  recipientEmail: '',
  useUnitName: '',
  useUnitSocialCreditCode: '',
  useUnitAddress: '',
  useUnitZipcode: '',
  useUnitContact: '',
  useUnitPhone: '',
  deptName: '',
  deptPhone: '',
  checkDate: '',
  feeNature: '',
  feeType: '',
  shouldAmount: 0,
  serviceAmount: 0,
  reduceFee: 0,
  checkType: undefined as number | undefined,
  reason: ''
})

const formattedCheckers = computed(() => {
  const teamList = taskOrderData.value?.teamInfoList
  console.log("teamList",teamList)
  if (!teamList || !Array.isArray(teamList) || teamList.length === 0) return []

  const result: { id: string; label: string }[] = []
  teamList.forEach((team: any, teamIndex: number) => {
    if (team.isLeader) {
      result.push({
        id: `leader-${team.member.id || teamIndex}`,
        label: `组长: ${team.member.nickname || ''}`
      })
    }else{
      result.push({
        id: `member-${team.member.id || teamIndex}`,
        label: `${team.member.nickname || ''}`
      })
    }
  })
  return result
})

const initFormData = () => {
  const data = taskOrderData.value
  if (!data) return

  const dateVal = data.checkDate
    ? Array.isArray(data.checkDate)
      ? formatArrayDate(data.checkDate)
      : data.checkDate
    : ''

  formData.value = {
    unitName: data.unitName || '',
    socialCreditCode: data.socialCreditCode || '',
    unitAddress: data.unitAddress || '',
    zipCode: data.zipCode || '',
    unitContact: data.unitContact || '',
    unitPhone: data.unitPhone || '',
    recipient: data.recipient || '',
    recipientPhone: data.recipientPhone || '',
    recipientEmail: data.recipientEmail || '',
    useUnitName: typeof data.useUnitName === 'object' ? data.useUnitName?.name || '' : data.useUnitName || '',
    useUnitSocialCreditCode: data.useUnitSocialCreditCode || '',
    useUnitAddress: data.useUnitAddress || '',
    useUnitZipcode: data.useUnitZipcode || '',
    useUnitContact: data.useUnitContact || '',
    useUnitPhone: data.useUnitPhone || '',
    deptName: data.deptName || '',
    deptPhone: data.deptPhone || '',
    checkDate: dateVal,
    feeNature: String(data.feeNature || ''),
    feeType: String(data.feeType || ''),
    shouldAmount: data.shouldAmount ?? data.payAmount ?? 0,
    serviceAmount: data.serviceAmount ?? 0,
    reduceFee: data.reduceFee ?? 0,
    checkType: data.checkType,
    reason: data.reason || ''
  }
}

watch(() => props.taskOrder, () => {
  initFormData()
}, { immediate: true, deep: true })

const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style lang="scss" scoped>
.loading-text {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.dialog-body {
  max-height: 70vh;
  overflow-y: auto;
}

.check-info-label-title {
  width: 100%;
  line-height: 32px;
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  &::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 16px;
    background: var(--el-color-primary);
    margin-right: 8px;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding: 16px 0 8px;
  display: flex;
  align-items: center;
  &::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 16px;
    background: var(--el-color-primary);
    margin-right: 8px;
  }
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 12px;
    align-items: center;
    &__label {
      height: auto;
      font-size: 13px;
      line-height: 20px;
      color: #606266;
      padding-right: 8px;
    }
  }
}

.selected-checkers {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 32px;
  padding: 4px 8px;
}
</style>
