<script setup lang="ts">
import {ref, computed, onMounted} from "vue";
import {ElMessage, FormInstance, FormRules} from 'element-plus';
import { ArrowDown, Printer, Download } from '@element-plus/icons-vue';
import {OrderReportApi} from "@/api/pressure2/orderreport";
import {SpreadViewer} from "@/components/DynamicReport";
import {InitParams} from "@/components/DynamicReport/SpreadInterface";
import {getPDF} from "@/api/laboratory/standard/template";
import {BoilerTaskOrderApi} from '@/api/pressure2/boilertaskorder';

const spreadRef=ref();
const props = defineProps({
  orderId: String,
  type: String,
});
const visible = defineModel('visible', { type: Boolean, default: false });
// 多报告支持
const orderList = ref<any[]>([])
const currentOrderIdx = ref(0)
const currentOrder = computed(() => orderList.value[currentOrderIdx.value] || {})
const initData=ref<InitParams>({
  templateId:'',
  refId:'',
  refName:'',
  insId:'',
  opType:1,
});

/** 推送相关 */
const pushDialogVisible = ref(false)
const pushFormType = ref('')
const submitting = ref(false)
const pushDialogFormRef = ref<FormInstance>()
const pushDialogFormData = ref({
  serviceFormReceiver: '',
  serviceFormReceiverPhone: '',
  serviceFormReceiverEmail: ''
})
const pushDialogFormRules = ref<FormRules>({
  serviceFormReceiver: [{ required: true, message: '请输入接收人名称' }],
  serviceFormReceiverPhone: [
    { required: true, message: '请输入接收人手机号码' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
  ],
  serviceFormReceiverEmail: [
    { required: true, message: '请输入接收人邮箱' },
    { type: 'email', message: '请输入正确的邮箱' }
  ]
})

const reloadCurrentReport = async () => {
  const current = currentOrder.value
  if (!current.templateId) return
  initData.value = {
    templateId: current.templateId,
    refId: current.acceptOrderId,
    refName: '',
    insId: '',
    opType: 1,
  }
  setTimeout(() => spreadRef.value?.reloadView(), 50)
}

const handlePrint = () => {
  const workbook = spreadRef.value?.getWorkbook?.()
  if (workbook) workbook.print()
  else ElMessage.warning('请先加载文档')
}

const handleDownload = async () => {
  try {
    const workbook = spreadRef.value?.getWorkbook?.()
    if (!workbook) return ElMessage.warning('请先加载文档')
    const formData = new FormData()
    await new Promise<void>((resolve, reject) => {
      workbook.save(async (blob) => {
        try {
          formData.append('file', blob)
          const response = await getPDF(formData)
          if (response) {
            const pdfBlob = new Blob([response], { type: 'application/pdf' })
            const url = window.URL.createObjectURL(pdfBlob)
            const link = document.createElement('a')
            link.href = url
            const fileName = currentOrder.value?.acceptOrderId
              ? `服务单_${currentOrder.value.acceptOrderId}_${new Date().getTime()}.pdf`
              : `服务单_${new Date().getTime()}.pdf`
            link.download = fileName
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
            ElMessage.success('下载成功')
            resolve()
          } else { reject(new Error('生成PDF失败')) }
        } catch (e) { reject(e) }
      }, (e) => reject(e), { includeBindingSource: true })
    })
  } catch { ElMessage.error('下载失败') }
}

const handlePushSubmit = (type: string) => {
  pushFormType.value = type
  pushDialogFormData.value = { serviceFormReceiver: '', serviceFormReceiverPhone: '', serviceFormReceiverEmail: '' }
  pushDialogFormRef.value?.resetFields()
  pushDialogVisible.value = true
}

const handlePushClose = () => { pushDialogVisible.value = false }

const handlePushConfirm = async () => {
  const valid = await pushDialogFormRef.value?.validate().catch(() => false)
  if (!valid) return
  submitting.value = true
  try {
    if (pushFormType.value === 'wx') {
      await BoilerTaskOrderApi.inspectionServicePush({
        equipMainType: props.type === 'pipe' ? "300" : "200",
        orderId: props.orderId,
        receiver: pushDialogFormData.value.serviceFormReceiver,
        receiverPhone: pushDialogFormData.value.serviceFormReceiverPhone,
        businessType: 100
      })
    } else {
      await BoilerTaskOrderApi.inspectionServiceEmailPush({
        id: props.orderId,
        businessType: 100,
        email: pushDialogFormData.value.serviceFormReceiverEmail,
        orderId: props.orderId,
        reportId: currentOrder.value.id,
      })
    }
    ElMessage.success('推送成功')
    pushDialogVisible.value = false
  } catch { ElMessage.error('推送失败') }
  finally { submitting.value = false }
}

const loadData = async () => {
  const orderPage = await OrderReportApi.getOrderReportPage({taskOrderId: props.orderId})
  if (orderPage.total > 0) {
    orderList.value = orderPage.list
    currentOrderIdx.value = 0
  } else {
    orderList.value = []
    return
  }
  for (const report of orderList.value) {
    if (props.type === 'pipe') await OrderReportApi.generatePipeOrderReport(report.acceptOrderId)
    else await OrderReportApi.generateBoilerOrderReport(report.acceptOrderId)
  }
  const refreshed = await OrderReportApi.getOrderReportPage({taskOrderId: props.orderId})
  if (refreshed.total > 0) orderList.value = refreshed.list

  initData.value.templateId = currentOrder.value.templateId
  initData.value.refId = currentOrder.value.acceptOrderId
  initData.value.opType = 1
  spreadRef.value?.reloadView()
}

const handleClose = () => { visible.value = false }

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

<template>
  <section v-if="visible">
    <ContentWrap title="服务单/受理单" class="order-record-wrapper !mb-[0px]">
      <div class="designer-inner">
        <div v-if="orderList.length > 1" class="report-tabs">
          <el-radio-group v-model="currentOrderIdx" size="small" @change="reloadCurrentReport">
            <el-radio-button v-for="(report, idx) in orderList" :key="report.id || idx" :label="idx">
              {{ `报告${idx + 1}` }}
            </el-radio-button>
          </el-radio-group>
        </div>
        <SpreadViewer :initData="initData" ref="spreadRef" :key="currentOrderIdx" />
      </div>
      <div class="operation-inner">
        <div class="btn-list">
          <el-dropdown class="mr-[12px]">
            <el-button type="success">
              推送<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="() => handlePushSubmit('wx')">小程序推送</el-dropdown-item>
                <el-dropdown-item @click="() => handlePushSubmit('email')">邮箱推送</el-dropdown-item>
                <el-dropdown-item @click="handleDownload">下载</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button type="primary" @click="handlePrint">
            <el-icon><Printer /></el-icon>
            打印
          </el-button>
          <el-button type="default" plain @click="handleClose">取 消</el-button>
        </div>
      </div>
    </ContentWrap>
  </section>

  <!-- 推送表单弹窗 -->
  <el-dialog v-model="pushDialogVisible" width="450px" :close-on-click-modal="false" align-center>
    <el-form ref="pushDialogFormRef" title="推送" :model="pushDialogFormData" :rules="pushDialogFormRules" label-width="140px" :validate-on-rule-change="false">
      <template v-if="pushFormType === 'wx'">
        <el-form-item label="接收人名称：" prop="serviceFormReceiver">
          <el-input v-model="pushDialogFormData.serviceFormReceiver" placeholder="请输入接收人名称" maxlength="20" show-word-limit class="!w-300px" />
        </el-form-item>
        <el-form-item label="接收人手机号码：" prop="serviceFormReceiverPhone">
          <el-input v-model="pushDialogFormData.serviceFormReceiverPhone" placeholder="请输入接收人手机号码" class="!w-300px" />
        </el-form-item>
      </template>
      <template v-if="pushFormType === 'email'">
        <el-form-item label="邮箱" prop="serviceFormReceiverEmail" :label-width="'auto'" class="mt-2">
          <el-input v-model="pushDialogFormData.serviceFormReceiverEmail" placeholder="请输入接收人邮箱" class="!w-full" />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button type="success" :loading="submitting" @click="handlePushConfirm">推送</el-button>
      <el-button plain @click="handlePushClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.app-container) {
  position: relative;
}
.order-record-wrapper {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 2000;
  :deep(.el-card__body) {
    display: flex;
    justify-content: space-between;
    align-items: stretch;
    height: calc(100% - 58px);
  }
}
.designer-inner {
  flex: 1;
  overflow: hidden;
  border: 1px solid var(--el-border-color);
  border-right-width: 0;
}
.report-tabs {
  padding: 6px 10px;
  background: #f5f7fa;
  border-bottom: 1px solid var(--el-border-color);
}
.operation-inner {
  display: flex;
  flex-direction: column;
  gap: 10px;
  flex-basis: 280px;
  padding: 7px 10px 20px;
  border: 1px solid var(--el-border-color);
  background-color: #fff;
  box-sizing: border-box;
  .btn-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    padding: 5px 0 2px;
    align-items: flex-start;
    .el-button { margin-left: 0; }
  }
}
</style>
