<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form :model="queryParams" ref="queryRef" inline label-width="80px">
        <el-form-item label="客户名称" prop="customerName" class="custom-form-item">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="编号" prop="receiptId" class="custom-form-item">
          <el-input v-model="queryParams.receiptId" placeholder="请输入编号" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson" class="custom-form-item">
          <el-select v-model="queryParams.contactPerson" placeholder="请选择" clearable filterable remote :remote-method="remoteLoadAllContacts" :loading="contactSearchLoading" @focus="remoteLoadAllContacts('')" style="width: 180px">
            <el-option v-for="item in filterContactOptions" :key="item.value" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="0" class="btns-item">
          <div class="search-btns-group">
            <el-button icon="Search" @click="handleQuery" class="btn-search">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery" class="btn-reset">重置</el-button>
            <el-button type="primary" icon="Plus" @click="handleAdd" class="btn-plus">新增</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="card-header">
          <span class="page-title">客户关怀信息列表</span>
          <div class="tabs-group">
            <span :class="['tab-btn', activeTab === 'mine' ? 'active' : '']" @click="switchTab('mine')">我负责的关怀</span>
            <span :class="['tab-btn', activeTab === 'all' ? 'active' : '']" @click="switchTab('all')">全部客户关怀</span>
          </div>
        </div>
      </template>
      <el-table ref="tableRef" v-loading="loading" :data="dataList" border class="custom-table" :header-cell-style="{ background: '#f8fafc', color: '#333', fontWeight: '400' }">
        <el-table-column label="单据编号" align="center" prop="receiptId" width="150">
          <template #default="scope">
            <span class="detail-link" @click="handleDetail(scope.row)">{{ scope.row.receiptId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="登记日期" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ scope.row.createTime ? scope.row.createTime.substring(0, 10) : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户联系人" align="center" prop="contactPerson" width="120" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="250" show-overflow-tooltip />
        <el-table-column label="关怀类型" align="center" prop="concernType" width="120">
          <template #default="scope">
            <span>{{ careTypeText(scope.row.concernType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="amount" width="100">
          <template #default="scope">
            <span>{{ formatAmount(scope.row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="auditStatus" width="100">
          <template #default="scope">
            <span v-if="statusText(scope.row.auditStatus)" class="status-tag" :class="scope.row.auditStatus == 1 ? 'success' : 'applying'">
              {{ statusText(scope.row.auditStatus) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="180" fixed="right">
          <template #header>
            <span>操作 <el-icon style="vertical-align: middle;"><Setting /></el-icon></span>
          </template>
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" @click="handleAuditDetail(scope.row)">审核明细</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" />
    </el-card>

    <!-- 详情抽屉 -->
    <care-detail ref="detailRef" @success="getList" />
    <!-- 新增抽屉 -->
    <care-add ref="addRef" @success="getList" />

    <!-- 审核明细抽屉 (独立实现) -->
    <el-drawer
      v-model="auditVisible"
      title="查看审核明细"
      direction="rtl"
      size="500px"
      destroy-on-close
      class="audit-drawer"
    >
      <div class="audit-timeline-container">
        <div class="audit-timeline">
          <!-- 1. 提交申请节点 (始终显示) -->
          <div class="timeline-node">
            <div class="node-icon success">
              <el-icon><User /></el-icon>
            </div>
            <div class="node-content">
              <div class="node-header">发起申请</div>
              <div class="audit-card">
                <div class="audit-user-row">
                  <div class="user-avatar">{{ auditForm.createBy ? '管' : '管' }}</div>
                  <div class="user-info">
                    <span class="user-name">{{ auditForm.createByName || '系统管理员' }}</span>
                    <div class="audit-status-tag">
                      <span class="status-text success">已提交</span>
                      <span class="audit-time">{{ auditForm.createTime }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 2. 审核节点 (仅当 auditStatus != 0 时显示) -->
          <div class="timeline-node" v-if="auditForm.auditStatus != 0">
            <div class="node-icon" :class="auditForm.auditStatus == 1 ? 'success' : 'danger'">
              <el-icon><User /></el-icon>
            </div>
            <div class="node-content">
              <div class="node-header">审核结果</div>
              <div class="audit-card">
                <div class="audit-user-row">
                  <div class="user-avatar">{{ getStaffName(auditForm.auditPeople).substring(0, 1) }}</div>
                  <div class="user-info">
                    <span class="user-name">{{ getStaffName(auditForm.auditPeople) }}</span>
                    <div class="audit-status-tag">
                      <span class="status-text" :class="auditForm.auditStatus == 1 ? 'success' : 'danger'">
                        {{ statusText(auditForm.auditStatus) }}
                      </span>
                      <span class="audit-time">{{ auditForm.auditDate }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 3. 待审核节点 (当 auditStatus == 0 时显示) -->
          <div class="timeline-node" v-else>
            <div class="node-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="node-content">
              <div class="node-header no-card">等待审核人审批...</div>
            </div>
          </div>

          <!-- 结束节点 -->
          <div class="timeline-node end-node" v-if="auditForm.auditStatus != 0">
            <div class="node-icon success">
              <el-icon><User /></el-icon>
            </div>
            <div class="node-content">
              <div class="node-header no-card">流程已结束</div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup name="CustomerCare">
import { ref, reactive, onMounted, getCurrentInstance, watch, toRefs } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { Setting, User } from '@element-plus/icons-vue';
import { listCare, delCare, getCare } from "@/api/customer/crmCare";
import { listContact } from "@/api/customer/crmContact";
import { listComStaff } from "@/api/system/comStaff/index";
import CareDetail from './detail.vue';
import CareAdd from './add.vue';

const proxy = getCurrentInstance().proxy;
const { care_type: careTypeOptions } = toRefs(reactive(proxy.useDict("care_type")));
const router = useRouter();
const route = useRoute();

const loading = ref(false);
const contactSearchLoading = ref(false);
const total = ref(0);
const dataList = ref([]);
const filterContactOptions = ref([]);
const activeTab = ref('mine');
const detailRef = ref(null);
const addRef = ref(null);
const auditVisible = ref(false);
const auditForm = ref({});
const staffOptions = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  customerName: undefined,
  receiptId: undefined,
  contactPerson: undefined,
  concernType: undefined,
  auditStatus: undefined,
  scope: 'mine'
});

const careTypeText = (val) => {
  const obj = careTypeOptions.value.find(item => String(item.value) === String(val));
  return obj ? obj.label : val;
};

const statusText = (status) => {
  const map = { 0: '申请中', 1: '已通过' };
  return map[status] || '';
};

const formatAmount = (val) => {
  if (val === null || val === undefined || val === '') return '0.00';
  return Number(val).toFixed(2);
};

const switchTab = (tab) => {
  activeTab.value = tab;
  queryParams.scope = tab;
  handleQuery();
};

const getList = () => {
  loading.value = true;
  listCare(queryParams).then(response => {
    dataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

/** 远程搜索所有联系人（查询栏使用） */
const remoteLoadAllContacts = (query) => {
  contactSearchLoading.value = true;
  listContact({ contactName: query || undefined, pageSize: 20 }).then(res => {
    filterContactOptions.value = (res.rows || []).map(item => ({
      label: item.contactName,
      value: item.id
    }));
    contactSearchLoading.value = false;
  }).catch(() => {
    contactSearchLoading.value = false;
  });
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.scope = activeTab.value;
  handleQuery();
};

const handleAdd = () => {
  addRef.value.open();
};

const handleDetail = (row) => {
  detailRef.value.open(row.id);
};

const handleAuditDetail = (row) => {
  loading.value = true;
  getCare(row.id).then(res => {
    auditForm.value = res.data;
    auditVisible.value = true;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

/** 转换员工姓名 */
const getStaffName = (staffId) => {
  if (!staffId) return '未指定';
  const staff = staffOptions.value.find(item => item.staffId == staffId || item.id == staffId);
  return staff ? (staff.staffName || staff.userName) : '审核人(' + staffId + ')';
};

/** 加载员工列表 */
const loadStaffOptions = () => {
  listComStaff({ pageSize: 1000 }).then(res => {
    staffOptions.value = res.rows || res.data || [];
  });
};



// 监听路由变化，关闭弹窗后刷新列表
watch(() => route.path, (newPath) => {
  if (newPath === '/customer/care') {
    getList();
  }
});

onMounted(() => {
  getList();
  loadStaffOptions();
  remoteLoadAllContacts('');
});
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-card {
  background-color: #fff;
  margin-bottom: 15px;
  :deep(.el-card__body) { padding: 20px; }
}

.card-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.custom-form-item, .btns-item {
  margin-bottom: 12px !important;
  margin-right: 20px;
}

.search-btns-group {
  display: flex; gap: 10px; align-items: center;
  .el-button { height: 36px !important; padding: 0 15px; }
  .btn-plus { width: 90px; background-color: #409eff; border-color: #409eff; color: #fff; font-weight: bold; }
}

.page-title { 
  font-size: 14px; 
  font-weight: bold; 
  color: #333; 
  margin-right: 30px;
}

.tabs-group {
  display: flex;
  gap: 12px;
  .tab-btn {
    padding: 5px 16px; 
    font-size: 13px; 
    color: #333; 
    cursor: pointer;
    border: 1px solid #e2e8f0; 
    background: #fff;
    border-radius: 4px;
    transition: all 0.2s;
    &.active { 
      border-color: #409eff; 
      color: #409eff; 
      background-color: #f0f7ff;
    }
    &:hover { 
      color: #409eff; 
      border-color: #c6e2ff;
    }
  }
}

.table-card { 
  margin-bottom: 20px;
  :deep(.el-card__header) {
    padding: 12px 20px;
    border-bottom: 1px solid #f1f5f9;
  }
  :deep(.el-card__body) { padding: 20px; } 
}
.custom-table { :deep(th.el-table__cell) { background-color: #f8fafc !important; } }
.detail-link { color: #333; cursor: pointer; }
.detail-link:hover { color: #409eff; }

.status-tag {
  display: inline-block;
  padding: 2px 12px;
  border-radius: 4px;
  font-size: 12px;
  &.applying {
    background-color: #f0f7ff;
    color: #409eff;
    border: 1px solid #d9ecff;
  }
  &.success {
    background-color: #f0f9eb;
    color: #67c23a;
    border: 1px solid #e1f3d8;
  }
}

/* 审核流程时间轴样式 (还原原型图) */
.audit-drawer {
  :deep(.el-drawer__header) {
    margin-bottom: 20px;
    padding: 20px 24px 0;
    span { font-size: 16px; color: #333; }
  }
}

.audit-timeline-container {
  padding: 10px 24px;
}

.audit-timeline {
  position: relative;
  &::before {
    content: '';
    position: absolute;
    left: 10px;
    top: 10px;
    bottom: 10px;
    width: 1px;
    background: #e2e8f0;
  }
}

.timeline-node {
  position: relative;
  padding-left: 40px;
  margin-bottom: 35px;
  
  .node-icon {
    position: absolute;
    left: 0;
    top: 0;
    width: 22px;
    height: 22px;
    border-radius: 50%;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #e2e8f0;
    z-index: 1;
    .el-icon { font-size: 14px; color: #94a3b8; }
    &.success {
      border-color: #67c23a;
      background-color: #67c23a;
      .el-icon { color: #fff; }
    }
    &.danger {
      border-color: #f56c6c;
      background-color: #f56c6c;
      .el-icon { color: #fff; }
    }
  }
  
  .node-header {
    font-size: 14px;
    color: #999;
    margin-bottom: 12px;
    &.no-card { color: #999; }
  }
  
  .audit-card {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .audit-user-row {
    display: flex;
    align-items: flex-start;
    gap: 12px;
  }
  
  .user-avatar {
    width: 32px;
    height: 32px;
    background: #cbd5e1;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    font-size: 14px;
    flex-shrink: 0;
  }
  
  .user-info {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .user-name {
    font-size: 14px;
    color: #333;
  }
  
  .audit-status-tag {
    display: flex;
    align-items: center;
    gap: 8px;
    .status-text { font-size: 13px; &.success { color: #67c23a; } }
    .audit-time { font-size: 13px; color: #999; }
  }
  
  .audit-opinion {
    font-size: 13px;
    color: #333;
    padding-top: 5px;
    margin-left: 0px; // 原型图中意见在头像下方
  }
}

.end-node { margin-bottom: 0; }

/* 强制所有字体不加粗 */
:deep(*) {
  font-weight: 400 !important;
}
</style>
