<template>
  <div class="dialog" v-if="dialogForm">
    <div class="head_box">
      <span class="title">{{ 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 #basic>
          <el-divider content-position="left">基础管理</el-divider>
        </template>
        <template #address>
          <el-divider content-position="left">地址信息</el-divider>
        </template>
        <template #jurisdiction>
          <el-divider content-position="left">管辖信息</el-divider>
        </template>
        <template #status>
          <el-divider content-position="left">状态信息</el-divider>
        </template>
        <template #bqInfo>
          <el-divider content-position="left">标签信息</el-divider>
        </template>
        <!-- 人员标签模型-->
        <template #bqList>
          <el-button @click="openDialog('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 #gxSsbmdm>
          <el-select
            v-model="listQuery.gxSsbmdm"
            placeholder="请选择管辖单位"
            style="width: 240px"
            @change="handleDeptChange('gxSsbmmc', $event)"
          >
            <el-option
              v-for="item in deptList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </template>
        <!-- 户籍派出所 -->
        <template #hjdPcsdm>
          <el-select
            v-model="listQuery.hjdPcsdm"
            placeholder="请选择户籍派出所"
            style="width: 240px"
            @change="handleDeptChange('hjdPcsmc', $event)"
          >
            <el-option
              v-for="item in deptList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </template>
        <!-- 诉求单位 -->
        <template #sqSsbmdm>
          <el-select
            v-model="listQuery.sqSsbmdm"
            placeholder="请选择户籍派出所"
            style="width: 240px"
            @change="handleDeptChange('sqSsbmmc', $event)"
          >
            <el-option
              v-for="item in deptList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </template>
        <!-- 现住地派出所 -->
        <template #xzdPcsdm>
          <el-select
            v-model="listQuery.xzdPcsdm"
            placeholder="请选择现住地派出所"
            style="width: 240px"
            @change="handleDeptChange('xzdPcsmc', $event)"
          >
            <el-option
              v-for="item in deptList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </template>
        <!-- 责任单位 -->
        <template #zrSsbmdm>
          <el-select
            v-model="listQuery.zrSsbmdm"
            placeholder="请选择责任单位"
            style="width: 240px"
            @change="handleDeptChange('zrSsbmmc', $event)"
          >
            <el-option
              v-for="item in deptList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </template>
      </FormMessage>
      <!-- 列表弹窗 -->
      <TagSelectorDialog
        v-model="chooseShow"
        ref="tagDialog"
        @chooseDate="handleTagSelect"
        :dic="{ D_GS_BQ_ZL, D_GS_BQ_LB, D_GS_BQ_LX }"
      />
    </div>
  </div>
</template>

<script setup>
import MyTable from "@/components/aboutTable/MyTable.vue";
import FormMessage from "@/components/aboutTable/FormMessage.vue";
import { qcckGet, qcckPost, qcckPut } from "@/api/qcckApi.js";
import TagSelectorDialog from "./TagSelectorDialogPeo.vue";
import * as rule from "@/utils/rules.js";
import {
  ref,
  defineExpose,
  reactive,
  onMounted,
  defineEmits,
  getCurrentInstance,
  nextTick
} from "vue";
import { selectUserDeptPage } from "@/api/user-manage";

const props = defineProps({
  dic: Object
});
const { proxy } = getCurrentInstance();

const {
  D_GS_BK_SSJZ,
  D_GS_ZDR_RYJB,
  D_GS_SSYJ,
  D_GS_BQ_DJ,
  D_BZ_XZQHDM,
  D_BZ_MZ,
  D_BZ_XB,
  D_GS_ZDR_CZZT,
  D_GS_BQ_ZL,
  D_GS_BQ_LB,
  D_GS_BQ_LX,
  D_GS_ZDR_YJDJ
} = proxy.$dict(
  "D_GS_BK_SSJZ",
  "D_GS_ZDR_RYJB",
  "D_GS_SSYJ",
  "D_GS_BQ_DJ",
  "D_BZ_XZQHDM",
  "D_BZ_MZ",
  "D_BZ_XB",
  "D_GS_ZDR_CZZT",
  "D_GS_BQ_ZL",
  "D_GS_BQ_LB",
  "D_GS_BQ_LX",
  "D_GS_ZDR_YJDJ"
); //获取字典数据
const emits = defineEmits([
  "update:modelValue",
  "chooseDate",
  "handleEditDate"
]);

const tagDialog = ref();
const dialogForm = ref(false); //弹窗
const formData = ref([
  { label: "", prop: "basic", type: "slot", width: "100%" },
  { label: "姓名", prop: "ryXm", type: "input" },
  { label: "性别", prop: "ryXb", type: "select", options: D_BZ_XB },
  { label: "民族", prop: "ryMz", type: "select", options: D_BZ_MZ },
  { label: "身份证号", prop: "rySfzh", type: "input" },
  { label: "联系电话", prop: "ryLxdh", type: "input" },
  { label: "出生日期", prop: "ryCsrq", type: "date" },
  { label: "籍贯", prop: "ryJg", type: "select", options: D_BZ_XZQHDM },
  {
    label: "级别",
    prop: "zdrRyjb",
    type: "select",
    options: D_GS_ZDR_RYJB
  },
  {
    label: "预警等级",
    prop: "zdrYjdj",
    type: "select",
    options: D_GS_ZDR_YJDJ
  },
  { label: "", prop: "address", type: "slot", width: "100%" },
  { label: "户籍地区划", prop: "hjdQh", type: "select", options: D_BZ_XZQHDM },
  { label: "户籍地详址", prop: "hjdXz", type: "input" },
  {
    label: "户籍地派出所",
    prop: "hjdPcsdm",
    type: "slot"
  },
  { label: "现住地区划", prop: "xzdQh", type: "select", options: D_BZ_XZQHDM },
  { label: "现住地详址", prop: "xzdXz", type: "input" },
  {
    label: "现住地派出所",
    prop: "xzdPcsdm",
    type: "slot"
  },
  { label: "", prop: "jurisdiction", type: "slot", width: "100%" },
  {
    label: "管辖单位",
    prop: "gxSsbmdm",
    type: "slot"
  },
  {
    label: "诉求单位",
    prop: "sqSsbmdm",
    type: "slot"
  },
  {
    label: "责任单位",
    prop: "zrSsbmdm",
    type: "slot"
  },
  { label: "所属警种", prop: "zdrSsjz", type: "select", options: D_GS_BK_SSJZ },
  {
    label: "涉及警种",
    prop: "zdrSjjz",
    type: "select",
    options: D_GS_BK_SSJZ,
    multiple: true
  },
  { label: "管控民警姓名", prop: "gkMjXm", type: "input" },
  { label: "管控民警警号", prop: "gkMjJh", type: "input" },
  { label: "管控原因", prop: "zdrLkyy", type: "textarea", width: "100%" },
  { label: "", prop: "status", type: "slot", width: "100%" },
  {
    label: "处置状态",
    prop: "zdrCzzt",
    type: "select",
    options: D_GS_ZDR_CZZT
  },

  { label: "入库开始时间", prop: "zdrRkkssj", type: "datetime" },
  { label: "入库结束时间", prop: "zdrRkjssj", type: "datetime" },

  // { label: "人员标签大类", prop: "bqdl", type: "select", options: [] },
  // { label: "人员标签细类", prop: "bqxl", type: "select", options: [] },
  { label: "", prop: "bqInfo", type: "slot", width: "100%" },
  { label: "标签列表", prop: "bqList", type: "slot", width: "80%" }
]);
const listQuery = ref({}); //表单
const deptList = ref([]); //部门列表
const chooseShow = ref(false); //选择弹窗
const tableDate = reactive({
  bqList: [], //表格数据
  keyCount: 0,
  rykeyCount: 0,
  tableConfiger: {
    rowHieght: 61,
    showSelectType: "null",
    loading: false
  },
  total: 0,
  tableHeight: 225,
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1
  }, //分页
  controlsWidth: 90, //操作栏宽度
  tableColumn: [
    { label: "标签名称", prop: "bqMc" },
    { label: "标签代码", prop: "bqDm" },
    { label: "标签种类", prop: "bqZl", showSolt: true },
    { label: "标签类型", prop: "bqLx", showSolt: true },
    { label: "标签类别", prop: "bqLb", showSolt: true }
  ]
});
const chooseType = ref("01"); //选择弹窗类型
const chooseTitle = ref(""); //选择弹窗
const loading = ref(false);
const elform = ref();
const title = ref("");
const rules = reactive({
  xsbt: [{ required: true, message: "请输入线索标题", trigger: "blur" }]
});
const editpeo = ref();
onMounted(() => {
  getdepartmentList();
});
// 初始化数据
const init = (type, row) => {
  dialogForm.value = true;
  title.value = type == "add" ? "新增" : type == "info" ? "详情" : "编辑";
};

// 获取部门列表
const getdepartmentList = () => {
  selectUserDeptPage().then((res) => {
    deptList.value = res?.records.map((item) => ({
      label: item.deptName,
      value: item.deptId
    }));
  });
};

const submit = () => {
  elform.value.submit((data) => {
    // 处理 zdrSjjz 字段（如果是数组就转成字符串）
    if (Array.isArray(data.zdrSjjz)) {
      data.zdrSjjz = data.zdrSjjz.join(",");
    }
    console.log("提交数据:", data, title.value);
    // 根据 title 判断是新增还是编辑
    if (title.value === "新增") {
      console.log("新增数据:", data);
      emits("chooseDate", data); // 新增
    } else if (title.value === "编辑") {
      emits("handleEditDate", data); // 编辑
    }
  });
};
// // 提交
// const submit = () => {
//   elform.value.submit((data) => {
//     data.zdrSjjz = data.zdrSjjz.join(",");
//     emits("chooseDate", data);
//       let url =
//         title.value == "新增"
//           ? "/mosty-gsxt/tbGsxtZdry/save"
//           : "/mosty-gsxt/tbGsxtZdry/update";
//       let params = { ...data };

//       qcckPost(params, url)
//         .then((res) => {
//           proxy.$message({ type: "success", message: title.value + "成功" });
//           emit("onSearch");
//           close();
//         })
//         .catch(() => {});
//   });
// };
// 打开弹窗
const openDialog = (type) => {
  chooseShow.value = true;
  chooseType.value = type;
  chooseTitle.value = "请选择标签";
  nextTick(() => {
    tagDialog.value.setValues(listQuery.value.bqList);
  });
};
const handleDeptChange = (nameField, selectedValue) => {
  // 找到选中的部门
  const selectedDept = deptList.value.find(
    (item) => item.value.toString() === selectedValue
  );
  // 更新名称
  listQuery.value[nameField] = selectedDept ? selectedDept.label : "";
};
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 属性
};

// 接收父组件传入的数据并回显
const setFormData = (data) => {
  tableDate.bqList = data.bqList ?? [];
  listQuery.value = {
    ...data // 假设 data 包含所有需要的字段
  };
};

// 关闭
const close = () => {
  listQuery.value = {};
  dialogForm.value = false;
  loading.value = false;
};
// 删除
const delDictItem = (bqId) => {
  tableDate.bqList = tableDate.bqList.filter((item) => item.bqId !== bqId);
  listQuery.value.bqList = tableDate.bqList;
};
// 2. 暴露获取数据的方法
const getFormData = () => {
  // 可以在这里添加验证逻辑
  return {
    formData: listQuery.value
  };
};
defineExpose({ init, setFormData, close });
</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;
}
</style>
