<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" inline label-width="80px">
        <el-form-item label="计划编号" prop="planNo" class="custom-form-item">
          <el-input v-model="queryParams.planNo" placeholder="请输入计划编号" clearable />
        </el-form-item>
        <el-form-item label="拜访人" prop="visitorId" class="custom-form-item">
          <el-select v-model="queryParams.visitorId" placeholder="请选择" clearable filterable style="width: 200px">
            <el-option v-for="item in staffOptions" :key="item.staffId" :label="item.staffName + (item.staffCode ? ' (' + item.staffCode + ')' : '')" :value="item.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划状态" prop="status" class="custom-form-item">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable>
            <el-option label="待审核" value="0" />
            <el-option label="已审核" value="1" />
            <el-option label="已驳回" value="2" />
          </el-select>
        </el-form-item>
        <div class="search-btns-area">
          <el-button icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        </div>
      </el-form>
    </el-card>

    <div class="title-container">
      <span class="list-title">拜访计划信息列表</span>
    </div>

    <!-- 列表区域 -->
    <el-card shadow="never" class="table-card" style="margin-top: 10px;">
      <el-table v-loading="loading" :data="dataList" border class="custom-table" :header-cell-style="{ background: '#f8fafc', color: '#333', fontWeight: 'bold' }">
        <el-table-column label="计划编号" align="center" prop="planNo" width="180">
          <template #default="scope">
            <span class="link-text" @click="handleDetail(scope.row)">{{ scope.row.planNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="拜访人" align="center" prop="visitorName" min-width="120" />
        <el-table-column label="开始时间" align="center" prop="startTime" min-width="150">
          <template #default="scope">{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" min-width="150">
          <template #default="scope">{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.status === '0'" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.status === '1'" type="success">已审核</el-tag>
            <el-tag v-else-if="scope.row.status === '2'" type="danger">已驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <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>
            <el-button link type="info" @click="handleDelete(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>

    <!-- 详情抽屉 -->
    <el-drawer v-model="detailOpen" size="80%" direction="rtl" destroy-on-close class="plan-detail-drawer" :with-header="false">
      <div class="drawer-header">
        <span class="header-title">拜访计划明细</span>
        <el-icon class="close-icon" @click="detailOpen = false"><Close /></el-icon>
      </div>
      
      <div class="drawer-body">
        <!-- 左侧主体内容 -->
        <div class="main-content">
          <div class="content-tabs">
            <div class="tab-item active">资料</div>
          </div>
          
          <div class="content-scroll">
            <!-- 基本信息 -->
            <div class="section-container">
              <div class="section-header-grey">
                <span class="title">基本信息</span>
              </div>
              <div class="info-grid-2">
                <div class="info-item"><span class="label">计划编号</span><span class="value">{{ detailData.planNo }}</span></div>
                <div class="info-item"><span class="label">拜访人</span><span class="value">{{ detailData.visitorName }}</span></div>
                <div class="info-item"><span class="label">开始时间</span><span class="value">{{ parseTime(detailData.startTime, '{y}-{m}-{d}') }}</span></div>
                <div class="info-item"><span class="label">结束时间</span><span class="value">{{ parseTime(detailData.endTime, '{y}-{m}-{d}') }}</span></div>
                <div class="info-item"><span class="label">状态</span>
                  <span class="value">
                    <template v-if="detailData.status === '0'">待审核</template>
                    <template v-else-if="detailData.status === '1'">已审核</template>
                    <template v-else-if="detailData.status === '2'">已驳回</template>
                  </span>
                </div>
              </div>
            </div>

            <!-- 日程信息 -->
            <div class="section-container" style="margin-top: 20px;">
              <div class="section-header-grey">
                <span class="title">日程信息</span>
              </div>
              <el-table :data="scheduleData" border class="custom-table" style="margin-top: 15px;">
                <el-table-column label="拜访日期" align="center" prop="visitDate" width="120" sortable />
                <el-table-column label="客户名称" align="center" prop="customerName" min-width="200" />
                <el-table-column label="关联对象" align="center" prop="relatedObject" min-width="120" />
                <el-table-column label="关联类型" align="center" prop="relatedType" width="100" />
                <el-table-column label="紧要程度" align="center" prop="urgency" width="100" />
                <el-table-column label="拜访目的" align="center" prop="purpose" min-width="150" show-overflow-tooltip />
                <el-table-column label="操作" align="center" width="100">
                  <template #default="scope">
                    <el-button link type="primary" @click="handleViewSchedule(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 右侧侧边栏 -->
        <div class="side-panel">
          <!-- 顶部标签栏 -->
          <div class="side-tabs-header">
            <div
              v-for="tab in [{k:'team',n:'团队成员'},{k:'logs',n:'操作日志'},{k:'admin',n:'管理信息'}]"
              :key="tab.k"
              :class="['side-tab-item', { active: activeSideTab === tab.k }]"
              @click="activeSideTab = tab.k"
            >{{ tab.n }}</div>
          </div>

          <div class="side-tab-content">
            <!-- 团队成员 Tab -->
            <div v-show="activeSideTab === 'team'">
               <div class="team-tab-header">
                 <div class="team-title">团队成员 ({{ teamList.length }})</div>
                 <el-button link type="primary" icon="Plus" @click="handleAddMember"></el-button>
               </div>
               
               <div class="team-search">
                 <el-input v-model="memberSearch" placeholder="请输入成员" prefix-icon="Search" size="small" clearable />
               </div>

               <div class="member-list">
                 <div v-for="(member, index) in filteredTeamList" :key="member.id || index" class="member-card">
                   <div class="m-left">
                      <el-avatar :size="36" icon="UserFilled" class="m-avatar" />
                      <div class="m-info">
                        <div class="m-line">
                          <span class="m-name">{{ member.realName || member.staffName || member.userName }}</span>
                          <span class="tag principal" v-if="member.isPrincipal || member.izManager === 1">负责人</span>
                          <span class="tag-text">{{ member.roleName || getRoleLabel(member.roleCode || member.role) }}</span>
                          <span class="tag-text">{{ member.updateAccredit == 1 || member.permission == 1 ? '仅查看' : '修改权限' }}</span>
                        </div>
                      </div>
                   </div>
                   <div class="m-ops">
                     <el-button link type="primary" @click="handleEditMember(member)">编辑</el-button>
                     <el-button link type="danger" @click="handleDeleteMember(member)">删除</el-button>
                   </div>
                 </div>
                 <el-empty v-if="filteredTeamList.length === 0" description="暂无成员" :image-size="60" />
               </div>
            </div>

            <!-- 操作日志 Tab -->
            <div v-show="activeSideTab === 'logs'">
              <div class="log-list" v-loading="logLoading">
                <div v-if="operateLogs && operateLogs.length > 0">
                   <div v-for="(log, index) in operateLogs" :key="log.id || index" class="log-item">
                     <span class="log-time">{{ parseTime(log.createTime || log.operateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                     <span class="log-user">{{ log.operator || log.operateBy || log.createByName || '系统' }}</span>
                     <span class="log-action">{{ getOperateTypeText(log.actionType || log.operateType) }}了</span>
                     <span class="log-target-link">{{ translateLogTarget(log.actionDetails) }}<template v-if="log.targetObject || log.target">：<span class="log-target-detail">{{ log.targetObject || log.target }}</span></template></span>
                   </div>
                </div>
                <div v-else class="empty-logs">
                  <el-empty description="暂无操作日志" :image-size="60" />
                </div>
              </div>
            </div>

            <!-- 管理信息 Tab -->
            <div v-show="activeSideTab === 'admin'">
              <div class="admin-tab-content">
                <div class="admin-grid">
                  <div class="admin-cell">
                    <span class="label">创建日期</span>
                    <span class="value">{{ parseTime(detailData.createTime || detailData.createDate, '{y}-{m}-{d}') || '--' }}</span>
                  </div>
                  <div class="admin-cell">
                    <span class="label">创建人</span>
                    <span class="value">{{ detailData.createByName || detailData.createUserName || detailData.nickName || detailData.createBy || '--' }}</span>
                  </div>
                  <div class="admin-cell">
                    <span class="label">修改日期</span>
                    <span class="value">{{ parseTime(detailData.updateTime || detailData.updateDate, '{y}-{m}-{d}') || '--' }}</span>
                  </div>
                  <div class="admin-cell">
                    <span class="label">最后修改人</span>
                    <span class="value">{{ detailData.updateByName || detailData.updateUserName || detailData.updateBy || '--' }}</span>
                  </div>
                  <div class="admin-cell" v-if="detailData.auditByName || detailData.auditBy">
                    <span class="label">审核人</span>
                    <span class="value">{{ detailData.auditByName || detailData.auditBy || '--' }}</span>
                  </div>
                  <div class="admin-cell" v-if="detailData.auditTime">
                    <span class="label">审核时间</span>
                    <span class="value">{{ parseTime(detailData.auditTime, '{y}-{m}-{d}') || '--' }}</span>
                  </div>
                  <div class="admin-cell" v-if="detailData.deptName">
                    <span class="label">所属部门</span>
                    <span class="value">{{ detailData.deptName || '--' }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 新增/编辑拜访计划抽屉 -->
    <el-drawer :title="title" v-model="open" size="80%" direction="rtl" destroy-on-close class="plan-drawer">
      <div class="dialog-content-area">
        <!-- 基本信息 -->
        <div class="section-container">
          <div class="section-title">基本信息</div>
          <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="basic-info-form">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="拜访人：" prop="visitorId">
                  <el-select v-model="form.visitorId" placeholder="请选择" style="width: 100%" clearable filterable @change="handleStaffChange">
                    <el-option v-for="item in staffOptions" :key="item.staffId" :label="item.staffName + (item.staffCode ? ' (' + item.staffCode + ')' : '')" :value="item.staffId" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开始时间：" prop="startTime">
                  <el-date-picker v-model="form.startTime" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结束时间：" prop="endTime">
                  <el-date-picker v-model="form.endTime" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 日程信息 -->
        <div class="section-container">
          <div class="section-header">
            <div class="section-title">日程信息</div>
            <el-button link type="primary" icon="Plus" @click="handleAddSchedule">新建</el-button>
          </div>
          <el-table :data="form.detailList" border class="schedule-table">
            <el-table-column label="拜访日期" align="center" prop="visitDate" width="150" sortable />
            <el-table-column label="客户名称" align="center" prop="customerName" min-width="150" />
            <el-table-column label="关联对象" align="center" prop="relatedObject" min-width="150" />
            <el-table-column label="关联类型" align="center" prop="relatedType" width="120" />
            <el-table-column label="紧要程度" align="center" prop="urgency" width="100" />
            <el-table-column label="拜访目的" align="center" prop="purpose" min-width="150" show-overflow-tooltip />
            <el-table-column label="操作" align="center" width="120">
              <template #default="scope">
                <el-button link type="primary" @click="handleEditSchedule(scope.$index, scope.row)">编辑</el-button>
                <el-button link type="danger" @click="handleDeleteSchedule(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <!-- 暂无数据插槽 -->
            <template #empty>
              <div style="padding: 30px 0; color: #909399;">暂无数据</div>
            </template>
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 新建日程对话框 -->
    <el-dialog :title="scheduleTitle" v-model="scheduleOpen" width="700px" append-to-body destroy-on-close class="schedule-dialog">
      <el-form ref="scheduleFormRef" :model="scheduleForm" :rules="scheduleRules" label-width="110px">
        <el-form-item label="关联类型：" prop="relatedType">
          <el-radio-group v-model="scheduleForm.relatedType">
            <el-radio label="客户">客户</el-radio>
            <el-radio label="项目商机">项目商机</el-radio>
            <el-radio label="年度入围">年度入围</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item :label="(scheduleForm.relatedType || '客户') + '：'" prop="customerName">
          <el-select v-model="scheduleForm.customerName" placeholder="请选择" style="width: 100%" filterable>
            <el-option v-for="item in customerOptions" :key="item.id" :label="item.customerName" :value="item.customerName" />
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="拜访日期：" prop="visitDate">
              <el-date-picker v-model="scheduleForm.visitDate" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧要程度：" prop="urgency">
              <el-select v-model="scheduleForm.urgency" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="dict in urgencyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="随访人：" prop="accompanyPerson">
          <el-select v-model="scheduleForm.accompanyPerson" placeholder="请选择" style="width: 100%" multiple>
            <el-option v-for="item in staffOptions" :key="item.staffId" :label="item.staffName + (item.staffCode ? ' (' + item.staffCode + ')' : '')" :value="item.staffName" />
          </el-select>
        </el-form-item>

        <el-form-item label="拜访目的：" prop="purpose">
          <el-input v-model="scheduleForm.purpose" type="textarea" :rows="5" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSchedule">确 认</el-button>
          <el-button @click="scheduleOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核明细抽屉 -->
    <el-drawer title="查看审核明细" v-model="auditOpen" size="500px" direction="rtl" destroy-on-close class="audit-drawer">
      <div class="audit-timeline-container" v-if="auditData.length > 0">
        <el-timeline>
          <el-timeline-item v-for="(item, index) in auditData" :key="index"
            :color="item.status === '1' ? '#10b981' : '#f56c6c'" :size="'large'"
            :icon="item.status === '1' ? 'Check' : 'Close'">
            <div class="audit-node">
              <div class="audit-header">
                <span class="audit-title">审核人：{{ item.status === '1' ? '已审批' : '已驳回' }}</span>
              </div>
              <div class="audit-content-card">
                <div class="audit-user-info">
                  <div class="avatar-box">{{ (item.auditByName || '').charAt(0) }}</div>
                  <span class="user-name">{{ item.auditByName }}</span>
                  <span :class="'audit-status ' + (item.status === '1' ? 'pass' : 'reject')">
                    {{ item.status === '1' ? '已通过' : '已驳回' }}
                    <span class="time-text">{{ parseTime(item.auditTime) }}</span>
                  </span>
                </div>
                <div class="audit-opinion">审核意见：{{ item.remark || '无' }}</div>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <el-empty v-else description="暂无审核记录" />
    </el-drawer>

    <!-- 编辑团队成员对话框 -->
    <el-dialog title="编辑团队成员" v-model="memberDialogOpen" width="500px" append-to-body class="member-edit-dialog">
      <el-form :model="memberForm" label-width="100px">
        <el-form-item label="人员姓名：">
          <span>{{ memberForm.userName }}</span>
        </el-form-item>
        <el-form-item label="成员角色：">
          <el-select v-model="memberForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="role in memberRoleOptions" :key="role.dictValue" :label="role.dictLabel" :value="role.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限：">
          <el-radio-group v-model="memberForm.permission">
            <el-radio value="1">仅查看</el-radio>
            <el-radio value="2">修改权限</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMemberDetail">确 认</el-button>
          <el-button @click="memberDialogOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加团队成员对话框 -->
    <el-dialog title="添加团队成员" v-model="addMemberDialogOpen" width="500px" append-to-body destroy-on-close class="member-add-dialog">
      <el-form :model="addMemberForm" label-width="100px">
        <el-form-item label="人员姓名：" :rules="[{ required: true, message: '请选择人员', trigger: 'change' }]">
          <el-select v-model="addMemberForm.staffId" placeholder="请选择人员" filterable style="width: 100%">
            <el-option v-for="user in staffOptions" :key="user.staffId" :label="user.staffName" :value="user.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item label="成员角色：">
          <el-select v-model="addMemberForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="role in memberRoleOptions" :key="role.dictValue" :label="role.dictLabel" :value="role.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限：">
          <el-radio-group v-model="addMemberForm.permission">
            <el-radio value="1">仅查看</el-radio>
            <el-radio value="2">修改权限</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddMember">确 认</el-button>
          <el-button @click="addMemberDialogOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看日程对话框 -->
    <el-dialog title="查看日程" v-model="viewScheduleOpen" width="700px" append-to-body destroy-on-close class="schedule-view-dialog">
      <el-form ref="viewScheduleFormRef" :model="viewScheduleForm" label-width="110px">
        <el-form-item label="关联类型：">
          <span>{{ viewScheduleForm.relatedType }}</span>
        </el-form-item>
        <el-form-item :label="(viewScheduleForm.relatedType || '客户') + '：'">
          <span>{{ viewScheduleForm.customerName }}</span>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="拜访日期：">
              <span>{{ parseTime(viewScheduleForm.visitDate, '{y}-{m}-{d}') }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧要程度：">
              <el-select v-model="viewScheduleForm.urgency" placeholder="请选择" disabled style="width: 100%">
                <el-option
                  v-for="dict in urgencyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="随访人：">
          <span>{{ viewScheduleForm.accompanyPersons }}</span>
        </el-form-item>

        <el-form-item label="拜访目的：">
          <el-input v-model="viewScheduleForm.purpose" type="textarea" :rows="5" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewScheduleOpen = false">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增跟进记录对话框 -->
    <el-dialog title="跟进记录" v-model="recordDialogOpen" width="600px" append-to-body destroy-on-close class="record-add-dialog">
      <el-form ref="recordFormRef" :model="recordForm" :rules="recordRules" label-width="110px">
        <el-form-item label="客户：">
          <span style="color: #333;">{{ detailData.visitorName || '-' }}</span>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="随访人：" prop="accompanyPerson">
              <el-select v-model="recordForm.accompanyPerson" multiple placeholder="请选择" style="width: 100%">
                <el-option v-for="item in staffOptions" :key="item.staffId" :label="item.staffName + (item.staffCode ? ' (' + item.staffCode + ')' : '')" :value="item.staffName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拜访方式：" prop="visitType">
              <el-select v-model="recordForm.visitType" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="dict in visitTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="拜访时间：" prop="visitTime">
              <el-date-picker v-model="recordForm.visitTime" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次拜访时间：" prop="nextVisitTime">
              <el-date-picker v-model="recordForm.nextVisitTime" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="拜访目的：" prop="purpose">
          <el-input v-model="recordForm.purpose" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="跟进情况：" prop="progress">
          <el-input v-model="recordForm.progress" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="记录图片：">
          <div style="width: 80px; height: 80px; border: 1px dashed #d9d9d9; border-radius: 4px; display: flex; align-items: center; justify-content: center; cursor: pointer; color: #999;">
            <el-icon :size="20"><Plus /></el-icon>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRecord">确 认</el-button>
          <el-button @click="recordDialogOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="VisitPlan">
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue';
import { Plus, Close, Search, Refresh, Delete, Check, Document } from '@element-plus/icons-vue';
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/visit/plan";
import { getDicts } from "@/api/system/dict/data";
import { listCommonDict } from "@/api/customer/customerDict";
import { listOperateLog } from "@/api/visit/operateLog";
import { listRecord as listVisitRecord } from "@/api/visit/record";
import { addRecord } from "@/api/visit/record";
import { selectStaffOptionList } from "@/api/customer/crmStaff";
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listTeamMember, addTeamMember, delTeamMember } from "@/api/customer/teamMember";

const { proxy } = getCurrentInstance();

const urgencyOptions = ref([]);
const visitTypeOptions = ref([]);
const staffOptions = ref([]);
const customerOptions = ref([]);
const visitTypeQuery = ref('');
const recordFormRef = ref(null);
const recordList = ref([]);
const followUpRecords = ref([]);
const filteredRecordList = computed(() => {
  if (!visitTypeQuery.value) return recordList.value;
  return recordList.value.filter(item => item.visitType === visitTypeQuery.value);
});

const loading = ref(false);
const dataList = ref([]);
const total = ref(0);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  planNo: undefined,
  visitorId: undefined,
  visitorName: undefined,
  status: undefined
});

// 主表单状态
const open = ref(false);
const title = ref("");
const isDetail = ref(false);
const detailOpen = ref(false);
const detailData = ref({});
const activeSideTab = ref('team');
const memberSearch = ref('');
const teamList = ref([]);
const memberRoleOptions = ref([]);
const filteredTeamList = computed(() => {
  if (!memberSearch.value) return teamList.value;
  return teamList.value.filter(m => (m.userName || m.realName || m.staffName || '').includes(memberSearch.value));
});
const memberDialogOpen = ref(false);
const addMemberDialogOpen = ref(false);
const editingMemberIndex = ref(-1);
const isEditMode = ref(false);
const recordDialogOpen = ref(false);

const memberForm = reactive({
  staffId: undefined,
  userName: '',
  role: '2',
  permission: '2'
});

const addMemberForm = reactive({
  staffId: undefined,
  role: '2',
  permission: '2'
});

const handleAddMember = () => {
  addMemberForm.staffId = undefined;
  addMemberForm.role = '2';
  addMemberForm.permission = '2';
  isEditMode.value = false;
  addMemberDialogOpen.value = true;
};

const rules = {
  visitorId: [{ required: true, message: "请选择拜访人", trigger: "change" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }]
};

// 日程表单状态
const scheduleOpen = ref(false);
const scheduleTitle = ref("新建日程");
const currentEditIndex = ref(-1);

const initScheduleForm = () => ({
  relatedType: '客户',
  customerName: '',
  relatedObject: '',
  visitDate: '',
  urgency: '',
  accompanyPerson: [],
  purpose: ''
});
const scheduleForm = ref(initScheduleForm());

const scheduleRules = {
  customerName: [{ required: true, message: "请选择关联对象", trigger: "change" }],
  visitDate: [{ required: true, message: "请选择拜访日期", trigger: "change" }],
  urgency: [{ required: true, message: "请选择紧要程度", trigger: "change" }],
  purpose: [{ required: true, message: "请输入拜访目的", trigger: "blur" }]
};

// 审核明细状态
const auditOpen = ref(false);

// 查看日程状态
const viewScheduleOpen = ref(false);
const viewScheduleForm = ref({});

// 获取列表数据
const getList = () => {
  loading.value = true;
  listPlan(queryParams).then(response => {
    dataList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

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

const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};

const handleAdd = () => {
  form.value = initForm();
  isDetail.value = false;
  title.value = "新增拜访计划";
  open.value = true;
};

const operateLogs = ref([]);
const auditData = ref([]);
const logLoading = ref(false);

const scheduleData = ref([]);

const initForm = () => ({
  id: undefined,
  planNo: '',
  visitorId: undefined,
  visitorName: '',
  startTime: '',
  endTime: '',
  detailList: []
});
const form = ref(initForm());
const formRef = ref();

const handleDetail = (row) => {
  logLoading.value = true;
  getPlan(row.id).then(response => {
    detailData.value = response.data;
    scheduleData.value = response.data.detailList || [];
    listOperateLog({ planId: row.id }).then(res => {
      operateLogs.value = res.data || res.rows || [];
    }).catch(() => {
      operateLogs.value = [];
    }).finally(() => {
      logLoading.value = false;
    });
    listVisitRecord({ planId: row.id }).then(res => {
      followUpRecords.value = res.rows || [];
      recordList.value = res.rows || [];
    });
    listTeamMember(row.id).then(res => {
      teamList.value = res.rows || res.data || [];
    }).catch(() => {
      teamList.value = [];
    });
    detailOpen.value = true;
  });
};

/** 选择人员处理 */
const handleStaffChange = (val) => {
  if (val) {
    const staff = staffOptions.value.find(item => item.staffId === val);
    if (staff) {
      form.value.visitorName = staff.staffName;
    }
  } else {
    form.value.visitorName = '';
  }
};

const handleNewRecord = () => {
  recordDialogOpen.value = true;
};

const handleEditMember = (member) => {
  editingMemberIndex.value = teamList.value.indexOf(member);
  isEditMode.value = true;
  memberForm.staffId = member.userNo || member.staffId;
  memberForm.userName = member.realName || member.staffName || member.userName || '';
  memberForm.role = String(member.roleCode || member.role || '2');
  memberForm.permission = String(member.updateAccredit ?? member.permission ?? '2');
  memberDialogOpen.value = true;
};

const submitAddMember = () => {
  if (!addMemberForm.staffId) {
    proxy.$modal.msgWarning("请选择人员");
    return;
  }
  const selectedUser = staffOptions.value.find(u => u.staffId == addMemberForm.staffId);
  addTeamMember({
    dataType: 3,
    objectNo: String(detailData.value.id),
    userNo: addMemberForm.staffId,
    realName: selectedUser?.staffName || '',
    roleCode: addMemberForm.role,
    updateAccredit: Number(addMemberForm.permission)
  }).then(() => {
    proxy.$modal.msgSuccess("添加成功");
    addMemberDialogOpen.value = false;
    listTeamMember(detailData.value.id).then(res => {
      teamList.value = res.rows || res.data || [];
    });
  }).catch(() => {});
};

const submitMemberDetail = () => {
  const member = teamList.value[editingMemberIndex.value];
  if (member && member.id) {
    const data = { id: member.id, roleCode: memberForm.role, updateAccredit: Number(memberForm.permission) };
    Object.assign(member, {
      roleCode: memberForm.role,
      updateAccredit: Number(memberForm.permission)
    });
    proxy.$modal.msgSuccess("修改成功");
  } else {
    proxy.$modal.msgSuccess("修改成功");
  }
  memberDialogOpen.value = false;
};

const handleDeleteMember = (member) => {
  if (!member || !member.id) return;
  proxy.$modal.confirm(`确认移除成员"${member.realName || member.staffName || member.userName}"吗？`).then(() => {
    delTeamMember(member.id).then(() => {
      proxy.$modal.msgSuccess("移除成功");
      listTeamMember(detailData.value.id).then(res => {
        teamList.value = res.rows || res.data || [];
      });
    }).catch(() => {});
  }).catch(() => {});
};

const getRoleLabel = (code) => {
  if (!code) return '普通成员';
  const found = memberRoleOptions.value.find(r => String(r.dictValue) === String(code));
  return found ? found.dictLabel : code;
};

const getOperateTypeText = (type) => {
  const map = { 1: '添加', 2: '编辑', 3: '删除', 4: '审核', 5: '转移', 6: '分析' };
  if (!type && type !== 0) return '操作';
  return map[String(type)] || `${type} `;
};

const translateLogTarget = (details) => {
  if (!details) return '拜访计划';
  if (details.includes('拜访计划') || details.includes('plan')) return '拜访计划';
  if (details.includes('日程') || details.includes('schedule')) return '日程';
  return '拜访计划';
};

const formatLogTarget = (log) => {
  if (!log) return '';
  const target = log.targetObject || log.target;
  if (!target) return '';
  if (target === log.actionDetails) return '';
  return target;
};

const submitRecord = () => {
  recordFormRef.value.validate(valid => {
    if (valid) {
      const data = {
        ...recordForm.value,
        planId: detailData.value.id,
        customerName: detailData.value.customerName,
        accompanyPerson: recordForm.value.accompanyPerson ? recordForm.value.accompanyPerson.join(',') : '',
        platformCode: 'crm'
      };
      addRecord(data).then(response => {
        proxy.$modal.msgSuccess("新增跟进记录成功");
        recordDialogOpen.value = false;
        // 刷新详情页的跟进记录
        listRecord({ planId: detailData.value.id }).then(res => {
          followUpRecords.value = res.rows || [];
        });
      });
    }
  });
};

const handleAuditDetail = (row) => {
  auditData.value = row.auditList || [];
  auditOpen.value = true;
};

const handleViewSchedule = (row) => {
  viewScheduleForm.value = JSON.parse(JSON.stringify(row));
  viewScheduleOpen.value = true;
};

const handleDelete = (row) => {
  const ids = row.id || proxy.selectIds;
  proxy.$modal.confirm(`确认删除计划编号为"${row.planNo}"的数据项吗？`).then(() => {
    return delPlan(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

const submitForm = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updatePlan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPlan(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

const cancel = () => {
  open.value = false;
};

// 日程操作
const handleAddSchedule = () => {
  scheduleForm.value = initScheduleForm();
  currentEditIndex.value = -1;
  scheduleTitle.value = "新建日程";
  scheduleOpen.value = true;
};

const handleEditSchedule = (index, row) => {
  const data = JSON.parse(JSON.stringify(row));
  if (data.accompanyPersons && typeof data.accompanyPersons === 'string') {
    data.accompanyPerson = data.accompanyPersons.split(',');
  } else {
    data.accompanyPerson = [];
  }
  scheduleForm.value = data;
  currentEditIndex.value = index;
  scheduleTitle.value = "编辑日程";
  scheduleOpen.value = true;
};

const handleDeleteSchedule = (index) => {
  form.value.detailList.splice(index, 1);
};

const submitSchedule = () => {
  proxy.$refs["scheduleFormRef"].validate((valid) => {
    if (valid) {
      const detail = {
        ...scheduleForm.value,
        relatedObject: scheduleForm.value.customerName,
        accompanyPersons: scheduleForm.value.accompanyPerson ? scheduleForm.value.accompanyPerson.join(',') : ''
      };
      
      if (currentEditIndex.value === -1) {
        form.value.detailList.push(detail);
      } else {
        form.value.detailList[currentEditIndex.value] = detail;
      }
      scheduleOpen.value = false;
    }
  });
};

onMounted(() => {
  getList();
  listCommonDict('T0001').then(res => {
    memberRoleOptions.value = res.data || [];
  });
  getDicts("crm_visit_urgency").then(response => {
    urgencyOptions.value = response.data || [];
  }).catch(e => {
    console.error('获取字典失败：', e);
  });
  getDicts("crm_visit_type").then(response => {
    visitTypeOptions.value = response.data || [];
  }).catch(() => {});
  selectStaffOptionList().then(response => {
    staffOptions.value = response.data || [];
  }).catch(() => {});
  listCustomerInfo().then(response => {
    customerOptions.value = response.rows || [];
  }).catch(() => {});
});
</script>

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

.search-card {
  border: none;
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

:deep(.el-form--inline) {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.custom-form-item {
  margin-bottom: 0 !important;
  margin-right: 0px;
  :deep(.el-form-item__label) {
    padding-right: 12px;
    color: #333;
    font-weight: 400;
  }
  :deep(.el-input), :deep(.el-select), :deep(.el-date-editor) {
    width: 220px;
  }
}

.search-btns-area {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-container {
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
  background-color: #fff;
  padding-left: 20px;
  border-radius: 4px 4px 0 0;
  .list-title {
    font-size: 14px;
    font-weight: 500;
    color: #333;
  }
}

.table-card {
  border: none;
  border-radius: 0 0 4px 4px;
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.link-text {
  color: #409eff;
  cursor: pointer;
}

/* 计划抽屉样式 */
.plan-drawer {
  :deep(.el-drawer__header) {
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 0;
    padding: 15px 20px;
    .el-drawer__title { font-size: 15px; color: #333; font-weight: bold; }
  }
}

.plan-detail-drawer {
  :deep(.el-drawer__body) {
    padding: 0;
    overflow: hidden;
  }
}

.drawer-header {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
  .header-title { font-size: 16px; font-weight: bold; color: #333; }
  .close-icon { cursor: pointer; color: #999; font-size: 18px; &:hover { color: #f5222d; } }
}

.drawer-body {
  height: calc(100vh - 50px);
  display: flex;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-right: 1px solid #f0f0f0;
  
  .content-tabs {
    padding: 0 20px;
    border-bottom: 1px solid #f0f0f0;
    .tab-item {
      display: inline-block;
      padding: 12px 0;
      margin-right: 30px;
      color: #595959;
      font-size: 14px;
      cursor: pointer;
      position: relative;
      
      &.active {
        color: #f5222d;
        font-weight: bold;
        &::after {
          content: "";
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          height: 2px;
          background-color: #f5222d;
        }
      }
    }
  }
  
  .content-scroll {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
  }
}

.section-header-grey {
  background-color: #f5f7fa;
  padding: 10px 15px;
  margin-bottom: 5px;
  .title {
    font-size: 14px;
    font-weight: bold;
    color: #409eff;
  }
}

.info-grid-2 {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px 40px;
  padding: 15px;
  .info-item {
    display: flex;
    font-size: 13px;
    align-items: flex-start;
    .label { color: #8c8c8c; width: 80px; flex-shrink: 0; }
    .value { color: #262626; word-break: break-all; }
  }
}

.team-tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0 12px;
  .team-title { font-size: 14px; font-weight: 600; color: #1d2129; }
}

.team-search {
  padding: 0 0 16px;
}

.member-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 4px;
  border-bottom: 1px solid #f2f3f5;
  &:hover { background-color: #fafbfc; }
  .m-left {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 0;
    .m-avatar { flex-shrink: 0; }
    .m-info {
      margin-left: 10px;
      flex: 1;
      min-width: 0;
      .m-line {
        display: flex;
        align-items: center;
        flex-wrap: nowrap;
        gap: 8px;
        line-height: 26px;
      }
      .m-name { font-size: 14px; color: #1d2129; font-weight: 500; white-space: nowrap; }
      .tag {
        font-size: 12px;
        padding: 0 6px;
        height: 22px;
        line-height: 20px;
        border-radius: 3px;
        display: inline-flex;
        align-items: center;
        white-space: nowrap;
        &.principal { color: #00b42a; background: transparent; border: 1px solid #00b42a; }
      }
      .tag-text { font-size: 13px; color: #86909c; white-space: nowrap; }
    }
  }
  .m-ops {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-left: 12px;
    flex-shrink: 0;
    .el-button { font-size: 13px; padding: 0 4px; color: #409eff; &:hover { opacity: 0.8; } }
    .el-button--danger { color: #f53f3f; }
  }
}

.side-panel {
  width: 380px;
  background-color: #fff;
  padding: 0;
  display: flex;
  flex-direction: column;

  .side-tabs-header {
    display: flex;
    border-bottom: 1px solid #f1f5f9;
    flex-shrink: 0;
    background: #fff;

    .side-tab-item {
      flex: 1;
      text-align: center;
      padding: 16px 8px;
      font-size: 13px;
      color: #1d2129;
      cursor: pointer;
      transition: all 0.2s;
      position: relative;

      &:hover { color: #f53f3f; }

      &.active {
        color: #f53f3f;
        font-weight: 600;
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 32px;
          height: 3px;
          background: #f53f3f;
          border-radius: 2px;
        }
      }
    }
  }

  .side-tab-content {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
  }
}

.record-tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 5px;
  .add-record-btn {
    font-size: 13px;
    font-weight: normal;
  }
  .filter-box {
    display: flex;
    align-items: center;
    .label { font-size: 12px; color: #8c8c8c; margin-right: 8px; }
  }
}

.record-list {
  padding: 0 5px;
}

.record-card-mini {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  &:last-child { border-bottom: none; }
  .r-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-size: 12px;
    .r-time { color: #8c8c8c; margin-right: 10px; }
    .r-user { color: #409eff; margin-right: 8px; }
    .r-act { color: #595959; }
  }
  .r-content {
    font-size: 13px;
    color: #262626;
    line-height: 1.6;
  }
}

.log-list {
  padding: 15px 5px;
  .log-item {
    padding: 10px 0;
    font-size: 13px;
    display: flex;
    align-items: baseline;
    line-height: 1.8;
    border-bottom: 1px solid #f5f5f5;
    &:last-child { border-bottom: none; }
    .log-time { color: #c0c4cc; margin-right: 8px; flex-shrink: 0; white-space: nowrap; }
    .log-user { color: #409eff; margin-right: 4px; cursor: pointer; &:hover { text-decoration: underline; } }
    .log-action { color: #606266; margin-right: 4px; }
    .log-target-link { color: #409eff; cursor: pointer; &:hover { text-decoration: underline; } }
    .log-target-detail { color: #409eff; }
  }
  .empty-logs { text-align: center; padding: 30px 0; }
}

.admin-tab-content {
  padding: 20px 5px;
  .admin-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px 24px;
    .admin-cell {
      display: flex;
      align-items: center;
      .label { color: #86909c; font-size: 13px; width: 70px; flex-shrink: 0; }
      .value { color: #1d2129; font-size: 13px; }
    }
  }
}

.dialog-content-area {
  padding: 0 10px;
}

.section-container {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f4f6fc;
  padding: 8px 15px;
  margin-bottom: 5px;
}

.section-title {
  font-size: 14px;
  color: #409eff;
  background-color: #f4f6fc;
  padding: 8px 15px;
  display: inline-block;
  width: 100%;
}

.section-header .section-title {
  padding: 0;
  width: auto;
}

/* 审核明细时间轴 */
.audit-drawer {
  :deep(.el-drawer__header) {
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 0;
    padding: 15px 20px;
    color: #333;
  }
}
.audit-timeline-container { padding: 20px; }

.audit-node {
  .audit-header { margin-bottom: 8px; }
  .audit-title { font-size: 14px; font-weight: 500; color: #333; }
}
.audit-content-card {
  background: #f9fafb;
  border-radius: 6px;
  padding: 12px 16px;
  .audit-user-info {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
    .avatar-box {
      width: 32px; height: 32px; border-radius: 50%;
      background: #409eff; color: #fff;
      display: flex; align-items: center; justify-content: center;
      font-size: 14px; font-weight: bold;
    }
    .user-name { font-size: 14px; color: #333; }
    .audit-status { font-size: 13px; }
    .audit-status.pass { color: #67c23a; }
    .audit-status.reject { color: #f56c6c; }
    .time-text { color: #999; margin-left: 6px; font-size: 12px; }
  }
  .audit-opinion { font-size: 13px; color: #666; }
}

/* 成员编辑弹窗样式 */
.member-edit-dialog {
  :deep(.el-dialog__header) {
    margin-right: 0;
    border-bottom: 1px solid #f0f0f0;
    padding: 15px 20px;
    .el-dialog__title { font-size: 16px; font-weight: bold; }
  }
  .dialog-footer {
    text-align: center;
    padding-bottom: 10px;
  }
}

/* 日程查看弹窗样式 */
.schedule-view-dialog {
  :deep(.el-dialog__header) {
    background-color: #409eff;
    margin-right: 0;
    padding: 15px 20px;
    .el-dialog__title { color: #fff; font-size: 16px; }
    .el-dialog__headerbtn .el-dialog__close { color: #fff; }
  }
  .dialog-footer {
    text-align: right;
    padding: 10px 0;
  }
}
</style>
