<script setup>
import {useRoute, useRouter} from "vue-router";
import {AuditRuleEnums} from "@/enums/AuditRuleEnums.ts"
import feedback from "@/utils/feedback";
import {
  getWarningBusiness,
  saveWarningBusiness,
  endWarningBusiness,
  auditRejectWarning, getWarningFlowList
} from '@/api/warning/business'
import { timeFormat } from '@/utils/util'
import warningDetail from './components/detail.vue'
import reportAudit from '@/components/reportAudit/start.vue'
import finishDistrbute from '@/components/reportAudit/finishDistrbute.vue'
import useTabsStore from "@/stores/modules/multipleTabs";

const { removeTab } = useTabsStore();
const route = useRoute()
const router = useRouter()

const loading = ref(false)

// 审批记录相关
const reportFlowDialog = ref(false)
const reportFlowLoading = ref(false)
const reportFlowTable = ref([])

// 详情相关
const detailShow = ref(false)
const detailProps = ref({})

// 提交给领导弹窗相关
const dialog = ref(false)
const warningCode = ref("warning")
const node = ref("leader")

// 领导通过弹窗相关
const finishDialog = ref(false)

// 表单数据
const formData = ref({
  reportProject: {},
  record: {},
  contents: []
})

// 行样式（已填写备注的行高亮）
const tableRowClassName = ({row}) => {
  return row.remark ? 'warning-row' : ''
}

// 是否为查看模式（已预警或有 flowId 但不是待审批状态）
const isViewMode = computed(() => {
  return formData.value.reportProject.warningState === '1'
})

// 是否为领导审批模式（warning_state='2' 且有 flowId）
const isLeaderMode = computed(() => {
  return formData.value.reportProject.warningState === '2' && route.query.flowId
})

// 问题详情是否可编辑
const canEditRemark = computed(() => {
  return formData.value.reportProject.warningState === '0'
      // ||
      //    (formData.value.reportProject.warningState === '2' && !route.query.flowId)
})

// 加载数据
const loadData = async () => {
  console.log(route.query)
  const reportId = route.query.reportId
  if (!reportId) {
    closePage()
    return
  }

  loading.value = true
  try {
    // 获取预警业务数据
    const res = await getWarningBusiness(reportId)

    // 填充项目信息
    formData.value.reportProject = res.reportProject || {}
    formData.value.record = res.record || {}

    // 填充预警内容（已有数据则用已有数据，否则用枚举）
    if (res.contents && res.contents.length > 0) {
      formData.value.contents = res.contents
    } else {
      formData.value.contents = AuditRuleEnums.map(item => ({
        ...item,
        remark: ''
      }))
    }
  } catch (e) {
    console.error('加载数据失败', e)
  } finally {
    loading.value = false
  }
}

// 保存
const handleSave = async () => {
  loading.value = true
  try {
    await saveWarningBusiness({
      reportId: route.query.reportId,
      contents: formData.value.contents.map(c => ({
        type: c.type,
        title: c.title,
        content: c.content,
        remark: c.remark || ''
      }))
    })
    feedback.msgSuccess('保存成功')
    loadData()
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

// 直接结束
const handleEnd = async () => {
  await feedback.confirm('确定直接结束预警吗？')

  loading.value = true
  try {
    await endWarningBusiness({
      reportId: route.query.reportId,
      contents: formData.value.contents.map(c => ({
        type: c.type,
        title: c.title,
        content: c.content,
        remark: c.remark || ''
      })),
      flowId: route.query.flowId,
    })
    feedback.msgSuccess('操作成功')
    closePage()
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

// 提交给领导
const handleSubmit = async () => {
  debugger
  loading.value = true
  try {
    await saveWarningBusiness({
      reportId: route.query.reportId,
      contents: formData.value.contents.map(c => ({
        type: c.type,
        title: c.title,
        content: c.content,
        remark: c.remark || ''
      })),

    })
    loading.value = false
    dialog.value = true
  } catch (e) {
    loading.value = false
    console.error(e)
  }
}

// 弹窗提交成功回调
const submitFeedback = () => {
  dialog.value = false
  closePage()
}

// 关闭弹窗回调
const closeAuditDialogFun = () => {
  dialog.value = false
}

// 领导通过
const handlePass = () => {
  finishDialog.value = true
}

// 弹窗提交成功回调
const FinishSubmitFeedback = () => {
  finishDialog.value = false
  feedback.msgSuccess('审批通过')
  closePage()
}

// 关闭弹窗回调
const FinishCloseAuditDialogFun = () => {
  finishDialog.value = false
}

// 领导驳回
const handleReject = async () => {
  loading.value = true
  try {
    await auditRejectWarning({
      flowId: route.query.flowId,
      reportId: route.query.reportId,
      approverMessage: ''
    })
    feedback.msgSuccess('已驳回')
    closePage()
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

// 打开审批记录
const getAuditTableFun = async () => {
  reportFlowDialog.value = true
  reportFlowLoading.value = true
  const res = await getWarningFlowList(route.query.reportId)
  reportFlowLoading.value = false
  reportFlowTable.value = res
}

// 打开详情
const DetailReport = () => {
  detailProps.value = {
    isEnd: formData.value.reportProject.reportType === "结算项目",
    id: formData.value.reportProject.id,
    backPath: '/entryWindow',
    node: formData.value.reportProject.node
  }
  detailShow.value = true
}

// 关闭详情
const closeDetailShow = () => {
  detailShow.value = false
}

// 取消/返回
const handleCancel = () => {
  closePage()
}

const closePage = () => {
  removeTab('/warning/business', router)
  router.back()
}

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

<template>
  <div class="warning-business-page" v-loading="loading">
    <!-- 报审信息 -->
    <div class="section">
      <h5>报审信息</h5>
      <el-form :model="formData.reportProject" label-width="140">
        <el-row>
          <el-col :span="6">
            <el-form-item label="报审类型">
              <el-input :model-value="formData.reportProject.reportType" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目名称">
              <el-input :model-value="formData.reportProject.reportName" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目类别">
              <el-input :model-value="formData.reportProject.projectType" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审计单位">
              <el-input :model-value="formData.reportProject.auditUnit" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="项目单位">
              <el-input :model-value="formData.reportProject.projectUnit" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目负责人">
              <el-input :model-value="formData.reportProject.projectPrincipal" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="负责人联系方式">
              <el-input :model-value="formData.reportProject.projectPhone" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报审金额（元）">
              <el-input :model-value="formData.reportProject.reportMoney" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="立项日期">
              <el-input :model-value="formData.reportProject.projectApprovalTime || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="立项金额（元）">
              <el-input :model-value="formData.reportProject.projectApprovalMoney" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="立项审批领导">
              <el-input :model-value="formData.reportProject.projectApprovalLead" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报审人">
              <el-input :model-value="formData.reportProject.applicant" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购方式">
              <el-input :model-value="formData.reportProject.purchaseMethod || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报审日期">
              <el-input :model-value="formData.reportProject.applicantTime" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文号">
              <el-input :model-value="formData.reportProject.referenceNumber" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发文日期">
              <el-input :model-value="formData.reportProject.publicationDate" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.reportProject.reportType === '结算项目'">
          <el-col :span="6">
            <el-form-item label="合同签订日期">
              <el-input :model-value="formData.reportProject.contractTime || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同金额">
              <el-input :model-value="formData.reportProject.contractMount" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务单位">
              <el-input :model-value="formData.reportProject.serviceUnit || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务单位负责人">
              <el-input :model-value="formData.reportProject.serviceUnitManager || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.reportProject.reportType === '结算项目'">
          <el-col :span="6">
            <el-form-item label="服务日期">
              <el-input :model-value="formData.reportProject.serviceTime || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务单位联系电话">
              <el-input :model-value="formData.reportProject.serviceUnitPhone || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审减金额">
              <el-input :model-value="formData.reportProject.archivingReduceMoney" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.reportProject.reportType === '结算项目'">
          <el-col :span="6">
            <el-form-item label="归档时间">
              <el-input :model-value="formData.reportProject.archiving || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审定金额（元）">
              <el-input :model-value="formData.reportProject.archivingMoney" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 预警监督信息 -->
    <div class="section">
      <h5>预警监督信息</h5>
      <el-form :model="formData.reportProject" label-width="140">
        <el-row>
          <el-col :span="6">
            <el-form-item label="预警监督状态">
              <el-input :model-value="{
                '0': '未预警监督',
                '1': '已预警监督',
                '2': '预警中'
              }[formData.reportProject.warningState] || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预警监督人员">
              <el-input :model-value="formData.reportProject.warningSupervision || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预警监督日期">
              <el-input :model-value="formData.reportProject.supervisionTime || '-'" readonly class="select-disabled-like"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label=" ">
              <el-button type="primary" style="width: 100%" @click="DetailReport">详情</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 预警监督情况 -->
    <div class="section">
      <h5>预警监督情况</h5>
      <el-table :data="formData.contents" border :row-class-name="tableRowClassName">
        <el-table-column label="序号" type="index" width="60" align="center"/>
        <el-table-column label="预警类型" prop="type" width="120"/>
        <el-table-column label="预警标题" prop="title" width="150"/>
        <el-table-column label="预警内容" prop="content"/>
        <el-table-column label="问题详情" min-width="200">
          <template #default="{ row }">
            <el-input
              v-model="row.remark"
              type="textarea"
              :rows="2"
              :disabled="!canEditRemark"
              placeholder="请填写问题详情"/>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 操作按钮 -->
    <div class="flex end mt-20">
      <!-- 待预警状态 (warning_state = '0')：预警人操作 -->
      <template v-if="formData.reportProject.warningState === '0'">
        <el-button type="primary" @click="handleSave" :loading="loading">保存</el-button>
        <el-button type="warning" @click="handleEnd" :loading="loading">直接结束</el-button>
        <el-button type="success" @click="handleSubmit" :loading="loading">提交给领导</el-button>
      </template>

      <!-- 预警中状态 (warning_state = '2')：领导审批操作 -->
      <template v-else-if="isLeaderMode">
        <el-button type="danger" @click="handleReject" :loading="loading">驳回</el-button>
        <el-button type="success" @click="handlePass" :loading="loading">通过</el-button>
      </template>

      <el-button type="primary" @click="getAuditTableFun" :loading="reportFlowLoading">审批记录</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>

    <!-- 审批记录弹窗 -->
    <el-dialog v-model="reportFlowDialog" title="审批记录" width="80vw">
      <div class="table-container">
        <el-table :data="reportFlowTable" v-loading="reportFlowLoading">
          <el-table-column width="50" type="index" label="序号" :index="(index) => index + 1"/>
          <el-table-column label="操作" prop="reportCode"/>
          <el-table-column label="办理人" prop="approver"/>
          <el-table-column label="提交时间" prop="areportTime">
            <template #default="{row}">
              {{ timeFormat(row.areportTime, 'yyyy-mm-dd hh:MM:ss') }}
            </template>
          </el-table-column>
          <el-table-column label="完成时间" prop="approverTime">
            <template #default="{row}">
              {{ timeFormat(row.approverTime, 'yyyy-mm-dd hh:MM:ss') }}
            </template>
          </el-table-column>
          <el-table-column label="办理结果" prop="approverState">
            <template #default="{row}">
              <el-tag type="primary" v-if="row.approverState === 'start'">开始</el-tag>
              <el-tag type="success" v-if="row.approverState === 'end'">完成</el-tag>
              <el-tag type="danger" v-if="row.approverState === 'reject'">驳回</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="办理意见" prop="approverMessage" show-overflow-tooltip/>
<!--          <el-table-column label="办理状态" prop="approverState"/>-->
        </el-table>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailShow" title="项目详情" width="90vw" @close="closeDetailShow">
      <warningDetail
        :id="detailProps.id"
        :node="detailProps.node"
        :back-path="detailProps.backPath"
        :is-end="detailProps.isEnd"
        @close-page-fun="closeDetailShow">
      </warningDetail>
    </el-dialog>

    <!-- 提交给领导弹窗 -->
    <report-audit
      @submitFeedback="submitFeedback"
      @closeFun="closeAuditDialogFun"
      :isWarning="warningCode"
      :reportId="formData.reportProject.id"
      :dialog="dialog"
      :nextNode="node"
      :reportProject="formData.reportProject"
    />

    <!-- 领导通过弹窗 -->
    <finish-distrbute
      @submitFeedback="FinishSubmitFeedback"
      @closeFun="FinishCloseAuditDialogFun"
      :isWarning="true"
      :reportId="formData.reportProject.id"
      :flowId="route.query.flowId"
      :dialog="finishDialog"
      :nextNode="'end'"
    />
  </div>
</template>

<style lang="scss">
.warning-business-page {
  padding: 20px;
  background: #fff;
}

.section {
  margin-bottom: 20px;
}

.section h5 {
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #333;
  font-weight: 600;
}

.button-group {
  margin-top: 30px;
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #eee;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.select-disabled-like {
  --el-input-bg-color: #ffffff;
  --el-input-border-color: #dcdfe6;
  --el-input-text-color: #000000;

  .el-input__wrapper {
    background-color: #ffffff;
    box-shadow: 0 0 0 1px var(--el-disabled-border-color) inset;
    cursor: not-allowed;
  }

  .el-input__inner {
    color: #000000;
    -webkit-text-fill-color: #000000;
    cursor: text;
  }
}
</style>
