<template>
  <div class="dual-wrapper">
    <Tabs v-model="activeTab" @on-click="handleTabChange">
      <TabPane label="接收中人员" name="receiving">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="4">
              <span>姓名：</span>
              <Input v-model="filters.receiving.name" placeholder="请输入" style="width: 65%" />
            </Col>
            <Col span="4">
              <span>身份证号：</span>
              <Input v-model="filters.receiving.card_no" placeholder="请输入" style="width: 55%" />
            </Col>
            <Col span="4">
              <span>选择市：</span>
              <Select v-model="filters.receiving.city_id" clearable style="width: 55%" @on-change="handleFilterCascade('receiving', 'city', $event)">
                <Option v-for="c in cityOptions" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择区：</span>
              <Select v-model="filters.receiving.area_id" clearable style="width: 55%" @on-change="handleFilterCascade('receiving', 'area', $event)">
                <Option v-for="c in areaState.receiving.areaList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择街道：</span>
              <Select v-model="filters.receiving.street_id" clearable style="width: 55%" @on-change="handleFilterCascade('receiving', 'street', $event)">
                <Option v-for="c in areaState.receiving.streetList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择社区：</span>
              <Select v-model="filters.receiving.community_id" clearable style="width: 55%">
                <Option v-for="c in areaState.receiving.communityList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
          </Row>
          <Row type="flex" :gutter="16" class="mbt15">
            <Col span="4">
              <span>转发状态：</span>
              <Select v-model="filters.receiving.turn_status" clearable style="width: 55%">
                <Option v-for="opt in dicts.turnStatus" :key="opt.value" :value="opt.value">{{ opt.label }}</Option>
              </Select>
            </Col>
            <Col span="8" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('receiving')">搜索</Button>
              <Button @click="handleReset('receiving')">重置</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.receiving" :columns="receivingColumns" :data="tables.receiving">
          <template slot="turn_status" slot-scope="{ row }">
            <span>{{ renderTurnStatus(row.turn_status) }}</span>
          </template>
          <template slot="receivingAction" slot-scope="{ row }">
            <Button size="small" type="primary" class="mr5" @click="openForwardModal(row)" :disabled="String(row.turn_status) === '1'">转发</Button>
            <Button size="small" type="warning" class="mr5" @click="openReturnModal(row)" :disabled="String(row.turn_status) === '1'">退回</Button>
            <Button size="small" @click="openDetail(row)">详情</Button>
          </template>
        </Table>
        <Page
          class="page_style"
          :total="pagers.receiving.totalRecord"
          :current="pagers.receiving.pageNo"
          :page-size="pagers.receiving.pageSize"
          show-total
          show-sizer
          @on-change="pageChange('receiving', $event)"
          @on-page-size-change="sizeChange('receiving', $event)"
        />
      </TabPane>

      <TabPane label="被接收人员" name="received">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="4">
              <span>姓名：</span>
              <Input v-model="filters.received.name" placeholder="请输入" style="width: 65%" />
            </Col>
            <Col span="4">
              <span>身份证号：</span>
              <Input v-model="filters.received.card_no" placeholder="请输入" style="width: 55%" />
            </Col>
            <Col span="4">
              <span>选择市：</span>
              <Select v-model="filters.received.city_id" clearable style="width: 55%" @on-change="handleFilterCascade('received', 'city', $event)">
                <Option v-for="c in cityOptions" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择区：</span>
              <Select v-model="filters.received.area_id" clearable style="width: 55%" @on-change="handleFilterCascade('received', 'area', $event)">
                <Option v-for="c in areaState.received.areaList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择街道：</span>
              <Select v-model="filters.received.street_id" clearable style="width: 55%" @on-change="handleFilterCascade('received', 'street', $event)">
                <Option v-for="c in areaState.received.streetList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择社区：</span>
              <Select v-model="filters.received.community_id" clearable style="width: 55%">
                <Option v-for="c in areaState.received.communityList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
          </Row>
          <Row class="mbt15">
            <Col span="24" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('received')">搜索</Button>
              <Button @click="handleReset('received')">重置</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.received" :columns="receivedColumns" :data="tables.received" />
        <Page
          class="page_style"
          :total="pagers.received.totalRecord"
          :current="pagers.received.pageNo"
          :page-size="pagers.received.pageSize"
          show-total
          show-sizer
          @on-change="pageChange('received', $event)"
          @on-page-size-change="sizeChange('received', $event)"
        />
      </TabPane>

      <TabPane label="待接收" name="pending">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="4">
              <span>姓名：</span>
              <Input v-model="filters.pending.name" placeholder="请输入" style="width: 65%" />
            </Col>
            <Col span="4">
              <span>身份证号：</span>
              <Input v-model="filters.pending.card_no" placeholder="请输入" style="width: 55%" />
            </Col>
            <Col span="4">
              <span>选择市：</span>
              <Select v-model="filters.pending.city_id" clearable style="width: 55%" @on-change="handleFilterCascade('pending', 'city', $event)">
                <Option v-for="c in cityOptions" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择区：</span>
              <Select v-model="filters.pending.area_id" clearable style="width: 55%" @on-change="handleFilterCascade('pending', 'area', $event)">
                <Option v-for="c in areaState.pending.areaList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择街道：</span>
              <Select v-model="filters.pending.street_id" clearable style="width: 55%" @on-change="handleFilterCascade('pending', 'street', $event)">
                <Option v-for="c in areaState.pending.streetList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择社区：</span>
              <Select v-model="filters.pending.community_id" clearable style="width: 55%">
                <Option v-for="c in areaState.pending.communityList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
          </Row>
          <Row type="flex" :gutter="16" class="mbt15">
            <Col span="4">
              <span>推送状态：</span>
              <Select v-model="filters.pending.push_status" clearable style="width: 55%">
                <Option v-for="opt in dicts.pushStatus" :key="opt.value" :value="opt.value">{{ opt.label }}</Option>
              </Select>
            </Col>
            <Col span="8" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('pending')">搜索</Button>
              <Button @click="handleReset('pending')">重置</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.pending" :columns="pendingColumns" :data="tables.pending">
          <template slot="push_status" slot-scope="{ row }">
            <span>{{ renderPushStatus(row.push_status) }}</span>
          </template>
          <template slot="pendingAction" slot-scope="{ row }">
            <Button size="small" type="primary" class="mr5" @click="openAcceptModal(row)" :disabled="String(row.push_status) !== '1'">同意</Button>
            <Button size="small" type="warning" class="mr5" @click="openRejectModal(row)" :disabled="String(row.push_status) !== '1'">拒绝</Button>
            <Button size="small" @click="openDetail(row)">详情</Button>
          </template>
        </Table>
        <Page
          class="page_style"
          :total="pagers.pending.totalRecord"
          :current="pagers.pending.pageNo"
          :page-size="pagers.pending.pageSize"
          show-total
          show-sizer
          @on-change="pageChange('pending', $event)"
          @on-page-size-change="sizeChange('pending', $event)"
        />
      </TabPane>

      <TabPane label="推送" name="push">
        <div class="search-div">
          <Row type="flex" :gutter="16" class="">
            <Col span="4">
              <span>姓名：</span>
              <Input v-model="filters.push.name" placeholder="请输入" style="width: 65%" />
            </Col>
            <Col span="4">
              <span>身份证号：</span>
              <Input v-model="filters.push.card_no" placeholder="请输入" style="width: 55%" />
            </Col>
            <Col span="4">
              <span>选择市：</span>
              <Select v-model="filters.push.city_id" clearable style="width: 55%" @on-change="handleFilterCascade('push', 'city', $event)">
                <Option v-for="c in cityOptions" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择区：</span>
              <Select v-model="filters.push.area_id" clearable style="width: 55%" @on-change="handleFilterCascade('push', 'area', $event)">
                <Option v-for="c in areaState.push.areaList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择街道：</span>
              <Select v-model="filters.push.street_id" clearable style="width: 55%" @on-change="handleFilterCascade('push', 'street', $event)">
                <Option v-for="c in areaState.push.streetList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择社区：</span>
              <Select v-model="filters.push.community_id" clearable style="width: 55%">
                <Option v-for="c in areaState.push.communityList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
          </Row>
          <Row type="flex" :gutter="16" class="mbt15">
            <Col span="4">
              <span>推送状态：</span>
              <Select v-model="filters.push.push_status" clearable style="width: 55%">
                <Option v-for="opt in dicts.pushStatus" :key="opt.value" :value="opt.value">{{ opt.label }}</Option>
              </Select>
            </Col>
            <Col span="12" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('push')">搜索</Button>
              <Button class="mr10" @click="handleReset('push')">重置</Button>
              <Button type="success" @click="openPushModal">推送</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.push" :columns="pushColumns" :data="tables.push">
          <template slot="push_status" slot-scope="{ row }">
            <span>{{ renderPushStatus(row.push_status) }}</span>
          </template>
          <template slot="pushAction" slot-scope="{ row }">
            <Poptip v-if="String(row.push_status) === '1'" confirm title="确认撤回此次推送？" transfer @on-ok="confirmRevoke(row)">
              <Button size="small" type="warning" class="mr5">撤回</Button>
            </Poptip>
            <Button size="small" @click="openDetail(row)">详情</Button>
          </template>
        </Table>
        <Page
          class="page_style"
          :total="pagers.push.totalRecord"
          :current="pagers.push.pageNo"
          :page-size="pagers.push.pageSize"
          show-total
          show-sizer
          @on-change="pageChange('push', $event)"
          @on-page-size-change="sizeChange('push', $event)"
        />
      </TabPane>

      <TabPane label="转发" name="forward">
        <div class="search-div">
          <Row type="flex" :gutter="16" class="">
            <Col span="4">
              <span>姓名：</span>
              <Input v-model="filters.forward.name" placeholder="请输入" style="width: 65%" />
            </Col>
            <Col span="4">
              <span>身份证号：</span>
              <Input v-model="filters.forward.card_no" placeholder="请输入" style="width: 55%" />
            </Col>
            <Col span="4">
              <span>选择市：</span>
              <Select v-model="filters.forward.city_id" clearable style="width: 55%" @on-change="handleFilterCascade('forward', 'city', $event)">
                <Option v-for="c in cityOptions" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择区：</span>
              <Select v-model="filters.forward.area_id" clearable style="width: 55%" @on-change="handleFilterCascade('forward', 'area', $event)">
                <Option v-for="c in areaState.forward.areaList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择街道：</span>
              <Select v-model="filters.forward.street_id" clearable style="width: 55%" @on-change="handleFilterCascade('forward', 'street', $event)">
                <Option v-for="c in areaState.forward.streetList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
            <Col span="4">
              <span>选择社区：</span>
              <Select v-model="filters.forward.community_id" clearable style="width: 55%">
                <Option v-for="c in areaState.forward.communityList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
              </Select>
            </Col>
          </Row>
          <Row type="flex" :gutter="16" class="mbt15">
            <Col span="4">
              <span>推送状态：</span>
              <Select v-model="filters.forward.push_status" clearable style="width: 55%">
                <Option v-for="opt in dicts.pushStatus" :key="opt.value" :value="opt.value">{{ opt.label }}</Option>
              </Select>
            </Col>
            <Col span="12" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('forward')">搜索</Button>
              <Button @click="handleReset('forward')">重置</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.forward" :columns="forwardColumns" :data="tables.forward">
          <template slot="push_status" slot-scope="{ row }">
            <span>{{ renderPushStatus(row.push_status) }}</span>
          </template>
          <template slot="forwardAction" slot-scope="{ row }">
            <Poptip v-if="String(row.push_status) === '1'" confirm title="确认撤回此次转发？" transfer @on-ok="confirmRevoke(row)">
              <Button size="small" type="warning" class="mr5">撤回</Button>
            </Poptip>
            <Button size="small" @click="openDetail(row)">详情</Button>
          </template>
        </Table>
        <Page
          class="page_style"
          :total="pagers.forward.totalRecord"
          :current="pagers.forward.pageNo"
          :page-size="pagers.forward.pageSize"
          show-total
          show-sizer
          @on-change="pageChange('forward', $event)"
          @on-page-size-change="sizeChange('forward', $event)"
        />
      </TabPane>
    </Tabs>

    <!-- 推送弹窗 -->
    <Modal v-model="pushModal.visible" title="人员推送" width="900" :mask-closable="false">
      <div class="modal-block">
        <h4 class="section-title">人员选择</h4>
        <div class="modal-search mb10">
          <Input v-model="pushModal.personFilters.name" placeholder="姓名" style="width: 180px" class="mr10" />
          <Input v-model="pushModal.personFilters.card_no" placeholder="身份证号" style="width: 200px" class="mr10" />
          <Button type="primary" @click="loadPushPersonList(1)">搜索</Button>
        </div>
        <Table
          border
          size="small"
          :loading="pushModal.personLoading"
          :columns="pushPersonColumns"
          :data="pushModal.personData"
          highlight-row
          :row-class-name="pushPersonRowClass"
          @on-row-click="selectPushPerson"
        />
        <Page
          class="page_style"
          size="small"
          :total="pushModal.personPager.totalRecord"
          :current="pushModal.personPager.pageNo"
          :page-size="pushModal.personPager.pageSize"
          show-total
          show-sizer
          @on-change="onPushPersonPage"
          @on-page-size-change="onPushPersonSize"
        />
      </div>
      <div class="modal-block">
        <h4 class="section-title">推送信息</h4>
        <Form :label-width="120">
          <FormItem label="选择人员">
            <span>{{ pushModal.selectedPerson ? pushModal.selectedPerson.name : '请选择人员' }}</span>
          </FormItem>
          <FormItem label="推送市（州）" required>
            <Select v-model="pushModal.form.recvie_city_id" placeholder="请选择" disabled>
              <Option v-for="c in cityOptions" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="推送县（市、区）" required>
            <Select v-model="pushModal.form.recvie_area_id" placeholder="请选择" @on-change="handlePushModalCascade('area', $event)">
              <Option v-for="c in pushModal.areaState.areaList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="推送街道（乡镇）" required>
            <Select v-model="pushModal.form.recvie_street_id" placeholder="请选择" @on-change="handlePushModalCascade('street', $event)">
              <Option v-for="c in pushModal.areaState.streetList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
            </Select>
          </FormItem>
          <FormItem label="推送原因" required>
            <Input type="textarea" :rows="3" v-model="pushModal.form.push_reason" placeholder="请输入推送原因" />
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button @click="pushModal.visible=false">取消</Button>
        <Button type="primary" :loading="pushModal.submitting" @click="submitPush">保存</Button>
      </div>
    </Modal>

    <!-- 转发弹窗 -->
    <Modal v-model="forwardModal.visible" title="人员转发" width="600" :mask-closable="false">
      <Form :label-width="140">
        <FormItem label="姓名">
          <span>{{ forwardModal.record.name || '-' }}</span>
        </FormItem>
        <FormItem label="身份证号">
          <span>{{ forwardModal.record.card_no || '-' }}</span>
        </FormItem>
        <FormItem label="转发市（州）" required>
          <Select v-model="forwardModal.form.recvie_city_id" placeholder="请选择" disabled>
            <Option v-for="c in cityOptions" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="转发县（市、区）" required>
          <Select v-model="forwardModal.form.recvie_area_id" placeholder="请选择" @on-change="handleForwardModalCascade('area', $event)">
            <Option v-for="c in forwardModal.areaState.areaList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="转发街道（乡镇）" required>
          <Select v-model="forwardModal.form.recvie_street_id" placeholder="请选择" @on-change="handleForwardModalCascade('street', $event)">
            <Option v-for="c in forwardModal.areaState.streetList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="转发原因" required>
          <Input type="textarea" :rows="3" v-model="forwardModal.form.push_reason" placeholder="请输入转发原因" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="forwardModal.visible=false">取消</Button>
        <Button type="primary" :loading="forwardModal.submitting" @click="submitForward">保存</Button>
      </div>
    </Modal>

    <!-- 同意接收 -->
    <Modal v-model="acceptModal.visible" title="确认接收" width="600" :mask-closable="false">
      <Form :label-width="130">
        <FormItem label="推送人员">
          <span>{{ acceptModal.record.person_name || acceptModal.record.name || '-' }}</span>
        </FormItem>
        <FormItem label="归属区域">
          <span>{{ formatBelongArea(acceptModal.record) }}</span>
        </FormItem>
        <FormItem label="推送区域">
          <span>{{ formatArea(acceptModal.record.push_city_name, acceptModal.record.push_area_name, acceptModal.record.push_street_name, acceptModal.record.push_community_name) }}</span>
        </FormItem>
        <FormItem label="接收区域">
          <span>{{ formatRecvieArea(acceptModal.record) }}</span>
        </FormItem>
        <FormItem label="推送原因">
          <span>{{ acceptModal.record.push_reason || '-' }}</span>
        </FormItem>
        <FormItem label="选择社区" required>
          <Select v-model="acceptModal.community_id" placeholder="请选择">
            <Option v-for="c in acceptModal.communityList" :key="c.parent_id" :value="c.parent_id">{{ c.name }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="acceptModal.visible=false">取消</Button>
        <Button type="primary" :loading="acceptModal.submitting" @click="confirmAccept">确认接收</Button>
      </div>
    </Modal>

    <!-- 拒绝弹窗 -->
    <Modal v-model="rejectModal.visible" title="拒绝原因" width="520" :mask-closable="false">
      <Input type="textarea" :rows="4" v-model="rejectModal.reason" placeholder="请输入拒绝原因" />
      <div slot="footer">
        <Button @click="rejectModal.visible=false">取消</Button>
        <Button type="primary" :loading="rejectModal.submitting" @click="confirmReject">提交</Button>
      </div>
    </Modal>

    <!-- 退回弹窗 -->
    <Modal v-model="returnModal.visible" title="退回原因" width="520" :mask-closable="false">
      <div>
        <p style="margin-bottom: 16px; color: #333; font-weight: 500;">{{ returnModal.tipText }}</p>
        <Input type="textarea" :rows="4" v-model="returnModal.reason" placeholder="请输入退回原因（必填）" />
      </div>
      <div slot="footer">
        <Button @click="returnModal.visible=false">取消</Button>
        <Button type="primary" :loading="returnModal.submitting" @click="confirmReturn">确认退回</Button>
      </div>
    </Modal>

    <!-- 详情 -->
    <Modal v-model="detailModal.visible" title="推送详情" width="720">
      <Spin fix v-if="detailModal.loading"></Spin>
      <div v-else>
        <Row :gutter="16">
          <Col span="12"><p><strong>姓名：</strong>{{ detailModal.data.person_name || detailModal.data.name || '-' }}</p></Col>
          <Col span="12"><p><strong>身份证号：</strong>{{ detailModal.data.card_no || '-' }}</p></Col>
          <Col span="12"><p><strong>推送状态：</strong>{{ renderPushStatus(detailModal.data.push_status) }}</p></Col>
          <Col span="12"><p><strong>推送类型：</strong>{{ detailModal.data.push_type === '1' ? '转发' : '推送' }}</p></Col>
        </Row>
        <Row :gutter="16" class="mt8">
          <Col span="24"><p><strong>归属区域：</strong>{{ formatBelongArea(detailModal.data) }}</p></Col>
        </Row>
        <Row :gutter="16" class="mt8">
          <Col span="24"><p><strong>推送区域：</strong>{{ formatArea(detailModal.data.push_city_name, detailModal.data.push_area_name, detailModal.data.push_street_name, detailModal.data.push_community_name) }}</p></Col>
        </Row>
        <Row :gutter="16" class="mt8">
          <Col span="24"><p><strong>接收区域：</strong>{{ formatArea(detailModal.data.recvie_city_name, detailModal.data.recvie_area_name, detailModal.data.recvie_street_name, detailModal.data.recvie_community_name) }}</p></Col>
        </Row>
        <Row :gutter="16" class="mt8">
          <Col span="12"><p><strong>推送时间：</strong>{{ formatDateTime(detailModal.data.push_time) }}</p></Col>
          <Col span="12"><p><strong>推送人：</strong>{{ detailModal.data.push_user_name || '-' }}</p></Col>
        </Row>
        <Row :gutter="16" class="mt8" v-if="detailModal.data.audit_time || detailModal.data.audit_user_name">
          <Col span="12" v-if="detailModal.data.audit_time">
            <p><strong>审核时间：</strong>{{ formatDateTime(detailModal.data.audit_time) }}</p>
          </Col>
          <Col span="12" v-if="detailModal.data.audit_user_name">
            <p><strong>审核人：</strong>{{ detailModal.data.audit_user_name }}</p>
          </Col>
        </Row>
        <Row :gutter="16" class="mt8" v-if="detailModal.data.return_time || detailModal.data.return_user_name">
          <Col span="12" v-if="detailModal.data.return_time">
            <p><strong>退回时间：</strong>{{ formatDateTime(detailModal.data.return_time) }}</p>
          </Col>
          <Col span="12" v-if="detailModal.data.return_user_name">
            <p><strong>退回人：</strong>{{ detailModal.data.return_user_name }}</p>
          </Col>
        </Row>
        <Row class="mt8">
          <Col span="24"><p><strong>推送原因：</strong>{{ detailModal.data.push_reason || '-' }}</p></Col>
        </Row>
        <Row class="mt8" v-if="detailModal.data.reject_reason">
          <Col span="24"><p><strong>拒绝原因：</strong>{{ detailModal.data.reject_reason }}</p></Col>
        </Row>
        <Row class="mt8" v-if="detailModal.data.return_time || detailModal.data.return_user_name || detailModal.data.return_reason">
          <Col span="24"><p><strong>退回原因：</strong>{{ detailModal.data.return_reason || '-' }}</p></Col>
        </Row>
      </div>
      <div slot="footer">
        <Button type="primary" @click="detailModal.visible=false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  getDualPushList,
  getDualForwardList,
  getDualPendingList,
  getDualReceivingList,
  getDualReceivedList,
  getDualPersonOptions,
  saveDualPush,
  revokeDualPush,
  acceptDualPush,
  rejectDualPush,
  returnDualPerson,
  getDualDetail,
  selectCurrentUserInfo
} from '@/api/key-person'
import { selectCityList } from '@/api/contradiction'
import { getDictList } from '@/api/common'

const buildFilters = {
  receiving: () => ({ name: '', card_no: '', city_id: '', area_id: '', street_id: '', community_id: '', turn_status: '' }),
  received: () => ({ name: '', card_no: '', city_id: '', area_id: '', street_id: '', community_id: '' }),
  pending: () => ({ name: '', card_no: '', city_id: '', area_id: '', street_id: '', community_id: '', push_status: '' }),
  push: () => ({ name: '', card_no: '', city_id: '', area_id: '', street_id: '', community_id: '', push_status: '' }),
  forward: () => ({ name: '', card_no: '', city_id: '', area_id: '', street_id: '', community_id: '', push_status: '' })
}

// 身份证号统一转码、规整（去除所有空白并大写），避免查询、筛选不生效
function normalizeCardNo (val) {
  if (!val) return ''
  const s = String(val).replace(/\s+/g, '').trim()
  if (!s) return ''
  return s.toUpperCase()
}

export default {
  name: 'key-person-dual-index',
  props: {
    category: { type: String, default: '' }
  },
  data () {
    return {
      activeTab: 'receiving',
      cityOptions: [],
      dicts: {
        pushStatus: [],
        pushStatusMap: {},
        turnStatus: [],
        turnStatusMap: {}
      },
      filters: {
        receiving: buildFilters.receiving(),
        received: buildFilters.received(),
        pending: buildFilters.pending(),
        push: buildFilters.push(),
        forward: buildFilters.forward()
      },
      areaState: {
        receiving: { areaList: [], streetList: [], communityList: [] },
        received: { areaList: [], streetList: [], communityList: [] },
        pending: { areaList: [], streetList: [], communityList: [] },
        push: { areaList: [], streetList: [], communityList: [] },
        forward: { areaList: [], streetList: [], communityList: [] }
      },
      tables: {
        receiving: [],
        received: [],
        pending: [],
        push: [],
        forward: []
      },
      loading: {
        receiving: false,
        received: false,
        pending: false,
        push: false,
        forward: false
      },
      pagers: {
        receiving: { pageNo: 1, pageSize: 10, totalRecord: 0 },
        received: { pageNo: 1, pageSize: 10, totalRecord: 0 },
        pending: { pageNo: 1, pageSize: 10, totalRecord: 0 },
        push: { pageNo: 1, pageSize: 10, totalRecord: 0 },
        forward: { pageNo: 1, pageSize: 10, totalRecord: 0 }
      },
      pushModal: {
        visible: false,
        submitting: false,
        personLoading: false,
        personData: [],
        personFilters: { name: '', card_no: '' },
        personPager: { pageNo: 1, pageSize: 10, totalRecord: 0 },
        selectedPerson: null,
        form: {
          recvie_city_id: '',
          recvie_area_id: '',
          recvie_street_id: '',
          recvie_community_id: '',
          recvie_region: '',
          push_reason: ''
        },
        areaState: { areaList: [], streetList: [], communityList: [] }
      },
      forwardModal: {
        visible: false,
        submitting: false,
        record: {},
        form: {
          key_person_id: '',
          sys_type: '',
          recvie_city_id: '',
          recvie_area_id: '',
          recvie_street_id: '',
          recvie_community_id: '',
          recvie_region: '',
          push_reason: '',
          push_type: '1'
        },
        areaState: { areaList: [], streetList: [], communityList: [] }
      },
      acceptModal: {
        visible: false,
        record: {},
        communityList: [],
        community_id: '',
        submitting: false,
        form: {
          recvie_city_id: '',
          recvie_area_id: '',
          recvie_street_id: ''
        },
        areaState: { areaList: [], streetList: [] }
      },
      rejectModal: {
        visible: false,
        record: {},
        reason: '',
        submitting: false
      },
      returnModal: {
        visible: false,
        record: {},
        reason: '',
        tipText: '',
        submitting: false
      },
      detailModal: {
        visible: false,
        data: {},
        loading: false
      },
      receivingColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '市（州）', key: 'city_name', align: 'center' },
        { title: '县（市、区）', key: 'area_name', align: 'center' },
        { title: '街道（乡镇）', key: 'street_name', align: 'center' },
        { title: '社区（村）', key: 'community_name', align: 'center' },
        { title: '姓名', key: 'name', align: 'center' },
        { title: '身份证号', key: 'card_no', align: 'center', width: 200 },
        { title: '转发状态', slot: 'turn_status', align: 'center', width: 120 },
        { title: '操作', slot: 'receivingAction', align: 'center', width: 220, fixed: 'right' }
      ],
      receivedColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '接收市（州）', key: 'recvie_city_name', align: 'center' },
        { title: '接收县（市、区）', key: 'recvie_area_name', align: 'center' },
        { title: '接收街道（乡镇）', key: 'recvie_street_name', align: 'center' },
        { title: '接收社区（村）', key: 'recvie_community_name', align: 'center' },
        { title: '姓名', key: 'name', align: 'center' },
        { title: '身份证号', key: 'card_no', align: 'center', width: 200 }
      ],
      pendingColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '推送市（州）', key: 'push_city_name', align: 'center' },
        { title: '推送县（市、区）', key: 'push_area_name', align: 'center' },
        { title: '推送街道（乡镇）', key: 'push_street_name', align: 'center' },
        { title: '推送社区（村）', key: 'push_community_name', align: 'center' },
        { title: '姓名', key: 'name', align: 'center' },
        { title: '身份证号', key: 'card_no', align: 'center', width: 200 },
        { title: '推送状态', slot: 'push_status', align: 'center', width: 120 },
        { title: '操作', slot: 'pendingAction', align: 'center', width: 220, fixed: 'right' }
      ],
      pushColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '推送市（州）', key: 'recvie_city_name', align: 'center' },
        { title: '推送县（市、区）', key: 'recvie_area_name', align: 'center' },
        { title: '推送街道（乡镇）', key: 'recvie_street_name', align: 'center' },
        { title: '推送社区（村）', key: 'recvie_community_name', align: 'center' },
        { title: '姓名', key: 'name', align: 'center' },
        { title: '身份证号', key: 'card_no', align: 'center', width: 200 },
        { title: '推送状态', slot: 'push_status', align: 'center', width: 120 },
        { title: '操作', slot: 'pushAction', align: 'center', width: 160, fixed: 'right' }
      ],
      forwardColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '推送市（州）', key: 'recvie_city_name', align: 'center' },
        { title: '推送县（市、区）', key: 'recvie_area_name', align: 'center' },
        { title: '推送街道（乡镇）', key: 'recvie_street_name', align: 'center' },
        { title: '推送社区（村）', key: 'recvie_community_name', align: 'center' },
        { title: '姓名', key: 'name', align: 'center' },
        { title: '身份证号', key: 'card_no', align: 'center', width: 200 },
        { title: '推送状态', slot: 'push_status', align: 'center', width: 120 },
        { title: '操作', slot: 'forwardAction', align: 'center', width: 160, fixed: 'right' }
      ],
      pushPersonColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '姓名', key: 'name', align: 'center' },
        { title: '身份证号', key: 'card_no', align: 'center' },
        { title: '街道', key: 'street_name', align: 'center' },
        { title: '社区', key: 'community_name', align: 'center' }
      ]
    }
  },
  computed: {
    currentCategory () {
      const route = this.$route || {}
      const q = route.query || {}
      return String(this.category || q.category || q.rating_dict_type || '2')
    }
  },
  watch: {
    category () {
      this.resetAll()
    },
    '$route.query.category' () {
      this.resetAll()
    }
  },
  created () {
    this.loadDicts()
    this.loadCityOptions()
    this.fetchList(this.activeTab)
  },
  methods: {
    loadDicts () {
      getDictList({ type: 'push_status' }).then(res => {
        if (res.data && res.data.errcode === 0) {
          const results = res.data.data && res.data.data.results ? res.data.data.results : []
          this.dicts.pushStatus = results.map(it => ({ label: it.label || it.name, value: it.value || it.dictValue }))
          const map = {}
          this.dicts.pushStatus.forEach(it => { map[it.value] = it.label })
          this.dicts.pushStatusMap = map
        }
      })
      getDictList({ type: 'turn_status' }).then(res => {
        if (res.data && res.data.errcode === 0) {
          const results = res.data.data && res.data.data.results ? res.data.data.results : []
          this.dicts.turnStatus = results.map(it => ({ label: it.label || it.name, value: it.value || it.dictValue }))
          const map = {}
          this.dicts.turnStatus.forEach(it => { map[it.value] = it.label })
          this.dicts.turnStatusMap = map
        }
      })
    },
    async loadCityOptions () {
      const ret = await selectCityList({})
      if (ret && ret.data && ret.data.errcode === 0) {
        this.cityOptions = ret.data.data || []
      }
    },
    handleTabChange (name) {
      this.activeTab = name
      this.fetchList(name)
    },
    fetchList (tab) {
      const apiMap = {
        receiving: getDualReceivingList,
        received: getDualReceivedList,
        pending: getDualPendingList,
        push: getDualPushList,
        forward: getDualForwardList
      }
      const api = apiMap[tab]
      if (!api) return
      this.loading[tab] = true
      // 统一处理身份证号（空白 -> 删除，末位 X -> 大写），避免查询/筛选失败
      const rawFilters = this.filters[tab] || {}
      const normalizedCardNo = normalizeCardNo(rawFilters.card_no)
      const params = Object.assign(
        {},
        rawFilters,
        { card_no: normalizedCardNo, cardNo: normalizedCardNo },
        { sys_type: this.currentCategory }
      )
      const payload = Object.assign({}, this.pagers[tab], { params })
      api(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          const data = ret.data.data || {}
          this.tables[tab] = data.results || []
          this.pagers[tab].totalRecord = data.totalRecord || 0
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      }).finally(() => { this.loading[tab] = false })
    },
    handleSearch (tab) {
      this.pagers[tab].pageNo = 1
      this.fetchList(tab)
    },
    handleReset (tab) {
      this.filters[tab] = buildFilters[tab]()
      if (this.areaState[tab]) {
        this.areaState[tab].areaList = []
        this.areaState[tab].streetList = []
        this.areaState[tab].communityList = []
      }
      this.pagers[tab].pageNo = 1
      this.fetchList(tab)
    },
    pageChange (tab, pageNo) {
      this.pagers[tab].pageNo = pageNo
      this.fetchList(tab)
    },
    sizeChange (tab, size) {
      this.pagers[tab].pageSize = size
      this.pagers[tab].pageNo = 1
      this.fetchList(tab)
    },
    handleFilterCascade (tab, level, value) {
      const target = this.areaState[tab]
      if (!target) return
      const filter = this.filters[tab]
      if (level === 'city') {
        filter.city_id = value
        filter.area_id = ''
        filter.street_id = ''
        filter.community_id = ''
        target.areaList = []
        target.streetList = []
        target.communityList = []
        if (!value) return
        selectCityList({ parent_id: value }).then(res => {
          target.areaList = (res.data && res.data.data) || []
        })
      } else if (level === 'area') {
        filter.area_id = value
        filter.street_id = ''
        filter.community_id = ''
        target.streetList = []
        target.communityList = []
        if (!value) return
        selectCityList({ parent_id: value }).then(res => {
          target.streetList = (res.data && res.data.data) || []
        })
      } else if (level === 'street') {
        filter.street_id = value
        filter.community_id = ''
        target.communityList = []
        if (!value) return
        selectCityList({ parent_id: value }).then(res => {
          target.communityList = (res.data && res.data.data) || []
        })
      }
    },
    async openPushModal () {
      this.pushModal.visible = true
      this.pushModal.submitting = false
      this.pushModal.selectedPerson = null
      this.pushModal.personFilters = { name: '', card_no: '' }
      this.pushModal.personPager = { pageNo: 1, pageSize: 10, totalRecord: 0 }
      // 获取当前登录人的城市ID
      let currentCityId = ''
      try {
        const ret = await selectCurrentUserInfo({})
        if (ret && ret.data && ret.data.errcode === 0) {
          const userData = ret.data.data || {}
          const user = userData._user || {}
          currentCityId = user.parent_id || ''
          console.log('当前用户信息', userData)
        }
      } catch (error) {
        console.error('获取当前用户信息失败:', error)
        this.$Notice.error({ title: '获取用户信息失败', desc: '请稍后重试' })
      }
      this.pushModal.form = {
        recvie_city_id: currentCityId,
        recvie_area_id: '',
        recvie_street_id: '',
        recvie_community_id: '',
        recvie_region: '',
        push_reason: ''
      }
      this.pushModal.areaState = { areaList: [], streetList: [], communityList: [] }
      // 如果设置了城市ID，自动加载区列表
      if (currentCityId) {
        await this.handlePushModalCascade('city', currentCityId)
      }
      this.loadPushPersonList(1)
    },
    loadPushPersonList (pageNo) {
      if (pageNo !== undefined && pageNo !== null) {
        this.pushModal.personPager.pageNo = pageNo
      }
      const normalizedCardNo = normalizeCardNo(this.pushModal.personFilters.card_no)
      const payload = {
        pageNo: this.pushModal.personPager.pageNo,
        pageSize: this.pushModal.personPager.pageSize,
        params: Object.assign(
          {},
          this.pushModal.personFilters,
          { card_no: normalizedCardNo, cardNo: normalizedCardNo },
          { sys_type: this.currentCategory }
        )
      }
      this.pushModal.personLoading = true
      getDualPersonOptions(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          const data = ret.data.data || {}
          this.pushModal.personData = data.results || []
          // 同步后端返回的分页信息，参考 index2.vue 的实现方式
          this.pushModal.personPager.totalRecord = data.totalRecord || 0
          if (data.pageNo !== undefined && data.pageNo !== null) {
            this.pushModal.personPager.pageNo = data.pageNo
          }
          if (data.pageSize !== undefined && data.pageSize !== null) {
            this.pushModal.personPager.pageSize = data.pageSize
          }
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      }).finally(() => { this.pushModal.personLoading = false })
    },
    onPushPersonPage (pageNo) {
      this.loadPushPersonList(pageNo)
    },
    onPushPersonSize (size) {
      this.pushModal.personPager.pageSize = size
      this.loadPushPersonList(1)
    },
    selectPushPerson (row) {
      this.pushModal.selectedPerson = row
    },
    pushPersonRowClass (row) {
      return (this.pushModal.selectedPerson && this.pushModal.selectedPerson.key_person_id === row.key_person_id) ? 'row-selected' : ''
    },
    handlePushModalCascade (level, value) {
      if (level === 'city') {
        this.pushModal.form.recvie_city_id = value
        this.pushModal.form.recvie_area_id = ''
        this.pushModal.form.recvie_street_id = ''
        this.pushModal.form.recvie_community_id = ''
        this.pushModal.areaState.areaList = []
        this.pushModal.areaState.streetList = []
        this.pushModal.areaState.communityList = []
        if (!value) return Promise.resolve()
        return selectCityList({ parent_id: value }).then(res => {
          this.pushModal.areaState.areaList = (res.data && res.data.data) || []
        })
      } else if (level === 'area') {
        this.pushModal.form.recvie_area_id = value
        this.pushModal.form.recvie_street_id = ''
        this.pushModal.form.recvie_community_id = ''
        this.pushModal.areaState.streetList = []
        this.pushModal.areaState.communityList = []
        if (!value) return Promise.resolve()
        return selectCityList({ parent_id: value }).then(res => {
          this.pushModal.areaState.streetList = (res.data && res.data.data) || []
        })
      } else if (level === 'street') {
        this.pushModal.form.recvie_street_id = value
        this.pushModal.form.recvie_community_id = ''
        return Promise.resolve()
      }
      return Promise.resolve()
    },
    async submitPush () {
      if (!this.pushModal.selectedPerson) {
        this.$Message.warning('请选择人员')
        return
      }
      const form = this.pushModal.form
      if (!form.recvie_city_id || !form.recvie_area_id || !form.recvie_street_id) {
        this.$Message.warning('请选择完整的推送区域（市/区/街道）')
        return
      }
      if (!form.push_reason || !form.push_reason.trim()) {
        this.$Message.warning('请填写推送原因')
        return
      }
      const payload = {
        key_person_id: this.pushModal.selectedPerson.key_person_id,
        sys_type: this.currentCategory,
        push_reason: form.push_reason.trim(),
        recvie_city_id: form.recvie_city_id,
        recvie_area_id: form.recvie_area_id,
        recvie_street_id: form.recvie_street_id,
        recvie_community_id: form.recvie_community_id,
        recvie_region: form.recvie_region,
        push_type: '0'
      }
      this.pushModal.submitting = true
      saveDualPush(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('推送成功')
          this.pushModal.visible = false
          this.fetchList('push')
        } else {
          this.$Notice.error({ title: '推送失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      }).finally(() => { this.pushModal.submitting = false })
    },
    async openForwardModal (row) {
      this.forwardModal.visible = true
      this.forwardModal.record = row
      this.forwardModal.submitting = false

      // 获取当前用户的市（州）ID作为默认值
      let currentCityId = ''
      try {
        const ret = await selectCurrentUserInfo({})
        if (ret && ret.data && ret.data.errcode === 0) {
          const userData = ret.data.data || {}
          const user = userData._user || {}
          currentCityId = user.parent_id || ''
        }
      } catch (error) {
        console.error('获取当前用户信息失败:', error)
      }

      this.forwardModal.form = {
        key_person_id: row.key_person_id,
        sys_type: this.currentCategory,
        recvie_city_id: currentCityId,
        recvie_area_id: '',
        recvie_street_id: '',
        recvie_community_id: '',
        recvie_region: '',
        push_reason: '',
        push_type: '1'
      }
      this.forwardModal.areaState = { areaList: [], streetList: [], communityList: [] }

      // 如果设置了市（州）ID，自动加载县（市、区）列表
      if (currentCityId) {
        selectCityList({ parent_id: currentCityId }).then(res => {
          this.forwardModal.areaState.areaList = (res.data && res.data.data) || []
        })
      }
    },
    handleForwardModalCascade (level, value) {
      if (level === 'area') {
        this.forwardModal.form.recvie_area_id = value
        this.forwardModal.form.recvie_street_id = ''
        this.forwardModal.areaState.streetList = []
        if (!value) return
        selectCityList({ parent_id: value }).then(res => {
          this.forwardModal.areaState.streetList = (res.data && res.data.data) || []
        })
      } else if (level === 'street') {
        this.forwardModal.form.recvie_street_id = value
        // 社区（村）已去除，不再处理
      }
    },
    submitForward () {
      const form = this.forwardModal.form
      if (!form.recvie_city_id) {
        this.$Message.warning('转发市（州）不能为空')
        return
      }
      if (!form.recvie_area_id) {
        this.$Message.warning('请选择转发县（市、区）')
        return
      }
      if (!form.recvie_street_id) {
        this.$Message.warning('请选择转发街道（乡镇）')
        return
      }
      if (!form.push_reason || !form.push_reason.trim()) {
        this.$Message.warning('请填写转发原因')
        return
      }
      const payload = Object.assign({}, form)
      this.forwardModal.submitting = true
      saveDualPush(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('转发成功')
          this.forwardModal.visible = false
          this.fetchList('receiving')
          this.fetchList('forward')
        } else {
          this.$Notice.error({ title: '转发失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      }).finally(() => { this.forwardModal.submitting = false })
    },
    async openAcceptModal (row) {
      this.acceptModal.visible = true
      this.acceptModal.submitting = false
      this.acceptModal.community_id = ''
      this.acceptModal.communityList = []
      this.acceptModal.record = row

      // 如果数据中没有接收区域名称字段，根据ID查询
      if (!row.recvie_city_name && (row.recvie_city_id || row.recvie_area_id || row.recvie_street_id)) {
        await this.loadRecvieAreaNames(row)
      }
      // 如果数据中没有归属区域名称字段，根据ID查询
      if (!row.belong_city_name && (row.belong_city_id || row.belong_area_id || row.belong_street_id || row.belong_community_id)) {
        await this.loadBelongAreaNames(row)
      }
      // 获取当前登录用户信息
      const userInfo = this.$store.state.user.severUserInfo || {}
      let streetId = ''

      // 根据用户层级获取街道ID
      if (userInfo.type === '4') {
        // 层级4（街道），code就是街道ID
        streetId = userInfo.code || userInfo.street_id || ''
      } else if (userInfo.type === '5') {
        // 层级5（社区），从parentIds中解析街道ID
        const parentIdsStr = userInfo.parentIds || userInfo.parent_ids || ''
        if (parentIdsStr) {
          const parentIdsArray = parentIdsStr.split(',')
          // parentIds: "0,220000000000,220100000000,220102000000,220102001000" -> 街道码在索引4
          streetId = parentIdsArray[4] || ''
        }
      } else if (userInfo.street_id) {
        // 如果有直接的street_id字段
        streetId = userInfo.street_id
      }

      // 如果从用户信息中获取不到街道ID，尝试从记录中获取接收街道ID
      if (!streetId) {
        streetId = row.recvie_street_id || ''
      }

      // 如果有街道ID，加载社区列表
      if (streetId) {
        selectCityList({ parent_id: streetId }).then(res => {
          if (res.data && res.data.errcode === 0) {
            this.acceptModal.communityList = (res.data.data) || []
          }
        }).catch(err => {
          console.error('加载社区列表失败:', err)
          this.acceptModal.communityList = []
        })
      } else {
        // 如果还是没有街道ID，尝试从详情中获取
        const recordId = row.id || row.dual_id
        if (!recordId) {
          console.error('记录ID不存在，无法加载社区列表', row)
          this.$Message.warning('记录ID不存在，无法加载社区列表')
          return
        }
        getDualDetail({ id: recordId }).then(ret => {
          if (ret.data && ret.data.errcode === 0) {
            this.acceptModal.record = ret.data.data || row
            // 尝试从记录中获取接收街道ID
            const recordStreetId = this.acceptModal.record.recvie_street_id
            if (recordStreetId) {
              selectCityList({ parent_id: recordStreetId }).then(res => {
                if (res.data && res.data.errcode === 0) {
                  this.acceptModal.communityList = (res.data.data) || []
                }
              }).catch(err => {
                console.error('加载社区列表失败:', err)
                this.acceptModal.communityList = []
              })
            } else {
              this.$Message.warning('无法获取街道信息，请稍后重试')
            }
          }
        }).catch(err => {
          console.error('获取详情失败:', err)
          this.$Message.error('获取详情失败，请稍后重试')
        })
      }
    },
    confirmAccept () {
      if (!this.acceptModal.community_id) {
        this.$Message.warning('请选择社区')
        return
      }
      if (!this.acceptModal.record.id) {
        this.$Message.error('记录ID不存在，无法接收')
        return
      }
      this.acceptModal.submitting = true
      acceptDualPush({ id: this.acceptModal.record.id, recvie_community_id: this.acceptModal.community_id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('接收成功')
          this.acceptModal.visible = false
          this.fetchList('pending')
          this.fetchList('receiving')
        } else {
          this.$Notice.error({ title: '接收失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      }).finally(() => { this.acceptModal.submitting = false })
    },
    openRejectModal (row) {
      this.rejectModal.visible = true
      this.rejectModal.record = row
      this.rejectModal.reason = ''
      this.rejectModal.submitting = false
    },
    confirmReject () {
      if (!this.rejectModal.reason) {
        this.$Message.warning('请输入拒绝原因')
        return
      }
      if (!this.rejectModal.record.id) {
        this.$Message.error('记录ID不存在，无法拒绝')
        return
      }
      this.rejectModal.submitting = true
      rejectDualPush({ id: this.rejectModal.record.id, reject_reason: this.rejectModal.reason }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('操作成功')
          this.rejectModal.visible = false
          this.fetchList('pending')
          this.fetchList('receiving')
        } else {
          this.$Notice.error({ title: '操作失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      }).finally(() => { this.rejectModal.submitting = false })
    },
    openReturnModal (row) {
      this.returnModal.visible = true
      this.returnModal.record = row
      this.returnModal.reason = ''
      this.returnModal.submitting = false
      // 设置确认退回的提示词
      const area = this.formatArea(row.belong_city_name, row.belong_area_name, row.belong_street_name, row.belong_community_name)
      this.returnModal.tipText = area === '-' ? '确认退回至归属地？' : `退回后，此人将退回至归属地 ${area}`
    },
    confirmReturn () {
      if (!this.returnModal.reason || !this.returnModal.reason.trim()) {
        this.$Message.warning('请输入退回原因')
        return
      }
      if (!this.returnModal.record.dual_person_id) {
        this.$Message.error('记录ID不存在，无法退回')
        return
      }
      this.returnModal.submitting = true
      const payload = {
        dual_person_id: this.returnModal.record.dual_person_id,
        return_reason: this.returnModal.reason.trim()
      }
      returnDualPerson(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('退回成功')
          this.returnModal.visible = false
          this.fetchList('receiving')
          this.fetchList('pending')
        } else {
          this.$Notice.error({ title: '退回失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      }).finally(() => {
        this.returnModal.submitting = false
      })
    },
    confirmRevoke (row) {
      revokeDualPush({ id: row.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('撤回成功')
          this.fetchList('push')
          this.fetchList('forward')
        } else {
          this.$Notice.error({ title: '撤回失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      })
    },
    async openDetail (row) {
      const recordId = row.id || row.dual_id
      if (!recordId) {
        console.error('记录ID不存在，无法查看详情', row)
        this.$Message.error('记录ID不存在，无法查看详情')
        return
      }
      this.detailModal.visible = true
      this.detailModal.loading = true
      this.detailModal.data = {}
      try {
        const ret = await getDualDetail({ id: recordId })
        if (ret.data && ret.data.errcode === 0) {
          this.detailModal.data = ret.data.data || {}
          // 如果数据中没有归属区域名称字段，根据ID查询
          if (!this.detailModal.data.belong_city_name && (this.detailModal.data.belong_city_id || this.detailModal.data.belong_area_id || this.detailModal.data.belong_street_id || this.detailModal.data.belong_community_id)) {
            await this.loadBelongAreaNames(this.detailModal.data)
          }
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      } catch (err) {
        console.error('获取详情失败:', err)
        this.$Notice.error({ title: '查询失败', desc: '获取详情失败，请稍后重试' })
      } finally {
        this.detailModal.loading = false
      }
    },
    renderPushStatus (value) {
      return this.dicts.pushStatusMap[value] || '-'
    },
    renderTurnStatus (value) {
      return this.dicts.turnStatusMap[value] || '-'
    },
    formatArea (city, area, street, community) {
      const list = [city, area, street, community].filter(Boolean)
      return list.length ? list.join(' / ') : '-'
    },
    async loadRecvieAreaNames (record) {
      // 根据ID查询区域名称
      const names = { city: '', area: '', street: '', community: '' }

      // 查询市名称 - 从 cityOptions 中查找
      if (record.recvie_city_id && !record.recvie_city_name) {
        try {
          const city = this.cityOptions.find(c => c.parent_id === record.recvie_city_id)
          if (city) {
            names.city = city.name
            this.$set(this.acceptModal.record, 'recvie_city_name', city.name)
          } else {
            // 如果 cityOptions 中没有，尝试查询
            const cityRes = await selectCityList({})
            if (cityRes.data && cityRes.data.errcode === 0) {
              const cityList = cityRes.data.data || []
              const foundCity = cityList.find(c => c.parent_id === record.recvie_city_id)
              if (foundCity) {
                names.city = foundCity.name
                this.$set(this.acceptModal.record, 'recvie_city_name', foundCity.name)
              }
            }
          }
        } catch (err) {
          console.error('查询市名称失败:', err)
        }
      } else if (record.recvie_city_name) {
        names.city = record.recvie_city_name
      }

      // 查询区名称
      if (record.recvie_area_id && !record.recvie_area_name && record.recvie_city_id) {
        try {
          const areaRes = await selectCityList({ parent_id: record.recvie_city_id })
          if (areaRes.data && areaRes.data.errcode === 0) {
            const areaList = areaRes.data.data || []
            const area = areaList.find(a => a.parent_id === record.recvie_area_id)
            if (area) {
              names.area = area.name
              this.$set(this.acceptModal.record, 'recvie_area_name', area.name)
            }
          }
        } catch (err) {
          console.error('查询区名称失败:', err)
        }
      } else if (record.recvie_area_name) {
        names.area = record.recvie_area_name
      }

      // 查询街道名称
      if (record.recvie_street_id && !record.recvie_street_name && record.recvie_area_id) {
        try {
          const streetRes = await selectCityList({ parent_id: record.recvie_area_id })
          if (streetRes.data && streetRes.data.errcode === 0) {
            const streetList = streetRes.data.data || []
            const street = streetList.find(s => s.parent_id === record.recvie_street_id)
            if (street) {
              names.street = street.name
              this.$set(this.acceptModal.record, 'recvie_street_name', street.name)
            }
          }
        } catch (err) {
          console.error('查询街道名称失败:', err)
        }
      } else if (record.recvie_street_name) {
        names.street = record.recvie_street_name
      }

      // 查询社区名称
      if (record.recvie_community_id && !record.recvie_community_name && record.recvie_street_id) {
        try {
          const communityRes = await selectCityList({ parent_id: record.recvie_street_id })
          if (communityRes.data && communityRes.data.errcode === 0) {
            const communityList = communityRes.data.data || []
            const community = communityList.find(c => c.parent_id === record.recvie_community_id)
            if (community) {
              names.community = community.name
              this.$set(this.acceptModal.record, 'recvie_community_name', community.name)
            }
          }
        } catch (err) {
          console.error('查询社区名称失败:', err)
        }
      } else if (record.recvie_community_name) {
        names.community = record.recvie_community_name
      }
    },
    formatRecvieArea (record) {
      if (!record) return '-'
      // 使用名称字段拼接
      return this.formatArea(record.recvie_city_name, record.recvie_area_name, record.recvie_street_name, record.recvie_community_name)
    },
    async loadBelongAreaNames (record) {
      // 根据ID查询归属区域名称
      const names = { city: '', area: '', street: '', community: '' }

      // 查询市名称 - 从 cityOptions 中查找
      if (record.belong_city_id && !record.belong_city_name) {
        try {
          const city = this.cityOptions.find(c => c.parent_id === record.belong_city_id)
          if (city) {
            names.city = city.name
            this.$set(record, 'belong_city_name', city.name)
          } else {
            // 如果 cityOptions 中没有，尝试查询
            const cityRes = await selectCityList({})
            if (cityRes.data && cityRes.data.errcode === 0) {
              const cityList = cityRes.data.data || []
              const foundCity = cityList.find(c => c.parent_id === record.belong_city_id)
              if (foundCity) {
                names.city = foundCity.name
                this.$set(record, 'belong_city_name', foundCity.name)
              }
            }
          }
        } catch (err) {
          console.error('查询归属市名称失败:', err)
        }
      } else if (record.belong_city_name) {
        names.city = record.belong_city_name
      }

      // 查询区名称
      if (record.belong_area_id && !record.belong_area_name && record.belong_city_id) {
        try {
          const areaRes = await selectCityList({ parent_id: record.belong_city_id })
          if (areaRes.data && areaRes.data.errcode === 0) {
            const areaList = areaRes.data.data || []
            const area = areaList.find(a => a.parent_id === record.belong_area_id)
            if (area) {
              names.area = area.name
              this.$set(record, 'belong_area_name', area.name)
            }
          }
        } catch (err) {
          console.error('查询归属区名称失败:', err)
        }
      } else if (record.belong_area_name) {
        names.area = record.belong_area_name
      }

      // 查询街道名称
      if (record.belong_street_id && !record.belong_street_name && record.belong_area_id) {
        try {
          const streetRes = await selectCityList({ parent_id: record.belong_area_id })
          if (streetRes.data && streetRes.data.errcode === 0) {
            const streetList = streetRes.data.data || []
            const street = streetList.find(s => s.parent_id === record.belong_street_id)
            if (street) {
              names.street = street.name
              this.$set(record, 'belong_street_name', street.name)
            }
          }
        } catch (err) {
          console.error('查询归属街道名称失败:', err)
        }
      } else if (record.belong_street_name) {
        names.street = record.belong_street_name
      }

      // 查询社区名称
      if (record.belong_community_id && !record.belong_community_name && record.belong_street_id) {
        try {
          const communityRes = await selectCityList({ parent_id: record.belong_street_id })
          if (communityRes.data && communityRes.data.errcode === 0) {
            const communityList = communityRes.data.data || []
            const community = communityList.find(c => c.parent_id === record.belong_community_id)
            if (community) {
              names.community = community.name
              this.$set(record, 'belong_community_name', community.name)
            }
          }
        } catch (err) {
          console.error('查询归属社区名称失败:', err)
        }
      } else if (record.belong_community_name) {
        names.community = record.belong_community_name
      }
    },
    formatBelongArea (record) {
      if (!record) return '-'
      // 优先使用名称字段，如果没有则使用ID查询后的名称
      return this.formatArea(record.belong_city_name, record.belong_area_name, record.belong_street_name, record.belong_community_name)
    },
    formatDateTime (val) {
      if (!val) return '-'
      const d = new Date(val)
      if (Number.isNaN(d.getTime())) {
        // 尝试解析字符串格式的时间
        const m = /^(\d{4}-\d{2}-\d{2})[ T]?(\d{2}:\d{2}:\d{2})?/.exec(String(val))
        if (m) return `${m[1]}${m[2] ? ' ' + m[2] : ' 00:00:00'}`
        return String(val)
      }
      const y = d.getFullYear()
      const mm = String(d.getMonth() + 1).padStart(2, '0')
      const dd = String(d.getDate()).padStart(2, '0')
      const HH = String(d.getHours()).padStart(2, '0')
      const MM = String(d.getMinutes()).padStart(2, '0')
      const SS = String(d.getSeconds()).padStart(2, '0')
      return `${y}-${mm}-${dd} ${HH}:${MM}:${SS}`
    },
    returnTip (row) {
      const area = this.formatArea(row.belong_city_name, row.belong_area_name, row.belong_street_name, row.belong_community_name)
      return area === '-' ? '确认退回至归属地？' : `退回后，此人将退回至归属地 ${area}`
    },
    resetAll () {
      Object.keys(this.filters).forEach(key => {
        this.filters[key] = buildFilters[key]()
        if (this.areaState[key]) {
          this.areaState[key].areaList = []
          this.areaState[key].streetList = []
          this.areaState[key].communityList = []
        }
        this.pagers[key].pageNo = 1
      })
      this.fetchList(this.activeTab)
    }
  }
}
</script>

<style scoped>
.dual-wrapper {
  padding: 10px;
}
.search-div {
  border: 1px solid #dce1e7;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #f8fbff;
}
.mbt15 {
  margin-top: 15px;
}
.mb10 {
  margin-bottom: 10px;
}
.mt8 {
  margin-top: 8px;
}
.mr5 {
  margin-right: 5px;
}
.mr10 {
  margin-right: 10px;
}
.text-right {
  text-align: right;
}
.page_style {
  margin-top: 12px;
  text-align: right;
}
.section-title {
  margin: 10px 0;
  font-weight: bold;
}
.modal-block {
  margin-bottom: 16px;
}
.row-selected td {
  background-color: #e6f7ff !important;
}
</style>
