<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" class="search-form">
        <el-form-item label="合同" prop="contractId">
          <el-select
            v-model="queryParams.contractId"
            placeholder="请选择合同"
            clearable
            filterable
            style="width: 240px"
            class="search-select"
          >
            <el-option
              v-for="contract in contractOptions"
              :key="contract.contractId"
              :label="`${contract.contractNumber} - ${contract.title}`"
              :value="contract.contractId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="周期状态" prop="periodStatus">
          <el-select v-model="queryParams.periodStatus" placeholder="请选择周期状态" clearable class="search-select">
            <el-option label="已创建" value="CREATED">
              <div class="status-option">
                <i class="el-icon-plus status-option-icon created"></i>
                <span class="status-option-text">已创建</span>
                <span class="status-option-dot created">●</span>
              </div>
            </el-option>
            <el-option label="已完成" value="COMPLETED">
              <div class="status-option">
                <i class="el-icon-check status-option-icon completed"></i>
                <span class="status-option-text">已完成</span>
                <span class="status-option-dot completed">●</span>
              </div>
            </el-option>
            <el-option label="已取消" value="CANCELLED">
              <div class="status-option">
                <i class="el-icon-close status-option-icon cancelled"></i>
                <span class="status-option-text">已取消</span>
                <span class="status-option-dot cancelled">●</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery" class="search-btn">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['credit:service-period:add']"
              class="action-btn"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['credit:service-period:edit']"
              class="action-btn"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['credit:service-period:remove']"
              class="action-btn"
            >删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="servicePeriodList" @selection-change="handleSelectionChange" class="service-period-table" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="周期编号" align="center" prop="periodNumber" min-width="120">
        <template #default="scope">
          <div class="period-number">
            <i class="el-icon-document"></i>
            {{ scope.row.periodNumber }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="合同信息" align="center" width="220">
        <template #default="scope">
          <div class="contract-info">
            <div class="contract-number">{{ getContractNumber(scope.row.contractId) }}</div>
            <div class="contract-client">{{ getContractClient(scope.row.contractId) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="服务开始日期" align="center" prop="serviceStartDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.serviceStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务结束日期" align="center" prop="serviceEndDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.serviceEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务天数" align="center" prop="serviceDays" width="80" />
      <el-table-column label="员工数量" align="center" prop="employeeCount" width="80" />
      <!-- 贷款倍数字段已隐藏 -->
      <el-table-column label="总人工成本" align="center" prop="totalLaborCost" width="130">
        <template #default="scope">
          <span class="cost-amount">¥{{ (scope.row.totalLaborCost || 0).toLocaleString() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总放款金额" align="center" prop="totalLoanAmount" width="130">
        <template #default="scope">
          <span class="loan-amount">¥{{ (scope.row.totalLoanAmount || 0).toLocaleString() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="周期状态" align="center" prop="periodStatus" width="120">
        <template #default="scope">
          <el-tag 
            :type="getStatusTagType(scope.row.periodStatus)" 
            :effect="scope.row.periodStatus === 'CREATED' ? 'light' : 'plain'"
            size="small"
            class="status-tag"
          >
            <i :class="getStatusIcon(scope.row.periodStatus)" class="status-icon"></i>
            {{ getStatusText(scope.row.periodStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['credit:service-period:query']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['credit:service-period:edit']">修改</el-button>
          <el-button link type="success" icon="User" @click="handleEmployeeManagement(scope.row)" v-hasPermi="['credit:service-period:assign']">员工管理</el-button>
          <el-button link type="warning" icon="Money" @click="handleCostCalculation(scope.row)" v-hasPermi="['credit:service-period:calculate']">成本计算</el-button>
          <el-button link type="info" icon="CreditCard" @click="handleLoanManagement(scope.row)" v-hasPermi="['credit:service-period-loan:list']">贷款管理</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['credit:service-period:remove']">删除</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"
        class="table-pagination"
      />
    </el-card>

    <!-- 添加或修改服务周期对话框 -->
    <el-dialog :title="title" v-model="open" width="950px" append-to-body class="service-period-dialog">
      <el-tabs v-model="activeTab" type="border-card" class="service-period-tabs">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本信息" name="basic">
          <div class="form-container">
            <!-- 详情模式：只读展示 -->
            <div v-if="isDetailMode">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="周期编号">{{ form.periodNumber || '系统自动生成' }}</el-descriptions-item>
                <el-descriptions-item label="合同信息">
                  <div class="contract-info-detail">
                    <div class="contract-number">{{ getContractNumber(form.contractId) }}</div>
                    <div class="contract-client">{{ getContractClient(form.contractId) }}</div>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="服务开始日期">{{ parseTime(form.serviceStartDate, '{y}-{m}-{d}') }}</el-descriptions-item>
                <el-descriptions-item label="服务结束日期">{{ parseTime(form.serviceEndDate, '{y}-{m}-{d}') }}</el-descriptions-item>
                <el-descriptions-item label="服务天数">{{ form.serviceDays }}天</el-descriptions-item>
                <el-descriptions-item label="员工数量">{{ form.employeeCount || 0 }}人</el-descriptions-item>
                <!-- 贷款倍数字段已隐藏 -->
                <el-descriptions-item label="总人工成本">
                  <span class="cost-amount">¥{{ (form.totalLaborCost || 0).toLocaleString() }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="总放款金额">
                  <span class="loan-amount">¥{{ (form.totalLoanAmount || 0).toLocaleString() }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="周期状态">
                  <el-tag 
                    :type="getStatusTagType(form.periodStatus)" 
                    :effect="form.periodStatus === 'CREATED' ? 'light' : 'plain'"
                    size="small"
                    class="status-tag"
                  >
                    <i :class="getStatusIcon(form.periodStatus)" class="status-icon"></i>
                    {{ getStatusText(form.periodStatus) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="服务内容" :span="2">{{ form.serviceContent || '暂无' }}</el-descriptions-item>
              </el-descriptions>
            </div>
            
            <!-- 编辑模式：可编辑表单 -->
            <div v-else>
              <el-form ref="servicePeriodRef" :model="form" :rules="rules" label-width="120px" class="service-period-form">
                <el-form-item label="合同" prop="contractId">
                  <el-select
                    v-model="form.contractId"
                    placeholder="请选择合同"
                    clearable
                    filterable
                    style="width: 100%"
                    class="contract-select"
                  >
                    <el-option
                      v-for="contract in contractOptions"
                      :key="contract.contractId"
                      :label="`${contract.contractNumber} - ${contract.title}`"
                      :value="contract.contractId"
                    />
                  </el-select>
                </el-form-item>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="服务开始日期" prop="serviceStartDate" >
                      <el-date-picker
                        v-model="form.serviceStartDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择服务开始日期"
                        style="width: 100%"
                        @change="calculateServiceDays"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="服务结束日期" prop="serviceEndDate">
                      <el-date-picker
                        v-model="form.serviceEndDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择服务结束日期"
                        style="width: 100%"
                        @change="calculateServiceDays"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="服务天数" prop="serviceDays">
                      <el-input-number 
                        v-model="form.serviceDays" 
                        :min="1" 
                        placeholder="自动计算" 
                        style="width: 100%" 
                        readonly 
                        :controls="false"
                      />
                      <div class="form-tip">
                        <i class="el-icon-info"></i>
                        根据开始和结束日期自动计算
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <!-- 贷款倍数字段已隐藏 -->
                    <el-form-item label="周期状态" prop="periodStatus">
                      <el-select v-model="form.periodStatus" placeholder="请选择周期状态" style="width: 100%" class="status-select">
                        <el-option label="已创建" value="CREATED">
                          <div class="status-option">
                            <i class="el-icon-plus status-option-icon created"></i>
                            <span class="status-option-text">已创建</span>
                            <span class="status-option-dot created">●</span>
                          </div>
                        </el-option>
                        <el-option label="已完成" value="COMPLETED">
                          <div class="status-option">
                            <i class="el-icon-check status-option-icon completed"></i>
                            <span class="status-option-text">已完成</span>
                            <span class="status-option-dot completed">●</span>
                          </div>
                        </el-option>
                        <el-option label="已取消" value="CANCELLED">
                          <div class="status-option">
                            <i class="el-icon-close status-option-icon cancelled"></i>
                            <span class="status-option-text">已取消</span>
                            <span class="status-option-dot cancelled">●</span>
                          </div>
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="服务内容" prop="serviceContent">
                  <el-input v-model="form.serviceContent" type="textarea" :rows="3" placeholder="请输入服务内容" class="service-content-input" />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 员工管理标签页 - 只在新增时显示 -->
        <el-tab-pane 
          v-if="!form.servicePeriodId || isNewServicePeriodSaved" 
          label="员工管理" 
          name="employees" 
          :disabled="!isNewServicePeriodSaved"
        >
          <div v-if="!isNewServicePeriodSaved" class="employee-tab-placeholder">
            <el-alert
              title="请先保存服务周期基本信息"
              description="需要先创建服务周期后才能添加员工"
              type="info"
              :closable="false"
              show-icon
            />
          </div>
          <div v-else>
            <BatchEmployeeSelector 
              :service-period-id="newServicePeriodId"
              @select-complete="handleEmployeeSelectComplete"
              @cancel="handleEmployeeCancel"
            />
          </div>
        </el-tab-pane>

        <!-- 贷款管理标签页 - 只在新增时显示 -->
        <el-tab-pane 
          v-if="!form.servicePeriodId || isNewServicePeriodSaved" 
          label="贷款管理" 
          name="loans" 
          :disabled="!isNewServicePeriodSaved"
        >
          <div v-if="!isNewServicePeriodSaved" class="loan-tab-placeholder">
            <el-alert
              title="请先保存服务周期基本信息"
              description="需要先创建服务周期后才能管理贷款"
              type="info"
              :closable="false"
              show-icon
            />
          </div>
          <div v-else>
            <LoanManagement 
              :service-period-id="newServicePeriodId"
              @loan-changed="handleLoanChanged"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <template #footer>
        <div class="dialog-footer">
          <!-- 详情模式：只显示关闭按钮 -->
          <template v-if="isDetailMode">
            <el-button @click="cancel">关 闭</el-button>
          </template>
          
          <!-- 编辑模式：显示完整的操作按钮 -->
          <template v-else>
            <el-button v-if="activeTab === 'basic'" type="primary" @click="submitForm">
              {{ form.servicePeriodId ? '确 定' : '保存并继续' }}
            </el-button>
            <el-button v-if="activeTab === 'employees'" type="success" @click="handleCompleteAndClose">
              完成并关闭
            </el-button>
            <el-button v-if="activeTab === 'employees'" @click="handleSkipEmployees">
              跳过员工管理
            </el-button>
            <el-button v-if="activeTab === 'loans'" type="success" @click="handleCompleteAndClose">
              完成并关闭
            </el-button>
            <el-button v-if="activeTab === 'loans'" @click="handleSkipLoans">
              跳过贷款管理
            </el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </template>
    </el-dialog>

    <!-- 员工管理对话框 -->
    <el-dialog title="员工管理" v-model="employeeDialogVisible" width="90%" append-to-body>
      <EmployeeManagement 
        v-if="employeeDialogVisible"
        :service-period-id="currentServicePeriodId"
        @close="employeeDialogVisible = false"
        @employee-changed="handleEmployeeChanged"
      />
    </el-dialog>

    <!-- 成本计算对话框 -->
    <el-dialog title="成本计算" v-model="costDialogVisible" width="70%" append-to-body>
      <CostCalculation 
        v-if="costDialogVisible"
        :service-period-id="currentServicePeriodId"
        @close="costDialogVisible = false"
      />
    </el-dialog>

    <!-- 贷款管理对话框 -->
    <el-dialog title="贷款管理" v-model="loanDialogVisible" width="95%" append-to-body>
      <LoanManagement 
        v-if="loanDialogVisible"
        :service-period-id="currentServicePeriodId"
        @close="loanDialogVisible = false"
        @loan-changed="handleLoanChanged"
      />
    </el-dialog>
  </div>
</template>

<script setup name="ServicePeriod">
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue';
import { listServicePeriod, getServicePeriod, delServicePeriod, addServicePeriod, updateServicePeriod } from "@/api/digitalCredit/servicePeriod";
import { listContracts } from "@/api/credit/contract";
import { parseTime } from "@/utils/ruoyi";
import EmployeeManagement from "./components/EmployeeManagement.vue";
import CostCalculation from "./components/CostCalculation.vue";
import BatchEmployeeSelector from "./components/BatchEmployeeSelector.vue";
import LoanManagement from "./components/LoanManagement.vue";

const { proxy } = getCurrentInstance();
const { period_status } = proxy.useDict('period_status');

const servicePeriodList = ref([]);
const contractOptions = ref([]);
const open = ref(false);
const employeeDialogVisible = ref(false);
const costDialogVisible = ref(false);
const loanDialogVisible = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const currentServicePeriodId = ref(null);
const loanAmountPreview = ref("¥0.00");
const activeTab = ref("basic");
const isNewServicePeriodSaved = ref(false);
const newServicePeriodId = ref(null);
const isDetailMode = ref(false); // 新增：区分详情模式和编辑模式

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractId: null,
    periodStatus: null,
  },
  rules: {
    contractId: [
      { required: true, message: "合同不能为空", trigger: "change" }
    ],
    serviceStartDate: [
      { required: true, message: "服务开始日期不能为空", trigger: "blur" }
    ],
    serviceEndDate: [
      { required: true, message: "服务结束日期不能为空", trigger: "blur" }
    ],
  }
});

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

/** 获取状态标签类型 */
function getStatusTagType(status) {
  const statusTypes = {
    'CREATED': 'success',
    'COMPLETED': 'info', 
    'CANCELLED': 'danger'
  };
  return statusTypes[status] || 'info';
}

/** 获取状态文本 */
function getStatusText(status) {
  const statusTexts = {
    'CREATED': '已创建',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusTexts[status] || status;
}

/** 获取状态图标 */
function getStatusIcon(status) {
  const statusIcons = {
    'CREATED': 'el-icon-plus',
    'COMPLETED': 'el-icon-check',
    'CANCELLED': 'el-icon-close'
  };
  return statusIcons[status] || 'el-icon-info';
}

/** 获取合同选项 */
function getContractOptions() {
  listContracts({ pageSize: 1000,contractStatus: 'CONFIRMED' }).then(response => {
    contractOptions.value = response.rows || response.data || [];
  }).catch(error => {
    console.error("获取合同列表失败:", error);
    contractOptions.value = [];
  });
}

/** 根据合同ID获取合同编号 */
function getContractNumber(contractId) {
  const contract = contractOptions.value.find(c => c.contractId === contractId);
  return contract ? contract.contractNumber : contractId;
}

/** 根据合同ID获取客户公司 */
function getContractClient(contractId) {
  const contract = contractOptions.value.find(c => c.contractId === contractId);
  return contract ? contract.title : '';
}

/** 计算贷款金额预览 */
function calculateLoanPreview() {
  // 这里可以根据当前的人工成本来计算预览
  // 暂时显示计算逻辑说明
  const multiplier = form.value.loanMultiplier;
  if (!multiplier || multiplier === 0 || multiplier === 1) {
    loanAmountPreview.value = "等于人工成本总和";
  } else {
    loanAmountPreview.value = `人工成本 × ${multiplier}`;
  }
}

/** 计算服务天数 */
function calculateServiceDays() {
  if (form.value.serviceStartDate && form.value.serviceEndDate) {
    const startDate = new Date(form.value.serviceStartDate);
    const endDate = new Date(form.value.serviceEndDate);
    
    if (endDate >= startDate) {
      // 计算天数差（包含开始和结束日期）
      const timeDiff = endDate.getTime() - startDate.getTime();
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
      form.value.serviceDays = daysDiff;
    } else {
      form.value.serviceDays = null;
      proxy.$modal.msgError('结束日期不能早于开始日期');
    }
  } else {
    // 如果日期不完整，清空服务天数
    form.value.serviceDays = null;
  }
}

/** 查询服务周期列表 */
function getList() {
  loading.value = true;
  listServicePeriod(queryParams.value).then(response => {
    servicePeriodList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    servicePeriodId: null,
    contractId: null,
    serviceStartDate: null,
    serviceEndDate: null,
    serviceDays: null,
    serviceContent: null,
    // 贷款倍数字段已隐藏，但保留在数据中以兼容后端
    loanMultiplier: null,
    periodStatus: "CREATED"
  };
  loanAmountPreview.value = "¥0.00";
  activeTab.value = "basic";
  isNewServicePeriodSaved.value = false;
  newServicePeriodId.value = null;
  isDetailMode.value = false; // 重置模式
  proxy.resetForm("servicePeriodRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.servicePeriodId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isDetailMode.value = false; // 设置为编辑模式
  open.value = true;
  title.value = "添加服务周期";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isDetailMode.value = false; // 设置为编辑模式
  const _servicePeriodId = row.servicePeriodId || ids.value;
  getServicePeriod(_servicePeriodId).then(response => {
    form.value = response.data;
    calculateLoanPreview(); // 计算预览
    open.value = true;
    title.value = "修改服务周期";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["servicePeriodRef"].validate(valid => {
    if (valid) {
      // 验证日期逻辑
      if (form.value.serviceStartDate && form.value.serviceEndDate) {
        const startDate = new Date(form.value.serviceStartDate);
        const endDate = new Date(form.value.serviceEndDate);
        
        if (endDate < startDate) {
          proxy.$modal.msgError('服务结束日期不能早于开始日期');
          return;
        }
        
        // 确保服务天数是最新计算的
        calculateServiceDays();
      }
      
      // 确保贷款倍数的处理
      const formData = { ...form.value };
      
      // 如果贷款倍数为空或0，设置为null（表示按人工成本计算）
      if (!formData.loanMultiplier || formData.loanMultiplier === 0) {
        formData.loanMultiplier = null;
      }
      
      console.log('提交的服务周期数据:', formData);
      
      if (formData.servicePeriodId != null) {
        // 修改现有服务周期
        updateServicePeriod(formData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 新增服务周期
        addServicePeriod(formData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          
          // 保存新创建的服务周期ID，用于员工管理
          if (response.data && response.data.servicePeriodId) {
            newServicePeriodId.value = response.data.servicePeriodId;
            form.value.servicePeriodId = response.data.servicePeriodId;
            isNewServicePeriodSaved.value = true;
            
            // 切换到员工管理标签页
            activeTab.value = "employees";
            title.value = "添加员工到服务周期";
            
            // 刷新列表但不关闭对话框
            getList();
          } else {
            // 如果没有返回ID，直接关闭对话框
            open.value = false;
            getList();
          }
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _servicePeriodIds = row.servicePeriodId || ids.value;
  proxy.$modal.confirm('是否确认删除服务周期编号为"' + _servicePeriodIds + '"的数据项？').then(function() {
    return delServicePeriod(_servicePeriodIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 详情按钮操作 */
function handleDetail(row) {
  reset();
  isDetailMode.value = true; // 设置为详情模式
  const servicePeriodId = row.servicePeriodId;
  getServicePeriod(servicePeriodId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "服务周期详情";
    activeTab.value = "basic"; // 默认显示基本信息标签页
  });
}

/** 员工管理按钮操作 */
function handleEmployeeManagement(row) {
  currentServicePeriodId.value = row.servicePeriodId;
  employeeDialogVisible.value = true;
}

/** 处理员工变化事件 */
function handleEmployeeChanged() {
  // 刷新服务周期列表，因为员工数量和总成本可能发生了变化
  getList();
}

/** 成本计算按钮操作 */
function handleCostCalculation(row) {
  currentServicePeriodId.value = row.servicePeriodId;
  costDialogVisible.value = true;
}

/** 贷款管理按钮操作 */
function handleLoanManagement(row) {
  currentServicePeriodId.value = row.servicePeriodId;
  loanDialogVisible.value = true;
}

/** 处理贷款变化事件 */
function handleLoanChanged() {
  // 刷新服务周期列表，因为贷款信息可能发生了变化
  getList();
}

/** 处理员工选择完成 */
function handleEmployeeSelectComplete(eventData) {
  // 根据不同场景显示合适的提示消息
  const { employeeCount, workDays } = eventData || {};
  
  if (activeTab.value === 'employees') {
    // 在新增服务周期的员工管理标签页中
    proxy.$modal.msgSuccess(`成功添加 ${employeeCount} 名员工！您可以继续添加更多员工或进入贷款管理。`);
    // 自动切换到贷款管理标签页
    setTimeout(() => {
      activeTab.value = "loans";
      title.value = "贷款管理";
    }, 1500);
  } else {
    // 在独立的员工管理对话框中
    proxy.$modal.msgSuccess(`员工分配成功！已为 ${employeeCount} 名员工分配 ${workDays} 天工作任务。`);
  }
  
  // 刷新服务周期列表，因为员工数量和总成本可能发生了变化
  getList();
}

/** 处理员工管理取消 */
function handleEmployeeCancel() {
  // 用户在员工管理中点击取消，回到基本信息标签页
  activeTab.value = "basic";
  proxy.$modal.msgInfo("已取消员工选择，您可以继续修改基本信息或重新选择员工。");
}

/** 跳过员工管理 */
function handleSkipEmployees() {
  proxy.$modal.confirm('确定要跳过员工管理吗？您可以稍后通过"员工管理"按钮添加员工。', '跳过确认', {
    confirmButtonText: '确定跳过',
    cancelButtonText: '继续添加员工',
    type: 'warning'
  }).then(() => {
    // 跳转到贷款管理标签页
    activeTab.value = "loans";
    title.value = "贷款管理";
  }).catch(() => {
    // 用户选择继续添加员工，不做任何操作
  });
}

/** 跳过贷款管理 */
function handleSkipLoans() {
  proxy.$modal.confirm('确定要跳过贷款管理吗？您可以稍后通过"贷款管理"按钮管理贷款。', '跳过确认', {
    confirmButtonText: '确定跳过',
    cancelButtonText: '继续管理贷款',
    type: 'warning'
  }).then(() => {
    proxy.$modal.msgSuccess("服务周期创建完成！");
    open.value = false;
    getList();
  }).catch(() => {
    // 用户选择继续管理贷款，不做任何操作
  });
}

/** 完成并关闭对话框 */
function handleCompleteAndClose() {
  proxy.$modal.msgSuccess("服务周期创建完成！");
  open.value = false;
  getList();
}

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

<style scoped>
.contract-info {
  text-align: left;
  padding: 12px 8px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 6px;
  margin: 4px 0;
  border-left: 3px solid #409eff;
}

.contract-number {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  margin-bottom: 6px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.contract-number::before {
  content: "📋";
  font-size: 12px;
}

.contract-client {
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
  padding-left: 18px;
  font-style: italic;
}

.cost-amount {
  font-weight: 600;
  color: #E6A23C;
}

.dialog-footer {
  text-align: right;
}

.mb8 {
  margin-bottom: 8px;
}

.app-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

/* 卡片动画效果 */
.search-card,
.table-card {
  transition: all 0.3s ease;
}

.search-card:hover,
.table-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: white;
}

.search-card :deep(.el-card__body) {
  padding: 25px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.search-select :deep(.el-input__inner) {
  border-radius: 6px;
}

.search-btn {
  border-radius: 6px;
  padding: 10px 20px;
}

.reset-btn {
  border-radius: 6px;
  padding: 10px 20px;
  margin-left: 10px;
}

/* 状态标签样式优化 */
.status-tag {
  font-weight: 500;
  border-radius: 12px;
  padding: 4px 12px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.status-icon {
  font-size: 12px;
}

/* 状态选项样式 */
.status-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 4px 0;
}

.status-option-icon {
  font-size: 14px;
  margin-right: 8px;
}

.status-option-text {
  flex: 1;
}

.status-option-dot {
  font-size: 16px;
  margin-left: 8px;
}

/* 状态颜色 */
.status-option-icon.created,
.status-option-dot.created {
  color: #67c23a;
}

.status-option-icon.completed,
.status-option-dot.completed {
  color: #909399;
}

.status-option-icon.cancelled,
.status-option-dot.cancelled {
  color: #f56c6c;
}

/* 表格卡片样式 */
.table-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: none;
  background: white;
}

.table-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
  padding: 18px 25px;
  border-bottom: none;
}

.table-card :deep(.el-card__body) {
  padding: 0;
  border-radius: 0 0 12px 12px;
}

/* 操作按钮样式优化 */
.action-btn {
  border-radius: 6px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
/* 周期编号样式 */
.period-number {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-weight: 600;
  color: #409eff;
}

.period-number i {
  font-size: 14px;
}

/* 服务周期表格样式 */
.service-period-table {
  border-radius: 8px;
  overflow: hidden;
}

.service-period-table :deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

.service-period-table :deep(.el-table__body-wrapper) {
  border-radius: 0 0 8px 8px;
}

/* 表格行悬停效果 */
:deep(.el-table tbody tr:hover > td) {
  background-color: #f5f7fa !important;
}

/* 表格头部样式 */
:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

/* 操作按钮组样式优化 */
:deep(.el-table .cell .el-button) {
  margin: 0 2px;
  padding: 5px 8px;
  font-size: 12px;
}

/* 金额显示样式 */
.cost-amount {
  font-weight: 700;
  color: #E6A23C;
  font-family: 'Courier New', monospace;
  background: linear-gradient(135deg, #fff7e6 0%, #fef2d6 100%);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #f0d0a0;
  display: inline-block;
}

.loan-amount {
  font-weight: 700;
  color: #67C23A;
  font-family: 'Courier New', monospace;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #a0d0f0;
  display: inline-block;
}

/* 表单布局优化 */
.el-form-item {
  margin-bottom: 18px;
}

/* 表单提示信息样式 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 6px;
  line-height: 1.4;
  padding: 4px 8px;
  background-color: #f4f4f5;
  border-radius: 4px;
  border-left: 3px solid #e6a23c;
  display: flex;
  align-items: center;
  gap: 4px;
}

.form-tip i {
  color: #409eff;
}

/* 搜索表单样式 */
.el-form--inline .el-form-item {
  margin-right: 15px;
}

/* 员工标签页占位符样式 */
.employee-tab-placeholder {
  padding: 40px 20px;
  text-align: center;
}

/* 贷款标签页占位符样式 */
.loan-tab-placeholder {
  padding: 40px 20px;
  text-align: center;
}

/* 对话框样式优化 */
.service-period-dialog :deep(.el-dialog__body) {
  padding: 10px 20px 20px;
}

.service-period-tabs :deep(.el-tabs__content) {
  padding: 25px;
  background-color: #fafafa;
  border-radius: 0 0 4px 4px;
}

.form-container {
  background: white;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.service-period-form .el-form-item {
  margin-bottom: 22px;
}

.contract-select :deep(.el-input__inner) {
  border-radius: 6px;
}

.status-select :deep(.el-input__inner) {
  border-radius: 6px;
}

.service-content-input :deep(.el-textarea__inner) {
  border-radius: 6px;
  resize: vertical;
}

/* 标签页样式优化 */
:deep(.el-tabs--border-card) {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-tabs--border-card .el-tabs__header) {
  background-color: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

:deep(.el-tabs--border-card .el-tabs__item) {
  border-radius: 6px 6px 0 0;
  margin: 0 2px;
  transition: all 0.3s ease;
}

/* 详情页面样式 */
.contract-info-detail {
  text-align: left;
}

.contract-info-detail .contract-number {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  margin-bottom: 4px;
}

.contract-info-detail .contract-client {
  color: #606266;
  font-size: 12px;
  font-style: italic;
}

/* 描述列表样式优化 */
:deep(.el-descriptions) {
  margin-top: 20px;
}

:deep(.el-descriptions__header) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-descriptions__body) {
  background-color: #fafafa;
}

:deep(.el-descriptions__table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-descriptions-item__label) {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #606266;
  width: 120px;
}

:deep(.el-descriptions-item__content) {
  background-color: white;
  color: #303133;
}

/* 状态标签在详情页面的样式 */
.status-tag {
  font-weight: 500;
  border-radius: 12px;
  padding: 4px 12px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.status-icon {
  font-size: 12px;
}

/* 金额显示样式在详情页面 */
.cost-amount {
  font-weight: 700;
  color: #E6A23C;
  font-family: 'Courier New', monospace;
  background: linear-gradient(135deg, #fff7e6 0%, #fef2d6 100%);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #f0d0a0;
  display: inline-block;
}

.loan-amount {
  font-weight: 700;
  color: #67C23A;
  font-family: 'Courier New', monospace;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #a0d0f0;
  display: inline-block;
}

:deep(.el-tabs--border-card .el-tabs__item.is-active) {
  background-color: white;
  border-bottom-color: white;
  font-weight: 600;
}
</style>