<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customName" class="custom-form-item no-margin-item">
              <el-input v-model="queryParams.customName" placeholder="请输入客户名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人类型" prop="contactType" class="custom-form-item no-margin-item">
              <el-select v-model="queryParams.contactType" placeholder="请选择" clearable>
                <el-option label="公司职员" value="0" />
                <el-option label="关系资源人" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="sex" class="custom-form-item no-margin-item">
              <el-select v-model="queryParams.sex" placeholder="请选择" clearable>
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机" prop="phoneNumber" class="custom-form-item no-margin-item">
              <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="mt-15">
          <el-col :span="24">
            <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-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 列表标题 -->
    <div class="title-container">
      <span class="list-title">联系人信息列表</span>
    </div>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-card">
      <el-table ref="tableRef" 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="name" width="120">
          <template #default="scope">
            <span class="contact-name-text" @click="handleDetail(scope.row)">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="department" width="120" />
        <el-table-column label="客户名称" align="center" prop="customName" min-width="120" show-overflow-tooltip />
        <el-table-column label="职位" align="center" prop="position" width="150" />
        <el-table-column label="手机号码" align="center" prop="phoneNumber" width="150" />
        <el-table-column label="座机" align="center" prop="landline" width="150" />
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="danger" @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 :title="drawerTitle" v-model="open" direction="rtl" size="80%" destroy-on-close>
      <div class="drawer-body">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="right">
          <!-- 个人资料区块 -->
          <div class="dialog-section">
            <div class="section-title">个人资料</div>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="姓名" required prop="name">
                  <el-input v-model="form.name" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系人类型" prop="contactType">
                  <el-radio-group v-model="form.contactType">
                    <el-radio label="公司职员">公司职员</el-radio>
                    <el-radio label="关系资源人">关系资源人</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="年龄" prop="age">
                  <el-input v-model="form.age" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="form.sex">
                    <el-radio label="男">男</el-radio>
                    <el-radio label="女">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="籍贯" prop="nativePlace">
                  <el-input v-model="form.nativePlace" placeholder="请输入籍贯" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="生日" prop="birthday">
                  <el-date-picker v-model="form.birthday" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="描述" prop="characterDesc">
              <el-input v-model="form.characterDesc" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </div>

          <!-- 办公信息区块 -->
          <div class="dialog-section">
            <div class="section-title">办公信息</div>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="归属公司" required prop="companyNo">
                  <el-select v-model="form.companyNo" placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in belongCompanyOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户名称" required prop="customerNo">
                  <el-select v-model="form.customerNo" placeholder="请选择" style="width: 100%" filterable remote :remote-method="remoteLoadCustomers" :loading="selectLoading">
                    <el-option v-for="item in customerOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="在职状态" prop="employmentStatusCode">
                  <el-radio-group v-model="form.employmentStatusCode">
                    <el-radio label="在职">在职</el-radio>
                    <el-radio label="离职">离职</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="部门" required prop="department">
                  <el-input v-model="form.department" placeholder="请输入部门" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="职位" prop="position">
                  <el-input v-model="form.position" placeholder="请输入职位" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="手机号码" required prop="phoneNumber">
                  <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="办公座机" prop="landline">
                  <el-input v-model="form.landline" placeholder="请输入办公座机" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="办公地址" prop="provinceCity">
                  <el-cascader
                    v-model="form.provinceCity"
                    :options="provinceOptions"
                    placeholder="请选择"
                    style="width: 100%"
                    :props="{ value: 'areaName', label: 'areaName', children: 'children' }"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label-width="0">
                  <el-input v-model="form.workAddress" placeholder="请输入详细地址" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="工作内容" prop="workDesc">
              <el-input v-model="form.workDesc" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="open = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 详情抽屉 -->
    <el-drawer v-model="detailOpen" direction="rtl" size="80%" destroy-on-close :with-header="false" class="detail-drawer">
      <div class="detail-container">
        <!-- 顶部标题栏 -->
        <div class="detail-header">
          <span class="detail-header-title">{{ detailData.customerName || '客户联系人详情' }}</span>
          <el-icon class="detail-close-btn" @click="detailOpen = false"><Close /></el-icon>
        </div>

        <!-- 内容区域：左侧主区域 + 右侧侧边栏 -->
        <div class="detail-body">
          <!-- 左侧主内容 -->
          <div class="detail-main">
            <!-- Tabs -->
            <div class="detail-tabs">
              <span :class="['tab-item', detailActiveTab === 'info' ? 'active' : '']" @click="detailActiveTab = 'info'">资料</span>
              <span :class="['tab-item', detailActiveTab === 'care' ? 'active' : '']" @click="detailActiveTab = 'care'">客户关怀</span>
            </div>

            <!-- 资料页签内容 -->
            <div v-if="detailActiveTab === 'info'" class="detail-info-content">
              <!-- 编辑按钮 -->
              <div class="detail-edit-bar">
                <el-button type="primary" size="small" icon="Edit" @click="handleEditFromDetail">编辑</el-button>
              </div>

              <!-- 个人信息 -->
              <div class="detail-section">
                <div class="detail-section-title">个人信息</div>
                <div class="detail-grid">
                  <div class="detail-field">
                    <span class="field-label">人员编号</span>
                    <span class="field-value id-text">{{ detailData.personnelNumber || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">姓名</span>
                    <span class="field-value">{{ detailData.name }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">联系人类型</span>
                    <span class="field-value">{{ detailData.contactType || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">性别</span>
                    <span class="field-value">{{ detailData.sex || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">年龄</span>
                    <span class="field-value">{{ detailData.age }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">籍贯</span>
                    <span class="field-value">{{ detailData.nativePlace || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">生日</span>
                    <span class="field-value">{{ detailData.birthday || '' }}</span>
                  </div>
                  <div class="detail-field full-width">
                    <span class="field-label">描述</span>
                    <span class="field-value">{{ detailData.characterDesc || '' }}</span>
                  </div>
                </div>
              </div>

              <!-- 办公信息 -->
              <div class="detail-section">
                <div class="detail-section-title">办公信息</div>
                <div class="detail-grid">
                  <div class="detail-field">
                    <span class="field-label">公司编号</span>
                    <span class="field-value">{{ detailData.companyNo || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">客户名称</span>
                    <span class="field-value">{{ detailData.customName || '' }}</span>
                  </div>
                  <div class="detail-field"></div>
                  <div class="detail-field">
                    <span class="field-label">在职状态</span>
                    <span class="field-value">{{ detailData.employmentStatusCode || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">手机号码</span>
                    <span class="field-value">{{ detailData.phoneNumber || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">部门</span>
                    <span class="field-value">{{ detailData.department || '' }}</span>
                  </div>
                  <div class="detail-field"></div>
                  <div class="detail-field">
                    <span class="field-label">办公座机</span>
                    <span class="field-value">{{ detailData.landline || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">办公地址</span>
                    <span class="field-value">{{ detailData.officeAddress || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">职位</span>
                    <span class="field-value">{{ detailData.position || '' }}</span>
                  </div>
                  <div class="detail-field"></div>
                  <div class="detail-field full-width">
                    <span class="field-label">工作地址</span>
                    <span class="field-value">{{ detailData.workAddress || '' }}</span>
                  </div>
                  <div class="detail-field full-width">
                    <span class="field-label">工作内容</span>
                    <span class="field-value">{{ detailData.workDesc || '' }}</span>
                  </div>
                </div>
              </div>

              <!-- 家庭信息 -->
              <div class="detail-section">
                <div class="detail-section-title">家庭信息</div>
                <div class="detail-grid">
                  <div class="detail-field full-width">
                    <span class="field-label">家庭住址</span>
                    <span class="field-value">{{ detailData.homeAddressDetail || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">家庭情况</span>
                    <span class="field-value">{{ detailData.familyStatus || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">爱好</span>
                    <span class="field-value">{{ detailData.hobby || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">性格特征</span>
                    <span class="field-value">{{ detailData.characterDesc || '' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">是否抽烟</span>
                    <span class="field-value">{{ detailData.izSmoking === 1 ? '是' : '否' }}</span>
                  </div>
                  <div class="detail-field">
                    <span class="field-label">是否喝酒</span>
                    <span class="field-value">{{ detailData.izWineDrink === 1 ? '是' : '否' }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 客户关怀页签 -->
            <div v-if="detailActiveTab === 'care'" class="detail-care-content">
              <div class="care-toolbar">
                <el-button type="primary" icon="Plus" @click="handleAddCare">新增</el-button>
              </div>
              <el-table :data="careList" v-loading="careLoading" border stripe>
                <el-table-column label="单据编号" align="center" prop="receiptId" min-width="150" show-overflow-tooltip />
                <el-table-column label="登记日期" align="center" prop="createTime" width="120">
                  <template #default="{ row }">{{ row.createTime || '' }}</template>
                </el-table-column>
                <el-table-column label="联系人" align="center" prop="contactPerson" min-width="100" show-overflow-tooltip />
                <el-table-column label="关怀类型" align="center" prop="concernType" width="120" show-overflow-tooltip />
                <el-table-column label="金额" align="center" prop="amount" width="120">
                  <template #default="{ row }">{{ row.amount ? '¥' + row.amount : '' }}</template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="80">
                  <template #default="{ row }">
                    <el-button link type="danger" size="small" @click="handleDeleteCare(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <!-- 右侧管理信息 -->
          <div class="detail-sidebar">
            <div class="sidebar-title">管理信息</div>
            <div class="sidebar-item">
              <span class="sidebar-label">创建日期</span>
              <span class="sidebar-value">{{ detailData.createTime }}</span>
            </div>
            <div class="sidebar-item">
              <span class="sidebar-label">创建人</span>
              <span class="sidebar-value">{{ detailData.createBy }}</span>
            </div>
            <div class="sidebar-item">
              <span class="sidebar-label">修改日期</span>
              <span class="sidebar-value">{{ detailData.updateTime }}</span>
            </div>
            <div class="sidebar-item">
              <span class="sidebar-label">最后修改人</span>
              <span class="sidebar-value">{{ detailData.updateBy }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 新增客户关怀对话框 -->
    <el-dialog v-model="careDialogVisible" title="新建客户关怀" width="700px" destroy-on-close>
      <el-form :model="careForm" label-width="90px">
        <div class="care-customer-name"><span class="required">*</span> 客户名称：{{ detailData.customerName || detailData.contactName }}</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行业">
              <el-input v-model="careForm.profession" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门">
              <el-input v-model="careForm.department" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务员">
              <el-input v-model="careForm.salesman" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input v-model="careForm.contactPerson" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机" required>
              <el-input v-model="careForm.phone" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="固定电话" required>
              <el-input v-model="careForm.telephone" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关怀类型" required>
              <el-select v-model="careForm.concernType" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in concernTypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额">
              <el-input v-model="careForm.amount" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="需求时间">
          <el-date-picker v-model="careForm.requirementDate" type="date" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="附件">
          <el-button icon="Upload">上传</el-button>
        </el-form-item>
        <el-form-item label="礼品描述" required>
          <el-input v-model="careForm.giftDesc" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="关怀理由" required>
          <el-input v-model="careForm.concernArgument" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto; justify-content: flex-end; display: flex; gap: 10px;">
          <el-button type="primary" @click="submitCareForm">确认</el-button>
          <el-button @click="careDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CustomerContact">
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from 'vue';
import { Close } from '@element-plus/icons-vue';
import { listContact, getContact, delContact, addContact, updateContact } from "@/api/customer/crmContact";
import { listCustomerInfo } from "@/api/customer/customerInfo/";
import { listCompanyOption } from "@/api/customer/customerInfo/";
import { listProvinceWithCities } from "@/api/customer/addressArea";
import { listCare, addCare as addCustomerCare, delCare as deleteCare } from "@/api/customer/crmCare";
import { listDictByType } from "@/api/customer/customerDict";

const { proxy } = getCurrentInstance();

const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
const open = ref(false);
const drawerTitle = ref("新增联系人");

/* 下拉选项 */
const belongCompanyOptions = ref([]);
const customerOptions = ref([]);
const provinceOptions = ref([]);
const selectLoading = ref(false);

/* 详情抽屉相关 */
const detailOpen = ref(false);
const detailActiveTab = ref('info');
const detailData = ref({});

/* 客户关怀相关 */
const careList = ref([]);
const careLoading = ref(false);
const careTotal = ref(0);
const careDialogVisible = ref(false);
const concernTypeOptions = ref([]);
const careForm = reactive({
  receiptId: '',
  concernType: '',
  amount: undefined,
  contactPerson: '',
  profession: '',
  department: '',
  salesman: '',
  phone: '',
  telephone: '',
  requirementDate: '',
  fileNo: '',
  giftDesc: '',
  concernArgument: ''
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  customName: undefined,
  contactType: undefined,
  name: undefined,
  sex: undefined,
  phoneNumber: undefined
});

const initFormData = () => ({
  id: undefined,
  personnelNumber: '',
  name: '',
  contactType: undefined,
  age: undefined,
  sex: undefined,
  nativePlace: '',
  birthday: undefined,
  workDesc: '',
  companyNo: undefined,
  customerNo: undefined,
  customName: '',
  employmentStatusCode: undefined,
  phoneNumber: '',
  department: '',
  position: '',
  landline: '',
  projectRole: '',
  izCruxPerson: '',
  officeAddress: '',
  workAddress: '',
  authorityDesc: '',
  projectRelationDesc: '',
  homeAddress: '',
  familyAddress: '',
  izSmoking: undefined,
  izWineDrink: undefined,
  familySituation: '',
  fond: '',
  characterDesc: '',
  platformCode: ''
});

const form = reactive(initFormData());

const rules = reactive({
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  companyNo: [{ required: true, message: "归属公司不能为空", trigger: "change" }],
  customerNo: [{ required: true, message: "客户名称不能为空", trigger: "change" }],
  department: [{ required: true, message: "部门不能为空", trigger: "blur" }],
  phoneNumber: [{ required: true, message: "手机号码不能为空", trigger: "blur" }]
});

/* 列表查询 */
const getList = () => {
  loading.value = true;
  listContact(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 loadBelongCompanyOptions = () => {
  listCompanyOption().then(res => {
    const options = (res.data || []).map(item => ({
      value: item.companyCode, // 使用 companyCode 对应后端 RemoteComCompanyVo
      label: item.companyName
    }));
    belongCompanyOptions.value = options;
  }).catch(() => {
    belongCompanyOptions.value = [];
  });
};

/* 加载省份列表（办公地址）- 省市两级联动 */
const loadProvinceOptions = () => {
  listProvinceWithCities().then(res => {
    provinceOptions.value = res.data || [];
  }).catch(() => {
    provinceOptions.value = [];
  });
};

/** 远程搜索客户 */
const remoteLoadCustomers = (query) => {
  selectLoading.value = true;
  listCustomerInfo({ customerName: query || undefined, pageSize: 20 }).then(res => {
    customerOptions.value = (res.rows || []).map(item => ({
      label: item.customerName,
      value: item.customerNo // 绑定编号
    }));
    selectLoading.value = false;
  }).catch(() => {
    selectLoading.value = false;
  });
};

/* 加载客户关怀列表 */
const loadCareList = () => {
  if (!detailData.value.id) return;
  careLoading.value = true;
  listCare({ customerId: detailData.value.id, pageNum: 1, pageSize: 100 }).then(res => {
    careList.value = res.rows || [];
    careTotal.value = res.total || 0;
    careLoading.value = false;
  }).catch(() => {
    careLoading.value = false;
  });
};

/* 新增客户关怀 */
const handleAddCare = () => {
  Object.assign(careForm, {
    receiptId: '',
    concernType: '',
    amount: undefined,
    contactPerson: detailData.value.contactName || '',
    profession: detailData.value.profession || '',
    department: detailData.value.deptName || '',
    salesman: detailData.value.salesman || '',
    phone: detailData.value.phone || '',
    telephone: detailData.value.officePhone || '',
    requirementDate: '',
    fileNo: '',
    giftDesc: '',
    concernArgument: ''
  });
  listDictByType('care_type').then(res => {
    concernTypeOptions.value = res.data || [];
  }).catch(() => {});
  careDialogVisible.value = true;
};

/* 提交客户关怀表单 */
const submitCareForm = () => {
  const submitData = { ...careForm, customerId: detailData.value.id };
  addCustomerCare(submitData).then(() => {
    proxy.$modal.msgSuccess("新增成功");
    careDialogVisible.value = false;
    loadCareList();
  }).catch(() => {});
};

/* 删除客户关怀 */
const handleDeleteCare = (row) => {
  proxy.$modal.confirm('确认删除该客户关怀记录吗？').then(() => {
    return deleteCare(row.id);
  }).then(() => {
    loadCareList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

/* 新增 */
const handleAdd = () => {
  resetForm();
  drawerTitle.value = "新增联系人";
  open.value = true;
  nextTick(() => {
    loadBelongCompanyOptions();
    loadProvinceOptions();
    remoteLoadCustomers('');
  });
};

/* 详情 */
const handleDetail = (row) => {
  const id = row.id;
  getContact(id).then(response => {
    detailData.value = response.data;
    detailActiveTab.value = 'info';
    detailOpen.value = true;
    loadCareList();
  }).catch(() => {});
};

/* 从详情页面进入编辑 */
const handleEditFromDetail = () => {
  detailOpen.value = false;
  resetForm();
  drawerTitle.value = "修改联系人";
  open.value = true;
  nextTick(() => {
    loadBelongCompanyOptions();
    loadProvinceOptions();
    remoteLoadCustomers('');
    Object.assign(form, detailData.value);
    // 处理级联地址回填
    if (form.officeAddress && typeof form.officeAddress === 'string') {
        form.provinceCity = form.officeAddress.split(',');
    }
  });
};

/* 删除 */
const handleDelete = (row) => {
  const ids = row.id;
  proxy.$modal.confirm(`确认删除联系人编号为"${ids}"的数据项吗？`).then(() => {
    return delContact(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

/* 表单重置 */
const resetForm = () => {
  Object.assign(form, initFormData());
  if (proxy.$refs.formRef) {
    proxy.resetForm("formRef");
  }
};

/* 提交表单 */
const submitForm = () => {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      const submitData = { ...form };
      // 将级联数组转为字符串存入 officeAddress
      if (Array.isArray(form.provinceCity)) {
          submitData.officeAddress = form.provinceCity.join(',');
      }
      // 根据选中项同步 CustomName (为了兼容新表的字符串存储)
      const targetCustomer = customerOptions.value.find(item => item.value === form.customerNo);
      if (targetCustomer) {
          submitData.customName = targetCustomer.label;
      }

      if (form.id != null) {
        updateContact(submitData).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(() => {});
      } else {
        addContact(submitData).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(() => {});
      }
    }
  });
};

onMounted(() => getList());
</script>

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

.search-card {
  border: none;
  background-color: #fff;
  margin-bottom: 5px;
  :deep(.el-card__body) {
    padding: 10px 0 20px 0;
  }
}

.mt-15 { margin-top: 15px; }

.custom-form-item, .btns-item {
  margin-bottom: 0px !important;
  display: flex !important;
  align-items: center;
  :deep(.el-form-item__label) {
    color: #333;
    font-weight: 400;
    white-space: nowrap;
    line-height: 36px;
    height: 36px;
    padding-right: 8px;
  }
  :deep(.el-form-item__content) {
    flex: 1;
    display: flex;
    align-items: center;
  }
}

.custom-form-item {
  :deep(.el-input__wrapper), :deep(.el-select__wrapper) {
    background-color: #fff;
    box-shadow: 0 0 0 1px #cbd5e1 inset !important;
    border-radius: 4px;
    height: 36px !important;
    line-height: 36px;
  }
}

.btns-item {
  margin-left: 5px;
  :deep(.el-form-item__content) {
    height: 36px;
    display: flex;
    align-items: center;
  }
}

.search-btns-group {
  display: flex;
  gap: 10px;
  align-items: center;

  .el-button {
    height: 36px !important;
    padding: 0 15px;
    vertical-align: middle;
  }

  .btn-search, .btn-reset {
    background-color: #fff;
    border: 1px solid #dcdfe6;
    color: #606266;
    &:hover { color: #409eff; border-color: #c6e2ff; background-color: #ecf5ff; }
  }

  .btn-plus { width: 90px; background-color: #409eff; border-color: #409eff; color: #fff; font-weight: bold; }
}

.title-container {
  padding: 10px 0;
  .list-title { font-size: 15px; font-weight: 600; color: #334155; }
}

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

.custom-table {
  :deep(th.el-table__cell) { background-color: #f8fafc !important; }
}

.contact-name-text { color: #ff8c42; font-weight: 500; cursor: pointer; }

/* 新增/编辑 弹窗样式 */
.dialog-section {
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #f1f5f9;
  &.no-border { border-bottom: none; }
  .section-title {
    font-size: 14px;
    font-weight: bold;
    color: #334155;
    margin-bottom: 20px;
    padding-left: 10px;
    border-left: 4px solid #3b82f6;
  }
}

:deep(.el-radio__label) { color: #475569; }

/* ====== 详情抽屉样式 ====== */
.detail-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #e2e8f0;
  .detail-header-title {
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
  }
  .detail-close-btn {
    font-size: 20px;
    color: #94a3b8;
    cursor: pointer;
    &:hover { color: #475569; }
  }
}

.detail-body {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.detail-main {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

/* Tabs */
.detail-tabs {
  display: flex;
  gap: 0;
  border-bottom: 2px solid #e2e8f0;
  padding: 0 24px;
  .tab-item {
    padding: 12px 16px;
    font-size: 14px;
    color: #64748b;
    cursor: pointer;
    position: relative;
    &.active {
      color: #3b82f6;
      font-weight: 600;
      &::after {
        content: '';
        position: absolute;
        bottom: -2px;
        left: 0;
        right: 0;
        height: 2px;
        background-color: #3b82f6;
      }
    }
    &:hover { color: #3b82f6; }
  }
}

.detail-info-content {
  padding: 20px 24px;
}

.detail-edit-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

/* 详情区块 */
.detail-section {
  margin-bottom: 24px;
  .detail-section-title {
    font-size: 14px;
    font-weight: bold;
    color: #334155;
    margin-bottom: 16px;
    padding-left: 10px;
    border-left: 4px solid #3b82f6;
  }
}

/* 详情字段网格 */
.detail-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0;
}

.detail-field {
  display: flex;
  align-items: flex-start;
  padding: 10px 0;
  &.full-width {
    grid-column: 1 / -1;
  }
  .field-label {
    min-width: 80px;
    color: #94a3b8;
    font-size: 13px;
    flex-shrink: 0;
  }
  .field-value {
    color: #1e293b;
    font-size: 13px;
    word-break: break-all;
    &.id-text {
      color: #3b82f6;
    }
  }
}

.detail-text-block {
  color: #64748b;
  font-size: 13px;
  line-height: 1.8;
  min-height: 20px;
}

/* 右侧管理信息栏 */
.detail-sidebar {
  width: 300px;
  flex-shrink: 0;
  border-left: 1px solid #e2e8f0;
  padding: 20px;
  background-color: #fafbfc;
  overflow-y: auto;
  .sidebar-title {
    font-size: 14px;
    font-weight: 600;
    color: #ef4444;
    margin-bottom: 20px;
  }
  .sidebar-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 14px;
    .sidebar-label {
      color: #94a3b8;
      font-size: 13px;
      min-width: 70px;
    }
    .sidebar-value {
      color: #1e293b;
      font-size: 13px;
      text-align: right;
      white-space: nowrap;
    }
  }
}

.detail-care-content {
  padding: 20px;
}

.care-toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.care-customer-name {
  font-size: 14px;
  margin-bottom: 16px;
  color: #333;
}
.care-customer-name .required {
  color: #f56c6c;
  margin-right: 4px;
}

/* 去掉详情抽屉默认 header */
:deep(.detail-drawer .el-drawer__header) {
  display: none;
}
</style>
