<template>
  <el-dialog
      :title="mode === 'add' ? '添加登记来件' : '修改登记来件'"
      v-model="visibleProxy"
      width="80vw"
      top="5vh"
      style="margin-bottom: 0"
  >
    <el-scrollbar max-height="76vh">
      <el-form
          ref="formRef"
          :model="model"
          :label-width="150"
          class="form-layout"
          style="min-height: 66vh"
          :rules="rules"
      >
        <!-- 来源 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="来源" prop="sourcePath">
              <el-cascader
                  v-model="model.sourcePath"
                  :options="dict.sourceTableAndLevel"
                  :props="{ emitPath: true, checkStrictly: false }"
                  clearable
                  filterable
                  show-all-levels
                  style="width: 100%"
                  placeholder="请选择来源（一级/二级）"
                  :disabled="mode=== 'edit'"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="业务类别" prop="handleMethod">
              <el-select
                  v-model="model.businessTypeCode"
                  placeholder="业务类别"
                  clearable
              >
                <el-option
                    v-for="item in dict.businessType"
                    :key="item.id"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 编号 + 受理时间 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号" prop="originId">
              <el-input
                  v-model="model.originId"
                  :placeholder="model.originIdSkip ? '无' : '请输入编号'"
                  :disabled="mode === 'edit' || model.originIdSkip"
              >
                <template #append>
                  <el-checkbox
                      v-model="model.originIdSkip"
                      @change="(v) => v && (model.originId = '')"
                      :disabled="mode=== 'edit'"
                  >
                    无
                  </el-checkbox>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="登记/受理时间" prop="discoveryTime">
              <el-date-picker
                  v-model="model.discoveryTime"
                  type="datetime"
                  placeholder="请选择"
                  value-format="YYYY-MM-DDTHH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 来件人姓名 + 身份证号码 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="来件人姓名" prop="responderName">
              <el-input
                  v-model="model.responderName"
                  :placeholder="model.responderNameSkip ? '无' : '请输入来件人姓名'"
                  :disabled="model.responderNameSkip"
              >
                <template #append>
                  <el-checkbox
                      v-model="model.responderNameSkip"
                      @change="(v) => v && (model.responderName = '')"
                  >
                    无
                  </el-checkbox>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <div style="display: flex; align-items: flex-start; gap: 8px;">
              <el-form-item label="身份证号码" prop="responderIdCode" style="flex: 1; margin-bottom: 0;">
                <el-input
                    v-model="model.responderIdCode"
                    :placeholder="model.responderIdCodeSkip ? '无' : '请输入身份证号码'"
                    :disabled="model.responderIdCodeSkip"
                >
                  <template #append>
                    <el-checkbox
                        v-model="model.responderIdCodeSkip"
                        @change="(v) => v && (model.responderIdCode = '')"
                    >
                      无
                    </el-checkbox>
                  </template>
                </el-input>
              </el-form-item>

              <el-button
                  type="primary"
                  :loading="duplicateLoading"
                  :disabled="model.responderIdCodeSkip"
                  @click="onCheckDuplicate"
              >
                查重
              </el-button>
            </div>
          </el-col>
        </el-row>

        <!-- 联系电话 + 被投诉二级机构 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="responderPhone">
              <el-input
                  v-model="model.responderPhone"
                  :placeholder="model.responderPhoneSkip ? '无' : '请输入联系电话'"
                  :disabled="model.responderPhoneSkip"
              >
                <template #append>
                  <el-checkbox
                      v-model="model.responderPhoneSkip"
                      @change="(v) => v && (model.responderPhone = '')"
                  >
                    无
                  </el-checkbox>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="被投诉二级机构" prop="secondDepartId" >
              <depart-tree-select
                  v-model="model.secondDepartId"
                  :check-strictly="true"
                  @node-click="(row) => (model.secondDepartName = row.shortName)"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 来件内容 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="来件内容" prop="thingDesc">
              <el-input v-model="model.thingDesc" type="textarea" :autosize="{ minRows: 4 }" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 涉嫌问题 + 是否重复件 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="涉嫌问题" prop="involveProblemIdList">
              <el-select v-model="model.involveProblemIdList" multiple clearable style="width: 100%">
                <el-option
                    v-for="item in dict.suspectProblem"
                    :key="item.dictValue"
                    :value="item.dictValue"
                    :label="item.dictLabel"
                >
                  <!-- 复选框展示 -->
                  <el-checkbox :model-value="model.involveProblemIdList.includes(item.dictValue)">
                    {{ item.dictLabel }}
                  </el-checkbox>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否重复件" prop="repeatt">
              <el-radio-group v-model="model.repeatt" clearable>
                <el-radio v-for="item in dict.yesNo" :key="item.id" :label="item.dictValue">
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 标签 -->
        <el-row>
          <el-col :span="18">
            <el-form-item label="标签" prop="tags">
              <el-checkbox-group v-model="model.tags">
                <el-checkbox v-for="item in dict.sfssTags" :key="item.id" :label="item.dictValue">
                  {{ item.dictLabel }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 办理方式 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="办理方式" prop="handleMethod">
              <el-radio-group v-model="model.handleMethod" clearable>
                <el-radio v-for="item in dict.handleMethodType" :key="item.id" :label="item.dictValue">
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="附件" prop="thingFiles">
          <file-upload
              v-model:files="model.thingFiles"
              tips="为便于“办理单位”更全面了解问题详情，请上传相关附件，如现场督察、数字督察等相关照片、视频及其他佐证材料。"
          />
        </el-form-item>
      </el-form>
    </el-scrollbar>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visibleProxy = false" size="large">取消</el-button>
        <el-button type="primary" @click="onSubmit" size="large">
          {{ mode === 'add' ? '添加' : '修改' }}
        </el-button>
      </div>
    </template>
    <!-- 重复件提示抽屉 -->
    <el-drawer
        v-model="duplicateDrawerVisible"
        direction="rtl"
        size="40%"
        class="duplicate-drawer"
    >
      <template #header>
        <div class="drawer-header danger">
          <el-icon size="22">
            <WarningFilled />
          </el-icon>
          <div class="title-group">
            <div class="title">身份证重复件风险提醒</div>
          </div>
        </div>
      </template>

      <!-- 内容区域 -->
      <div class="drawer-body">
        <!-- 顶部风险提示 -->
        <el-alert
            type="warning"
            show-icon
            :closable="false"
            class="drawer-alert"
        >
          <template #title>
            系统检测到该身份证号可能存在重复登记记录
          </template>
        </el-alert>

        <!-- 当前身份证号高亮 -->
        <div class="id-highlight">
          当前身份证号：
          <span>{{ model.responderIdCode }}</span>
        </div>

        <!-- 无数据 -->
        <el-empty
            v-if="duplicateList.length === 0"
            description="暂无重复数据"
        />

        <!-- 重复件表格 -->
        <el-table
            v-else
            :data="duplicateList"
            stripe
            style="width: 100%"
        >
          <el-table-column
              prop="originId"
              label="编号"
              width="140"
          />
          <el-table-column
              prop="sourceTablePath"
              label="来源"
              width="180"
          />
          <el-table-column
              prop="responderName"
              label="姓名"
              width="120"
          />
          <el-table-column
              prop="responderIdCode"
              label="身份证号"
          />
          <el-table-column
              prop="discoveryTime"
              label="登记/受理时间"
              width="180"
          >
            <template #default="{ row }">
              {{
                row.discoveryTime
                    ? dayjs(row.discoveryTime).format('YYYY-MM-DD HH:mm:ss')
                    : '-'
              }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
  </el-dialog>
</template>

<script setup>
import {computed, ref, watch} from "vue";
import {maileRepeatt} from "@/api/data/complaintCollection.ts";
import { WarningFilled } from '@element-plus/icons-vue'
import dayjs from "dayjs";
import feedback from "@/utils/feedback.ts";

const props = defineProps({
  modelValue: Boolean, // 控制弹窗显示
  mode: { type: String, default: "add" }, // add | edit
  model: { type: Object, required: true }, // addForm / updateForm
  dict: { type: Object, required: true },
  rules: { type: Object, required: true },
});

const emit = defineEmits(["update:modelValue", "submit"]);

const formRef = ref();

const visibleProxy = computed({
  get: () => props.modelValue,
  set: (v) => emit("update:modelValue", v),
});
watch(
    () => visibleProxy.value,
    (v) => {
      if (v) {
        // 打开弹窗时，统一重置所有 “无” 勾选状态
        props.model.originIdSkip = false
        props.model.responderNameSkip = false
        props.model.responderIdCodeSkip = false
        props.model.responderPhoneSkip = false
      }
    }
)


// 级联选择 -> 拆字段（和你现在 addForm 的 watch 一样）
watch(
    () => props.model.sourcePath,
    (path) => {
      if (!path || path.length === 0) return;
      props.model.sourceTable = (path && path[0]) || "";
      props.model.sourceTableSubOne = (path && path[1]) || "";
    },
    { deep: true }
);


function fillFiledName() {
  const code = props.model.businessTypeCode;
  const hit = props.dict.businessType?.find(
      (d) => String(d.dictValue) === String(code)
  );
  props.model.businessTypeName = hit?.dictLabel || "";
}

async function onSubmit() {
  fillFiledName();
  // await formRef.value.validate();
  emit("submit");
}

// 查重
const duplicateDrawerVisible = ref(false)
const duplicateList = ref([])
const duplicateLoading = ref(false)
const onCheckDuplicate = async () => {
  if (!props.model.responderIdCode) return
  duplicateLoading.value = true
  duplicateList.value = []
  try {
    const body = {
      responderIdCode: props.model.responderIdCode,
    }
    const res = await maileRepeatt(body)
    const list = res?.complaintCollectionPageDTOS || []
    if (list.length > 0) {
      duplicateList.value = list
      duplicateDrawerVisible.value = true
    } else {
      feedback.msgSuccess("未发现重复登记记录");
    }
  } catch (error) {
    feedback.msgError('查重失败')
  } finally {
    duplicateLoading.value = false
  }
}


</script>

<style>
.form-layout {
  padding: 0 34px;
}

.dialog-footer {
  padding: 16px 24px 24px;
}


/* 重复件抽屉整体 */
.duplicate-drawer {
  --el-drawer-padding-primary: 20px;
}

/* 抽屉标题 */
.drawer-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #d46b08;
}

/* 内容区域 */
.drawer-body {
  padding-top: 8px;
}

/* 顶部提示 */
.drawer-alert {
  margin-bottom: 16px;
}

/* 身份证号高亮 */
.id-highlight {
  margin-bottom: 20px;
  padding: 12px 16px;
  background: #fafafa;
  border-left: 4px solid #faad14;
  font-size: 14px;
  line-height: 22px;
}

.id-highlight span {
  margin-left: 8px;
  font-weight: 600;
  color: #d4380d;
}


.drawer-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 4px 0;
}

.drawer-header.danger {
  color: #0d73ee;
}

.drawer-header .title-group {
  display: flex;
  flex-direction: column;
}

.drawer-header .title {
  font-size: 20px;
  font-weight: 600;
  line-height: 1.2;
}

.drawer-header .sub-title {
  font-size: 13px;
  color: #8c8c8c;
  margin-top: 2px;
}

</style>
