<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="申请" prop="searchKey">
        <el-input v-model="queryParams.searchKey" placeholder="申请编号/项目名称/项目编号/医保编码" clearable style="width: 280px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="可打印" prop="printable" label-width="80px">
        <el-checkbox v-model="queryParams.printable" true-label="1" false-label="0">是</el-checkbox>
      </el-form-item>
      <el-form-item label="项目分类" prop="itemType" label-width="100">
        <el-select v-model="queryParams.itemType" clearable style="width: 200px;">
          <el-option label="药品" value="1"></el-option>
          <el-option label="诊疗" value="2"></el-option>
        </el-select>
      </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>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">发起申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Printer" @click="handlePrint"
          :disabled="selectedRows.length === 0">打印申请单</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="ratioApplicationRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="申请编号" prop="applicationNo" :show-overflow-tooltip="true" />
      <el-table-column label="项目名称" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="项目编号" prop="busNo" :show-overflow-tooltip="true" />
      <el-table-column label="医保编码">
        <template #default="scope">
          <span v-if="scope.row.ybNo !== null && scope.row.ybNo !== undefined && scope.row.ybNo !== ''">
            {{ scope.row.ybNo }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="项目分类" prop="itemTypeName" :show-overflow-tooltip="true" align="center" width="100" />
      <!-- 自付比例列 -->
      <el-table-column label="自付比例" align="center" width="150">
        <template #default="scope">
          <span
            v-if="scope.row.applicationRatio !== null && scope.row.applicationRatio !== undefined && scope.row.applicationRatio !== ''">
            {{ scope.row.applicationRatio }}%
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- 二次自付比例列 -->
      <el-table-column label="二次自付比例" align="center" width="150">
        <template #default="scope">
          <span
            v-if="scope.row.twiceRatio !== null && scope.row.twiceRatio !== undefined && scope.row.twiceRatio !== ''">
            {{ scope.row.twiceRatio }}%
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" prop="startDate" :show-overflow-tooltip="true" align="center" width="150" />
      <el-table-column label="结束时间" prop="endDate" :show-overflow-tooltip="true" align="center" width="150" />
      <!-- 申请状态列 -->
      <el-table-column label="申请状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getApplicationStatusType(scope.row.applicationStatus)"
            :color="getApplicationStatusColor(scope.row.applicationStatus)"
            :style="{ color: getApplicationStatusTextColor(scope.row.applicationStatus) }" effect="plain" size="small">
            {{ getApplicationStatusName(scope.row.applicationStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批进度" width="150" align="center">
        <template #default="scope">
          <div class="progress-bar">
            <div v-for="(segment, index) in getApprovalProcess(scope.row)" :key="index"
              :class="getSegmentClass(segment, index)" class="progress-segment"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-tooltip content="详情" placement="top">
            <el-button link type="primary" icon="View" @click="openDialog(scope.row.id)">详情</el-button>
          </el-tooltip>
          <el-tooltip content="取消" placement="top"
            v-if="scope.row.applicationStatus == 0 && scope.row.initialApprovalResult == 0">
            <el-button link type="primary" icon="Close" @click="cancelApply(scope.row.id)">取消</el-button>
          </el-tooltip>
          <el-tooltip content="盈亏测算" placement="top"
            v-if="scope.row.applicationStatus == 0 && scope.row.initialApprovalResult == 0">
            <el-button link type="primary" icon="Money" @click="processApply(scope.row.id, 1)">盈亏测算</el-button>
          </el-tooltip>
          <el-tooltip content="财务报批" placement="top"
            v-if="scope.row.applicationStatus == 0 && scope.row.financeApprovalResult == 0">
            <el-button link type="primary" icon="DocumentChecked"
              @click="processApply(scope.row.id, 2)">财务报批</el-button>
          </el-tooltip>
          <el-tooltip content="上会决议" placement="top"
            v-if="scope.row.applicationStatus == 0 && scope.row.finalApprovalResult == 0">
            <el-button link type="primary" icon="ChatRound" @click="processApply(scope.row.id, 3)">上会决议</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="ratioApplicationRecordRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <!-- 左侧列 -->
          <el-col :span="12">
            <el-form-item label="项目分类" prop="itemType">
              <el-radio-group v-model="form.itemType">
                <el-radio :label="1">药品</el-radio>
                <el-radio :label="2">诊疗</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="自付比例" prop="applicationRatio">
              <el-input v-model="form.applicationRatio" placeholder="请输入自付比例" style="width: 100%" />
            </el-form-item>
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker v-model="form.startDate" type="date" placeholder="选择开始时间" value-format="YYYY-MM-DD"
                style="width: 100%;" />
            </el-form-item>
          </el-col>
          <!-- 右侧列 -->
          <el-col :span="12">
            <el-form-item label="申请项目" prop="definitionId">
              <el-input v-model="form.definitionName" placeholder="请选择申请项目" style="width: 100%"
                :disabled="!form.itemType" readonly @click="handleShowDefinitionDialog">
              </el-input>
            </el-form-item>
            <el-form-item label="二次自付比例" prop="twiceRatio">
              <el-input v-model="form.twiceRatio" placeholder="请输入二次自付比例" style="width: 100%" />
            </el-form-item>
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束时间" value-format="YYYY-MM-DD"
                style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="申请原因" prop="applicationReason">
          <el-input type="textarea" :rows="5" v-model="form.applicationReason" placeholder="请输入申请原因" maxlength="500"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="submitCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog :title="processTitle" v-model="processOpen" width="700px" append-to-body>
      <el-form ref="ratioApplicationProcessRef" :model="processForm" :rules="processRules" label-width="100px">
        <el-form-item label="审批结果" prop="approvalResult">
          <el-radio-group v-model="processForm.approvalResult">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见" prop="approvalOpinion">
          <el-input type="textarea" :rows="5" v-model="processForm.approvalOpinion" placeholder="审批意见" maxlength="500"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitProcessForm">提 交</el-button>
          <el-button @click="submitProcessCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 项目选择弹窗 -->
    <el-dialog v-model="definitionDialogVisible" title="选择申请项目" width="70%">
      <el-form :model="queryDefinitionParams" ref="queryDefinitionRef" :inline="true" label-width="68px"
        @submit.native.prevent>
        <el-form-item label="项目" prop="searchDefinitionKey">
          <el-input v-model="queryDefinitionParams.searchKey" placeholder="项目编号/项目名称/医保编码" clearable
            style="width: 240px" @keyup.enter="handleDefinitionQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleDefinitionQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetDefinitionQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格数据 -->
      <el-table v-loading="definitionLoading" :data="definitionList" highlight-current-row @row-click="handleRowClick"
        style="width: 100%;" ref="definitionTableRef">
        <!-- 单选列 -->
        <el-table-column width="60" align="center">
          <template #default="scope">
            <el-radio v-model="selectedDefinitionId" :label="scope.row.id"
              @change="handleRadioChange(scope.row)">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="项目编号" prop="busNo" :show-overflow-tooltip="true" />
        <el-table-column label="项目名称" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="医保编码" prop="ybNo" :show-overflow-tooltip="true" />
        <el-table-column label="医保等级" prop="chrgitmLvName" :show-overflow-tooltip="true" />
        <el-table-column label="生产厂家" prop="manufacturerText" :show-overflow-tooltip="true" />
        <el-table-column label="规格" prop="totalVolume" :show-overflow-tooltip="true" />
      </el-table>
      <pagination v-show="definitionTotal > 0" :total="definitionTotal" v-model:page="queryDefinitionParams.pageNo"
        v-model:limit="queryDefinitionParams.pageSize" @pagination="getDefinitionList" style="margin: 20px 0;" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDefinitionForm">确 定</el-button>
          <el-button @click="definitionDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" :title="`比例调整申请详情 - ${detailData.applicationNo}`" width="1000px"
      :close-on-click-modal="false" :destroy-on-close="true" class="approval-detail-dialog">
      <!-- 基本信息区域 -->
      <div class="basic-info-section">
        <div class="container-wrapper">
          <div class="section-header">
            <i class="el-icon-document"></i>
            <span>申请基本信息</span>
          </div>
          <div class="info-cards">
            <el-row :gutter="8">
              <el-col :span="12" v-for="(item, index) in basicInfoItems" :key="index">
                <el-card shadow="never" class="compact-card">
                  <div class="horizontal-layout">
                    <div class="label-column">{{ item.label }}</div>
                    <div class="value-column">{{ item.value }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <el-card shadow="never" class="compact-card reason-card adaptive-card">
              <div class="horizontal-layout">
                <div class="label-column">申请原因</div>
                <div class="value-column adaptive-content">
                  {{ detailData.applicationReason || '-' }}
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- 审批流程区域 -->
      <div class="approval-flow-section">
        <div class="section-header">
          <i class="el-icon-s-operation"></i>
          <span>审批流程状态</span>
        </div>

        <div class="status-summary">
          <div class="status-badge">
            <el-tag :type="getOverallStatusType(detailData.applicationStatus)" size="large" class="status-tag">
              {{ getApplicationStatusName(detailData.applicationStatus) }}
            </el-tag>
            <span class="status-desc">{{ getStatusDescription(detailData) }}</span>
          </div>
        </div>

        <!-- 水平流程步骤 -->
        <div class="horizontal-flow">
          <div class="flow-container">
            <div v-for="(step, index) in approvalSteps" :key="index" class="flow-step" :class="step.status">
              <div class="step-header">
                <div class="step-title">{{ step.title }}</div>
              </div>

              <div class="step-content">
                <div v-if="step.approver" class="step-info-item">
                  <i class="el-icon-user"></i>
                  <span>{{ step.approver || '待分配' }}</span>
                </div>
                <div v-if="step.time" class="step-info-item">
                  <i class="el-icon-time"></i>
                  <span>{{ step.time || '待处理' }}</span>
                </div>
                <div v-if="step.opinion" class="step-info-item full-width">
                  <i class="el-icon-chat-line-round"></i>
                  <span class="opinion-text">{{ step.opinion || '无' }}</span>
                </div>
              </div>

              <div class="step-result">
                <el-tag :type="getResultTagType(step.result)" effect="dark" size="small" class="result-tag">
                  {{ step.resultText }}
                </el-tag>
              </div>
            </div>

            <!-- 连接线 -->
            <div class="flow-connectors">
              <div v-for="n in 3" :key="n" class="connector" :class="getConnectorClass(n)"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="dialog-footer-1">
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup name="GfStudentList">
import {
  getPage,
  getDetail,
  add,
  cancel,
  process,
  getDefinitionSelectPage,
  getPrintList
} from "@/api/gf/ratioApplicationRecord.js";
import { computed, ref } from 'vue'

const { proxy } = getCurrentInstance();
const {
  application_status,
} = proxy.useDict(
  "application_status",
);

const ratioApplicationRecordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const definitionList = ref([]);
const definitionDialogVisible = ref(false)
const definitionLoading = ref(true);
const definitionTotal = ref(0);
const definitionDateRange = ref([]);
const selectedDefinitionId = ref(undefined)
const selectedDefinition = ref(undefined)
const definitionTableRef = ref();
const processTitle = ref("");
const processOpen = ref(false);
// 选中的行数据
const selectedRows = ref([])

// 对话框显示状态
const dialogVisible = ref(false)
// 详情数据
const detailData = ref({})

const data = reactive({
  form: {},
  processForm: {
    id: undefined,
    approvalRole: undefined,
    approvalResult: 1,
    approvalOpinion: undefined,
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    searchKey: undefined,
    itemType: undefined,
    applicationStatus: undefined,
    printable: '0',
  },
  queryDefinitionParams: {
    pageNo: 1,
    pageSize: 10,
    searchKey: undefined,
    itemType: undefined,
  },
  rules: {
    itemType: [
      { required: true, message: "项目分类不能为空", trigger: ["blur", "change"] }
    ],
    definitionId: [
      { required: true, message: "申请项目不能为空", trigger: ["blur", "change"] }
    ],
    applicationRatio: [
      { required: true, message: "自付比例不能为空", trigger: ["blur", "change"] },
      { pattern: /^(100(\.0{1,2})?$|^[1-9]?\d(\.\d{1,2})?)$/, message: '请输入0-100之间的数字，最多保留两位小数', trigger: 'blur' }
    ],
    twiceRatio: [
      { pattern: /^(100(\.0{1,2})?$|^[1-9]?\d(\.\d{1,2})?)$/, message: '请输入0-100之间的数字，最多保留两位小数', trigger: 'blur' }
    ],
    startDate: [
      { required: true, message: "开始时间不能为空", trigger: ["blur", "change"] }
    ],
    endDate: [
      { required: true, message: "结束时间不能为空", trigger: ["blur", "change"] }
    ],
    applicationReason: [
      { required: true, message: "申请原因不能为空", trigger: "change" }
    ],
  },
  processRules: {
    approvalResult: [
      { required: true, message: "审批结果不能为空", trigger: ["blur", "change"] }
    ],
    approvalOpinion: [
      { required: true, message: "审批意见不能为空", trigger: ["blur", "change"] }
    ],
  },
});

const { queryParams, form, processForm, rules, processRules, queryDefinitionParams } = toRefs(data);

/** 查询分页 */
function getList() {
  loading.value = true;
  getPage(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    ratioApplicationRecordList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    itemType: undefined,
    applicationRatio: undefined,
    twiceRatio: undefined,
    startDate: undefined,
    endDate: undefined,
    applicationReason: undefined,
    definitionId: undefined,
    definitionName: undefined,
  };
  proxy.resetForm("ratioApplicationRecordRef");
}
/** 发起申请 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "发起申请";
}


/** 打印申请单 */
function handlePrint() {
  for (const row of selectedRows.value) {
    if (row.applicationStatus != 0 && row.finalApprovalResult != 0) {
      proxy.$modal.msgWarning("只有等待上会决议的申请才可打印，已为您自动勾选筛选条件");
      queryParams.value.printable = '1'
      getList()
      return
    }
  }
  let itemTypeNow = ''
  let idArray = []
  for (const row of selectedRows.value) {
    if (itemTypeNow && itemTypeNow != row.itemType) {
      proxy.$modal.msgWarning("只能批量选择药品或诊疗项目，不可同时选择药品和诊疗项目");
      return
    }
    itemTypeNow = row.itemType
    idArray.push(row.id)
  }
  getPrintList(idArray).then(response => {
    console.log(response.data)
    //TODO:郭睿打印申请单组件调用
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ratioApplicationRecordRef"].validate(valid => {
    if (valid) {
      add(form.value).then(response => {
        proxy.$modal.msgSuccess("创建成功");
        open.value = false;
        getList();
      });
    }
  });
}
/** 取消按钮 */
function submitCancel() {
  open.value = false;
  reset();
}


/** 提交按钮 */
function submitProcessForm() {
  proxy.$refs["ratioApplicationProcessRef"].validate(valid => {
    if (valid) {
      process(processForm.value).then(response => {
        proxy.$modal.msgSuccess("提交成功");
        processOpen.value = false
        processTitle.value = ""
        getList();
      });
    }
  });
}
/** 取消按钮 */
function submitProcessCancel() {
  processOpen.value = false;
  processForm.value = {
    id: undefined,
    approvalRole: undefined,
    approvalResult: 1,
    approvalOpinion: undefined,
  };
  proxy.resetForm("ratioApplicationProcessRef");
}


// 打开对话框方法
const processApply = (id, role) => {
  console.log(id)
  console.log(role)
  if (role == 1) {
    processTitle.value = "盈亏测算"
  } else if (role == 2) {
    processTitle.value = "财务报批"
  } else if (role == 3) {
    processTitle.value = "上会决议"
  }
  processForm.value = {
    id: id,
    approvalRole: role,
    approvalResult: 1,
    approvalOpinion: undefined,
  };
  processOpen.value = true;
}

/** 处理申请项目选择框 */
function handleShowDefinitionDialog() {
  // 确保有项目分类后再打开弹窗
  if (!form.value.itemType) {
    proxy.$modal.msgWarning("请先选择项目分类");
    return;
  }
  definitionDialogVisible.value = true;
  // 重置弹窗内的选中状态
  selectedDefinitionId.value = undefined;
  selectedDefinition.value = undefined;
  // 重置查询条件并获取列表
  queryDefinitionParams.value.pageNo = 1;
  queryDefinitionParams.value.searchKey = '';
  getDefinitionList(); // 此函数内部已包含回显逻辑
}

// 行点击事件
const handleRowClick = (row) => {
  selectedDefinitionId.value = row.id
  selectedDefinition.value = row
}

// 单选按钮变化事件
const handleRadioChange = (row) => {
  selectedDefinition.value = row
}

//提交单选表单
const submitDefinitionForm = () => {
  if (!selectedDefinition.value) {
    proxy.$modal.msgWarning("请选择一个项目");
    return
  }
  if (selectedDefinition.value.chrgitmLv == 3) {
    proxy.$modal.msgWarning("不能选择医保自费项目");
    return
  }
  // 将id和name传回表单
  form.value.definitionId = selectedDefinition.value.id
  form.value.definitionName = selectedDefinition.value.name
  definitionDialogVisible.value = false
}

// 监听项目分类变化，切换时清空已选项目
watch(() => form.value.itemType, (newVal, oldVal) => {
  // 确保分类确实发生了变化，并且新值不是undefined或null
  if (newVal !== oldVal && newVal != null) {
    form.value.definitionId = undefined;
    form.value.definitionName = undefined;
    // 同时清空弹窗内可能存在的选中状态
    selectedDefinitionId.value = undefined;
    selectedDefinition.value = null;
  }
});

/** 获取分页项目列表 */
function getDefinitionList() {
  definitionLoading.value = true;
  queryDefinitionParams.value.itemType = form.value.itemType; // 确保传入了当前分类
  getDefinitionSelectPage(proxy.addDateRange(queryDefinitionParams.value, definitionDateRange.value)).then(response => {
    definitionList.value = response.data.records;
    definitionTotal.value = response.data.total;
    definitionLoading.value = false;

    // 重点：在下一个时间片（DOM更新后）执行回显逻辑
    proxy.$nextTick(() => {
      // 如果表单中已有选中的项目ID
      if (form.value.definitionId) {
        // 在当前页数据中查找对应的行
        const selectedRow = definitionList.value.find(item => item.id === form.value.definitionId);
        if (selectedRow) {
          // 找到后，更新弹窗内的选中状态
          selectedDefinitionId.value = selectedRow.id;
          selectedDefinition.value = selectedRow;
        }
      }
    });
  }).catch(error => {
    definitionLoading.value = false;
    proxy.$modal.msgError("加载项目列表失败");
  });
}
/** 搜索按钮操作 */
function handleDefinitionQuery() {
  queryDefinitionParams.value.pageNo = 1;
  getDefinitionList();
}
/** 重置按钮操作 */
function resetDefinitionQuery() {
  definitionDateRange.value = [];
  proxy.resetForm("queryDefinitionRef");
  handleDefinitionQuery();
}

// 确保这些方法在setup中正确定义
function getApplicationStatusType(status) {
  const typeMap = {
    '0': 'primary',
    '1': 'success',
    '2': 'danger',
    '3': 'info'
  }
  return typeMap[status]
}

function getApplicationStatusColor(status) {
  const colorMap = {
    '0': '#E6F7FF',
    '1': '#F3FEF0',
    '2': '#FBF2F2',
    '3': '#8F9293'
  }
  return colorMap[status]
}

function getApplicationStatusTextColor(status) {
  const colorMap = {
    '3': '#FFF'
  }
  return colorMap[status]
}

function getApplicationStatusName(status) {
  const colorMap = {
    '0': '处理中',
    '1': '已通过',
    '2': '已驳回',
    '3': '已取消'
  }
  return colorMap[status]
}

// 获取审批进度数组
const getApprovalProcess = (row) => {
  if (row.applicationStatus === 0 && row.initialApprovalResult === 0) {
    return [1, 2, 0, 0]
  }
  if (row.applicationStatus === 3) {
    return [3, 0, 0, 0]
  }
  if (row.applicationStatus === 0 && row.initialApprovalResult === 1 && row.financeApprovalResult === 0) {
    return [1, 1, 2, 0]
  }
  if (row.applicationStatus === 2 && row.initialApprovalResult === 2) {
    return [1, 3, 0, 0]
  }
  if (row.applicationStatus === 0 && row.initialApprovalResult === 1 && row.financeApprovalResult === 1 && row.finalApprovalResult === 0) {
    return [1, 1, 1, 2]
  }
  if (row.applicationStatus === 2 && row.initialApprovalResult === 1 && row.financeApprovalResult === 2) {
    return [1, 1, 3, 0]
  }
  if (row.applicationStatus === 1 && row.initialApprovalResult === 1 && row.financeApprovalResult === 1 && row.finalApprovalResult === 1) {
    return [1, 1, 1, 1]
  }
  if (row.applicationStatus === 2 && row.initialApprovalResult === 1 && row.financeApprovalResult === 1 && row.finalApprovalResult === 2) {
    return [1, 1, 1, 3]
  }
  return [0, 0, 0, 0];
};

// 获取段落的CSS类名
const getSegmentClass = (segment, index) => {
  const baseClass = index === 0 ? 'first-segment' :
    index === 3 ? 'last-segment' : 'middle-segment';

  if (segment === 1) {
    return `${baseClass} completed`; // 已完成 - 绿色
  } else if (segment === 2) {
    return `${baseClass} current`;    // 当前进行中 - 蓝色
  } else if (segment === 3) {
    return `${baseClass} rejected`;   // 驳回/取消 - 红色
  } else {
    return `${baseClass} pending`;    // 未开始 - 灰色
  }
};

// 打开对话框方法
const openDialog = (id) => {
  getDetail(id).then(response => {
    detailData.value = response.data
  })
  dialogVisible.value = true
}

// 打开对话框方法
const closeDialog = () => {
  dialogVisible.value = false
}

// 打开对话框方法
const cancelApply = (id) => {
  cancel(id).then(response => {
    proxy.$modal.msgSuccess("取消成功");
    getList();
  })
}

// 计算审批步骤数据
const approvalSteps = computed(() => {
  const data = detailData.value
  const steps = []

  // 申请提交步骤
  steps.push({
    title: '申请提交',
    approver: data.applicant,
    time: data.applicationTime,
    opinion: data.applicationReason,
    result: 'submitted',
    resultText: '已提交',
    status: 'success',
    icon: 'el-icon-upload'
  })

  // 盈亏测算步骤
  const initialStatus = getStepStatus(data.initialApprovalResult, 1, data.applicationStatus)
  steps.push({
    title: '盈亏测算',
    approver: data.initialApprover,
    time: data.initialApprovalTime,
    opinion: data.initialApprovalOpinion,
    result: data.initialApprovalResult,
    resultText: getResultText(data.initialApprovalResult),
    status: initialStatus,
    icon: 'el-icon-calculator'
  })

  // 财务报批步骤
  const financeStatus = getStepStatus(data.financeApprovalResult, 2, data.applicationStatus, data.initialApprovalResult)
  steps.push({
    title: '财务报批',
    approver: data.financeApprover,
    time: data.financeApprovalTime,
    opinion: data.financeApprovalOpinion,
    result: data.financeApprovalResult,
    resultText: getResultText(data.financeApprovalResult),
    status: financeStatus,
    icon: 'el-icon-money'
  })

  // 上会决议步骤
  const finalStatus = getStepStatus(data.finalApprovalResult, 3, data.applicationStatus, data.financeApprovalResult)
  steps.push({
    title: '上会决议',
    approver: data.finalRecorder,
    time: data.finalRecordTime,
    opinion: data.finalApprovalOpinion,
    result: data.finalApprovalResult,
    resultText: getResultText(data.finalApprovalResult),
    status: finalStatus,
    icon: 'el-icon-s-check'
  })

  return steps
})

// 计算当前激活的步骤索引
const currentStepIndex = computed(() => {
  const data = detailData.value
  if (data.applicationStatus === 3) return -1 // 已取消
  if (data.finalApprovalResult === 1) return 3 // 会议通过
  if (data.finalApprovalResult === 0) return 3 // 会议处理中
  if (data.financeApprovalResult === 1) return 2 // 财务通过，进入会议
  if (data.financeApprovalResult === 0) return 2 // 财务处理中
  if (data.initialApprovalResult === 1) return 1 // 测算通过，进入财务
  if (data.initialApprovalResult === 0) return 1 // 测算处理中
  return 0 // 刚提交
})

// 获取步骤状态
const getStepStatus = (result, stepIndex, appStatus, prevResult) => {
  if (appStatus === 3) return 'warning' // 已取消

  // 如果前面的步骤未通过，当前步骤为未开始
  if (stepIndex > 1 && prevResult !== 1) return 'wait'

  if (result === 1) return 'success'
  if (result === 2) return 'error'
  if (result === 0) return stepIndex === currentStepIndex.value ? 'process' : 'wait'
  return 'wait'
}

// 获取结果文本
const getResultText = (result) => {
  const map = { 0: '处理中', 1: '通过', 2: '驳回', 3: '取消' }
  return map[result] || '未开始'
}

// 获取结果标签类型
const getResultTagType = (result) => {
  const map = { 0: 'info', 1: 'success', 2: 'danger', 3: 'warning' }
  return map[result] || 'info'
}

// 获取整体状态类型
const getOverallStatusType = (status) => {
  const map = { 0: 'primary', 1: 'success', 2: 'danger', 3: 'warning' }
  return map[status] || 'info'
}

// 获取状态描述
const getStatusDescription = (data) => {
  if (data.applicationStatus === 0) {
    if (data.initialApprovalResult === 0) return '等待盈亏测算'
    if (data.financeApprovalResult === 0) return '等待财务报批'
    if (data.finalApprovalResult === 0) return '等待上会决议'
  }
  return getApplicationStatusName(data.applicationStatus)
}

// 日期格式化方法
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 在 script 中添加计算属性
const basicInfoItems = computed(() => [
  { label: '项目名称', value: detailData.value.name || '-' },
  { label: '项目编号', value: detailData.value.busNo || '-' },
  { label: '项目分类', value: detailData.value.itemTypeName || '-' },
  { label: '医保等级', value: detailData.value.chrgitmLvName || '-' },
  { label: '自付比例', value: detailData.value.applicationRatio ? `${detailData.value.applicationRatio}%` : '-' },
  { label: '原自付比例', value: detailData.value.oldRatio ? `${detailData.value.oldRatio}%` : '-' },
  { label: '全价', value: detailData.value.totalPrice ? `${detailData.value.totalPrice}元` : '-' },
  { label: '价格差', value: detailData.value.priceDiff ? `${detailData.value.priceDiff}元` : '-' },
  { label: '二次比例', value: detailData.value.twiceRatio ? `${detailData.value.twiceRatio}%` : '-' },
  { label: '原二次比例', value: detailData.value.oldTwiceRatio ? `${detailData.value.oldTwiceRatio}%` : '-' },
  { label: '开始时间', value: formatDate(detailData.value.startDate) },
  { label: '结束时间', value: formatDate(detailData.value.endDate) },
  { label: '申请人', value: detailData.value.applicant || '-' },
  { label: '申请时间', value: formatDateTime(detailData.value.applicationTime) }
]);

// 获取连接线样式
const getConnectorClass = (connectorIndex) => {
  const steps = approvalSteps.value;

  // 连接线索引从1开始，对应步骤0到步骤1、步骤1到步骤2、步骤2到步骤3之间的连接线
  const prevStepIndex = connectorIndex - 1;

  if (prevStepIndex < 0 || prevStepIndex >= steps.length) {
    return 'pending';
  }

  const prevStep = steps[prevStepIndex];
  const currentStep = steps[connectorIndex];

  // 如果前一步骤是成功状态
  if (prevStep.status === 'success') {
    // 如果当前步骤是处理中，连接线显示为进行中状态
    if (currentStep.status === 'process') {
      return 'process';
    }
    // 如果当前步骤是错误状态，连接线显示为错误状态
    else if (currentStep.status === 'error') {
      return 'error';
    }
    // 如果当前步骤是成功，连接线也显示成功
    else if (currentStep.status === 'success') {
      return 'success';
    }
    // 其他情况显示等待状态
    else {
      return 'pending';
    }
  }
  // 如果前一步骤是处理中状态
  else if (prevStep.status === 'process') {
    return 'process';
  }
  // 如果前一步骤是错误状态
  else if (prevStep.status === 'error') {
    return 'error';
  }
  // 默认等待状态
  else {
    return 'pending';
  }
};

// 暴露方法给父组件
defineExpose({
  openDialog
})

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}


getList();
</script>

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

.mb8 {
  margin-bottom: 8px;
}

.progress-bar {
  display: flex;
  height: 24px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.progress-segment {
  flex: 1;
  transition: all 0.3s ease;
  border-right: 2px solid #fff;
}

.progress-segment:hover {
  transform: scale(1.05);
  z-index: 1;
}

.first-segment {
  border-radius: 4px 0 0 4px;
}

.last-segment {
  border-radius: 0 4px 4px 0;
  border-right: none;
}

.completed {
  background: #67c23a;
}

.current {
  background: #409eff;
}

.pending {
  background: #c0c4cc;
}

.rejected {
  background: #f56c6c;
}

.approval-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.approval-detail-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #e8e8e8;
  padding: 15px 20px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-header i {
  margin-right: 8px;
  color: #409eff;
}

.basic-info-section {
  margin-bottom: 20px;
}

.container-wrapper {
  background-color: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  padding: 16px;
}

.info-cards {
  border: none;
  padding: 0;
}

.compact-card {
  margin-bottom: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.el-card__body {
  padding: 0px 20px 0px 20px !important;
}

/* 申请原因卡片自适应 */
.adaptive-card {
  height: auto;
}

.horizontal-layout {
  display: flex;
  align-items: stretch;
  min-height: inherit;
}

.label-column {
  flex: 0 0 100px;
  font-weight: 600;
  color: #333;
  padding: 12px;
  border-right: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  font-size: 13px;
}

.value-column {
  flex: 1;
  padding: 12px;
  display: flex;
  align-items: center;
  word-break: break-word;
  min-height: 20px;
  line-height: 1.4;
  font-size: 13px;
  color: #666;
}

.adaptive-content {
  max-height: 400px;
  overflow-y: auto;
  align-items: flex-start;
}

.approval-flow-section {
  padding: 20px;
  background: #fafbfc;
  border-radius: 8px;
  border: 1px solid #eaeef2;
}

.status-summary {
  margin-bottom: 25px;
  padding: 15px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.status-badge {
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-tag {
  font-size: 14px;
  padding: 6px 12px;
}

.status-desc {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.horizontal-flow {
  overflow-x: auto;
  padding: 10px 0;
}

.flow-container {
  display: flex;
  min-width: 800px;
  position: relative;
  padding: 0 20px;
}

.flow-step {
  flex: 1;
  position: relative;
  z-index: 2;
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin: 0 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid #eaeef2;
}

.flow-step:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.flow-step.success {
  border-top: 3px solid #67c23a;
}

.flow-step.process {
  border-top: 3px solid #409eff;
  animation: pulse 2s infinite;
}

.flow-step.wait {
  border-top: 3px solid #c0c4cc;
}

.flow-step.error {
  border-top: 3px solid #f56c6c;
}

.step-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.step-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.step-content {
  flex: 1;
  /* 占据剩余空间 */
  margin-bottom: 10px;
  min-height: 100px;
  /* 内容区域最小高度 */
}

/* 确保步骤内容不会与底部结果重叠 */
.step-content:has(+ .step-result) {
  padding-bottom: 40px;
}

.step-info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
  color: #606266;
}

.step-info-item i {
  margin-right: 6px;
  width: 16px;
  text-align: center;
}

.step-info-item.full-width {
  align-items: flex-start;
  min-height: 40px;
  max-height: 80px;
  /* 根据需求调整最大高度 */
  overflow-y: auto;
  overflow-x: hidden;
  padding: 6px 8px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  margin-top: 4px;
}

.step-info-item.full-width .opinion-text {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.4;
  width: 100%;
}

/* 自定义滚动条样式 */
.step-info-item.full-width::-webkit-scrollbar {
  width: 4px;
}

.step-info-item.full-width::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.step-info-item.full-width::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.step-info-item.full-width::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.opinion-text {
  line-height: 1.4;
  word-break: break-word;
}

.step-result {
  position: absolute;
  bottom: 15px;
  left: 50%;
  transform: translateX(-50%);
  width: calc(100% - 30px);
  /* 减去左右padding */
  text-align: center;
  padding: 8px 0;
  background-color: white;
  z-index: 2;
}

.result-tag {
  font-weight: 500;
}

.flow-connectors {
  position: absolute;
  top: 40px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 0 80px;
  z-index: 1;
}

.connector {
  height: 2px;
  flex: 1;
  margin: 0 10px;
  position: relative;
}

.connector::before {
  content: '';
  position: absolute;
  top: -3px;
  right: -4px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #c0c4cc;
}

.connector.success {
  background: linear-gradient(to right, #67c23a, #67c23a);
}

.connector.success::before {
  background: #67c23a;
}

.connector.process {
  background: linear-gradient(to right, #67c23a, #409eff);
}

.connector.process::before {
  background: #409eff;
}

.connector.pending {
  background: #f0f0f0;
}

.connector.pending::before {
  background: #c0c4cc;
}

.connector.error {
  background: linear-gradient(to right, #67c23a, #f56c6c);
}

.connector.error::before {
  background: #f56c6c;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
  }

  70% {
    box-shadow: 0 0 0 6px rgba(64, 158, 255, 0);
  }

  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

.dialog-footer-1 {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 20px 10px 0;
  margin-top: 20px;
}

.dialog-footer-1 .el-button {
  min-width: 100px;
  height: 36px;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .approval-detail-dialog {
    width: 95% !important;
  }

  .flow-container {
    flex-direction: column;
    min-width: auto;
  }

  .flow-step {
    display: flex;
    flex-direction: column;
    min-height: 180px;
    /* 确保有足够的最小高度 */
    position: relative;
    padding-bottom: 50px;
    /* 为底部结果区域留出空间 */
  }

  .flow-connectors {
    display: none;
  }

  .status-badge {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .adaptive-content {
    max-height: 300px;
  }

  .label-column {
    flex: 0 0 80px;
  }
}
</style>