<template>
  <div class="dialog" v-if="dialogForm">
    <div class="head_box">
      <span class="title">重点群体管理 </span>
      <div>
        <el-button type="primary" size="small" :loading="loading" @click="submit">保存</el-button>
        <el-button size="small" @click="close">关闭</el-button>
      </div>
    </div>
    <div class="form_cnt">
      <FormMessage v-model="listQuery" :formList="formData" ref="elform" :rules="rules">
        <template #qtXx>
          <el-divider content-position="left">群体信息</el-divider>
        </template>
        <template #qtGlXx>
          <el-divider content-position="left">群体管理信息</el-divider>
        </template>
        <template #spXx>
          <el-divider content-position="left">审批信息</el-divider>
          <ApprovalInfo ref="approvalInfoRef" />
        </template>
        <template #xzRy>
          <div class="btns">
            <el-button type="primary" @click="handleAddEdit('add', '')">新增</el-button>
            <el-button type="primary" @click="selectionAdd()">选择重点人员</el-button>
          </div>
          <MyTable :tableData="pageData.tableData" :tableColumn="pageData.tableColumn" :key="pageData.keyCount"
            :tableConfiger="pageData.tableConfiger" :controlsWidth="pageData.controlsWidth" @chooseData="chooseData">
            <template #ryxx="{ row }">
              <div>
                <img src="" alt="" />
                <ul>
                  <li>姓名：{{ row.rySfzh }}</li>
                  <li class="rowClass">
                    性别：
                    <DictTag :tag="false" :value="row.ryXb" :options="D_BZ_XB" />
                  </li>
                  <li class="rowClass">
                    籍贯：
                    <DictTag :tag="false" :value="row.ryJg" :options="D_BZ_XZQHDM" />
                  </li>
                  <li>身份证：{{ row.rySfzh }}</li>
                  <li>出生日期：{{ row.ryCsrq }}</li>
                  <li class="rowClass">
                    民族：
                    <DictTag :tag="false" :value="row.ryMz" :options="D_BZ_MZ" />
                  </li>
                </ul>
              </div>
              <div class="flex">
                <el-button type="primary" size="small"> 涉恐人员</el-button>
                <el-button type="primary" size="small"> 涉稳人员</el-button>
                <el-button type="primary" size="small"> 在逃人员</el-button>
              </div>
            </template>
            <template #jzxx="{ row }">
              <div class="rowClass">
                户籍地区划：
                <DictTag :tag="false" :value="row.hjdQh" :options="D_BZ_XZQHDM" />
              </div>
              <div>户籍派出所：{{ row.hjdPcsmc }}</div>
              <div>户籍地详址：{{ row.hjdXz }}</div>
            </template>
            <template #gxdw="{ row }">
              <div>管辖单位：{{ row.gxSsbmmc }}</div>
              <div class="rowClass">
                人员级别：
                <DictTag :tag="false" :value="row.zdrRyjb" :options="D_GS_ZDR_RYJB" />
              </div>
              <div>管控原因：{{ zdrLkyy }}</div>
              <div class="rowClass">
                管控状态：
                <DictTag :tag="false" :value="row.zdrBkZt" :options="D_GS_ZDR_BK_ZT" />
              </div>
            </template>
            <template #zdrCzzt="{ row }">
              <DictTag :tag="false" :value="row.zdrCzzt" :options="D_GS_ZDR_CZZT" />
            </template>
            <template #xtSjzt="{ row }">
              <div>
                {{
                  row.xtSjzt == 0 ? "注销" : row.xtSjzt == 1 ? "正常" : "封存"
                }}
              </div>
            </template>
            <template #controls="{ row, index }">
              <el-button size="small" type="primary" @click="handleAddEdit('edit', row)" link>编辑</el-button>
              <el-button size="small" type="danger" @click="deleteData(index)" link>删除</el-button>
            </template>
          </MyTable>
        </template>
        <template #bqInfo>
          <el-divider content-position="left">标签信息</el-divider>
        </template>
        <!-- 人员标签模型-->
        <template #bqList>
          <el-button @click="open('01')">选择</el-button>
          <div class="boxlist">
            <MyTable :tableData="tableDate.bqList" :tableColumn="tableDate.tableColumn"
              :tableHeight="tableDate.tableHeight" :key="tableDate.keyCount" :tableConfiger="tableDate.tableConfiger"
              :controlsWidth="tableDate.controlsWidth">
              <template #bqLb="{ row }">
                <DictTag :value="row.bqLb" :tag="false" :options="D_GS_BQ_LB" />
              </template>
              <template #bqLx="{ row }">
                <DictTag :value="row.bqLx" :tag="false" :options="D_GS_BQ_LX" />
              </template>
              <template #bqZl="{ row }">
                <DictTag :value="row.bqZl" :tag="false" :options="D_GS_BQ_ZL" />
              </template>
              <!-- 操作 -->
              <template #controls="{ row }">
                <el-link type="danger" @click="delDictItem(row.bqId)">删除</el-link>
              </template>
            </MyTable>
          </div>
        </template>

        <!-- 两群采集录入-->
        <template #lqxxList>
          <el-button @click="openDialog('01')">新增</el-button>
          <div class="boxlist">
            <MyTable :tableData="tableDate.lqxxList" :tableColumn="tableDate.tableLqColumn"
              :tableHeight="tableDate.tableHeight" :key="tableDate.keyCount" :tableConfiger="tableDate.tableConfiger"
              :controlsWidth="tableDate.controlsWidth">
              <!-- 操作 -->
              <template #controls="{ row, index }">
                <el-link type="danger" @click="delDictItem(index)">删除</el-link>
              </template>
            </MyTable>
          </div>
        </template>
      </FormMessage>
    </div>
    <!-- 列表弹窗 -->
    <DialogList :Single="false" :roleIds="roleIds" v-if="chooseShow" @chooseDate="chooseDate" :titleValue="chooseTitle"
      v-model="chooseShow" :bqLx="chooseType" bqDl="02"></DialogList>
    <addFormPeo ref="addFormDiloag" @chooseDate="addFormPeoDate" @handleEditDate="handleEditDate" />

    <selectionList :Single="false" :roleIds="selectroleId" v-if="selectionValue" @chooseDate="chooseSelectDate"
      :titleValue="chooseTitle" v-model="selectionValue">
    </selectionList>
    <!-- 列表弹窗 -->
    <TagSelectorDialog v-model="choose" ref="tagDialog" @chooseDate="handleTagSelect"
      :dic="{ D_GS_BQ_ZL, D_GS_BQ_LB, D_GS_BQ_LX }" />
  </div>
</template>

<script setup>
import FormMessage from "@/components/aboutTable/FormMessage.vue";
import MyTable from "@/components/aboutTable/MyTable.vue";
import DialogList from "./dialogList.vue";
import selectionList from "./selectionList.vue";
import addFormPeo from "./addFormPeo.vue";
import ApprovalInfo from "./approvalInfo.vue";
import TagSelectorDialog from "./TagSelectorDialogPeo.vue";
import { qcckGet, qcckPost, qcckPut } from "@/api/qcckApi.js";

import {
  ref,
  defineExpose,
  reactive,
  onMounted,
  defineEmits,
  getCurrentInstance,
  nextTick
} from "vue";
const emit = defineEmits(["updateDate"]);
const props = defineProps({
  dic: Object
});
const { proxy } = getCurrentInstance();
const {
  D_BZ_SF,
  D_GS_ZDQT_FXDJ,
  D_GS_ZDQT_LB,
  D_BZ_XB,
  D_GS_ZDR_RYJB,
  D_BZ_MZ,
  D_BZ_XZQHDM,
  D_GS_ZDR_BK_ZT,
  D_GS_ZDR_CZZT,
  D_GS_BQ_ZL,
  D_GS_BQ_LB,
  D_GS_BQ_LX
} = proxy.$dict(
  "D_BZ_SF",
  "D_GS_ZDQT_FXDJ",
  "D_GS_ZDQT_LB",
  "D_BZ_XB",
  "D_GS_ZDR_RYJB",
  "D_BZ_MZ",
  "D_BZ_XZQHDM",
  "D_GS_ZDR_BK_ZT",
  "D_GS_ZDR_CZZT",
  "D_GS_BQ_ZL",
  "D_GS_BQ_LB",
  "D_GS_BQ_LX"
); //获取字典数据
const dialogTitle = ref("新增信息"); //弹窗标题
const tagDialog = ref();

const roleIds = ref([]); //选择角色
const selectroleId = ref([]); //选择角色
const approvalInfoRef = ref(null);

const dialogForm = ref(false); //弹窗
const formRef = ref();
const activeName = ref("first");
const formData = ref([
  { prop: "qtXx", type: "slot", width: "100%" },
  { label: "群体名称", prop: "qtMc", type: "input" },
  { label: "群体别名", prop: "qtBm", type: "input" },
  { label: "群体简称", prop: "qtJc", type: "input" },
  { label: "群体类别", prop: "qtLb", type: "select", options: D_GS_ZDQT_LB },
  { label: "成立时间", prop: "qtClsj", type: "date", lx: "datetime" },
  { label: "风险等级", prop: "qtFxdj", type: "select", options: D_GS_ZDQT_FXDJ },
  { label: "背景资料", prop: "qtBjzl", type: "input" },
  { label: "两群采集录入", prop: "lqxxList", type: "slot", width: "100%" },
  { label: "", prop: "qtGlXx", type: "slot", width: "100%" },
  { label: "管辖单位", prop: "gxSsdwmc", type: "input" },
  { label: "联系人", prop: "gkMjXm", type: "input" },
  { label: "联系方式", prop: "gkMjLxfs", type: "input" },
  { label: "", prop: "xzRy", type: "slot", width: "100%" },
  { label: "", prop: "spXx", type: "slot", width: "100%" },
  { label: "", prop: "bqInfo", type: "slot", width: "100%" },
  { label: "标签列表", prop: "bqList", type: "slot", width: "80%" }
]);
//人员信息
const pageData = reactive({
  tableData: [], //表格数据
  rykeyCount: 0,
  tableConfiger: {
    rowHieght: 61,
    showSelectType: "checkBox",
    loading: false,
    size: "small",
    border: false
  },
  total: 0,
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1
  }, //分页
  controlsWidth: 220, //操作栏宽度
  tableColumn: [
    { label: "重点人员信息", prop: "ryxx", showSolt: true },
    { label: "户籍居住信息", prop: "jzxx", showSolt: true },
    { label: "管辖单位", prop: "gxdw", showSolt: true },
    { label: "处置状态", prop: "zdrCzzt", showSolt: true },
    { label: "状态", prop: "xtSjzt", showSolt: true }
  ]
});

const addFormDiloag = ref();
//两群信息表格，重点人标签表格
const tableDate = reactive({
  lqxxList: [], //两群信息表格数据
  bqList: [], //标签表格数据
  tableConfiger: {
    rowHieght: 30,
    showSelectType: "null",
    loading: false,
    haveControls: false,
    showIndex: false
  },
  tableHeight: 200,
  tableLqColumn: [
    { label: "微信群", prop: "wxqId" },
    {
      label: "QQ群",
      prop: "qqqId"
    },
    { label: "群主昵称", prop: "qzNc" },
    { label: "群主姓名", prop: "qzXm" },
    { label: "联系人电话", prop: "qzLxdh" },
    { label: "群重要内容", prop: "qZynr" },
    { label: "操作", prop: "controls", showSolt: true }
  ],
  tableColumn: [
    { label: "标签名称", prop: "bqMc" },
    { label: "标签代码", prop: "bqDm" },
    { label: "标签种类", prop: "bqZl", showSolt: true },
    { label: "标签类型", prop: "bqLx", showSolt: true },
    { label: "标签类别", prop: "bqLb", showSolt: true }
  ]
});
const chooseShow = ref(false); //选择弹窗

const chooseType = ref(""); //选择类型
const chooseTitle = ref(""); //选择弹窗标题
const dialogList = ref(null); //选择弹窗实例
const currentEditIndex = ref(null);
const listQuery = ref({
  sfbqdj: []
}); //表单
const loading = ref(false);
const selectionValue = ref(false);
const elform = ref();
const title = ref("");
const rules = reactive({
  xsbt: [{ required: true, message: "请输入线索标题", trigger: "blur" }]
});
const editpeo = ref();
onMounted(() => { });
// 初始化数据
const init = async (type, row) => {
  dialogForm.value = true;
  await nextTick(); // 等待子组件挂载
  title.value = type == "add" ? "新增" : "编辑";
  if (row) getDataById(row.id);
  if (type === "edit" && row) {
    addFormDiloag.value?.setFormData?.(row); // 回显布控信息
    approvalInfoRef.value?.setFormData?.(row); // 回显审批信息
  } else {
    // 如果是新增模式，清空表单（可选）
    addFormDiloag.value?.resetForm?.();
    approvalInfoRef.value?.resetForm?.();
  }
};

const handleTagSelect = (selectedTags) => {
  tableDate.bqList = selectedTags.map((item) => ({
    bqDm: item.bqDm || "",
    bqId: item.bqId || "",
    bqLb: item.bqLb || "",
    bqLx: item.bqLx || "",
    bqMc: item.bqMc || "",
    bqZl: item.bqZl || ""
  }));
  listQuery.value.bqList = tableDate.bqList;
  // 每个标签包含: bqDm, bqId, bqLb, bqLx, bqMc, bqZl 属性
};
// 根据id查询详情
const getDataById = (id) => {
  qcckGet({}, "/mosty-gsxt/tbGsxtZdqt/selectVoById/" + id).then((res) => {
    listQuery.value = res;
    pageData.tableData = res.zdryList;
    tableDate.lqxxList = res.lqxxList;
    tableDate.bqList = res.bkdxList;
  });
};
const handleAddEdit = (type, row) => {
  addFormDiloag.value.init(type, row);
  dialogTitle.value = "新增信息";
};
const selectionAdd = () => {
  selectionValue.value = true;
};
// 打开弹窗
const openDialog = (type) => {
  chooseShow.value = true;
  chooseType.value = type;
  chooseTitle.value = "请录入两群信息";
};

// 打开弹窗
const open = (type) => {
  choose.value = true;
  nextTick(() => {
    tagDialog.value.setValues(listQuery.value.bqList);
  });
};
// 选择数据
const chooseDate = (data) => {
  tableDate.lqxxList.push(data);
  chooseShow.value = false;
};

//重点人员新增
const addFormPeoDate = (data) => {
  console.log(data, "选择的数据");
  pageData.tableData.push(data);
  addFormDiloag.value.close();
};

//编辑数据
const handleEditDate = (editedData) => {
  const index = pageData.tableData.findIndex(
    (item) => item.rySfzh === editedData.rySfzh // 用身份证号匹配
  );
  console.log(index, "编辑索引");
  if (index !== -1) {
    pageData.tableData[index] = { ...editedData };
  }
  addFormDiloag.value.close();
};
// 选择数据
const chooseSelectDate = (data) => {
  pageData.tableData.push(...data);
  selectionValue.value = false;
};

//删除两群信息
const delDictItem = (index) => {
  tableDate.lqxxList.splice(index, 1);
};

const submitForm = () => {
  // 正确调用子组件的submit方法
  formRef.value.submit(
    // 成功回调
    (validData) => {
      // 处理编辑情况
      if (dialogTitle.value === "编辑信息") {
        // 确保 currentEditIndex 有效
        if (
          currentEditIndex.value >= 0 &&
          currentEditIndex.value < pageData.tableData.length
        ) {
          pageData.tableData[currentEditIndex.value] = {
            ...pageData.tableData[currentEditIndex.value],
            gkMjXm: validData.gkMjXm,
            ryXb: validData.ryXb,
            rySfzh: validData.rySfzh,
            hjdXz: validData.hjdXz,
            xzdXz: validData.xzdXz,
            gkMjLxfs: validData.gkMjLxfs,
            clCph: validData.clCph,
            clCjh: validData.clCjh,
            qtTxzh: validData.qtTxzh,
            bkLx: validData.bkLx,
            bkLx: validData.bkLx,
            fjZp: validData.fjZp
          };
        } else {
          console.error("无效的编辑索引:", currentEditIndex.value);
        }
      }
      // 处理新增情况
      else {
        pageData.tableData.push(validData);
      }
      //赋值子组件数据传递给父组件
      listQuery.value.bkdxList = pageData.tableData;
      // 关闭弹窗并重置表单
      addFormDiloag.value = false;
    },
    // 错误回调（可选）
    (errors) => {
      console.error("表单验证失败:", errors);
      ElMessage.error("请检查表单填写是否正确");
    }
  );
};
// 根据索引删除数据
const deleteData = (index) => {
  pageData.tableData.splice(index, 1);
};
// 提交
const submit = () => {
  elform.value.submit((data) => {
    const { formData } = approvalInfoRef.value?.getFormData?.();

    const params = {
      ...(formData || {}), // 如果 formData 是 null/undefined，默认空对象
      ...(data || {}), // 如果 data 是 null/undefined，默认空对象
      zdryList: pageData.tableData,
      lqxxList: tableDate.lqxxList
    };
    let url =
      title.value == "新增"
        ? "/mosty-gsxt/tbGsxtZdqt/save"
        : "/mosty-gsxt/tbGsxtZdqt/update";
    qcckPost(params, url)
      .then((res) => {
        proxy.$message({ type: "success", message: title.value + "成功" });
        emit("updateDate");
        close();
      })
      .catch(() => { });
  });
};

// 关闭
const close = () => {
  listQuery.value = {};
  dialogForm.value = false;
  loading.value = false;
};
defineExpose({ init });
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

::v-deep .el-tabs--card>.el-tabs__header .el-tabs__item.is-active {
  color: #0072ff;
  background: rgba(0, 114, 255, 0.3);
}

.boxlist {
  width: 99%;
  height: 225px;
  margin-top: 10px;
  overflow: hidden;
}

.btns {
  display: grid;
  grid-template-columns: 1fr 1fr;
}
</style>
