<template>
  <div>
    <div class="headClass">
      <h3>群体背景信息</h3>
      <!-- @click="gettbGsxtZdqtUpdate" -->
      <el-button type="primary" v-if="showBut" :disabled="disabled" @click="submit">保存</el-button>
    </div>
    <div class="form_cnt">
      <FormMessage :disabled="disabled" v-model="listQuery" :formList="formData" labelWidth="100px" ref="elform"
        :rules="rules">
        <template #ryzp>
          <div style="width: 100%; padding-left: 50px">
            <MOSTY.Upload :showBtn="false" :limit="1" v-model="listQuery.ryzp" />
          </div>
        </template>
        <template #ryLxdh>
          <div class="phone-input-container">
            <div class="inputGroup" v-for="(item,index) in listQuery.ryLxdh" :key="index">
              <el-input v-model="listQuery.ryLxdh[index]" class="group" placeholder="请输入电话号码" />
              <div class="flex align-center but">
                <el-button type="primary" :icon="Plus" circle @click="addPhone" title="添加电话号码" />
                <el-button type="success" :icon="Minus" circle @click="removePhone(index)" title="删除电话号码" />
              </div>
            </div>
          </div>
        </template>
        <template #tags>
          <div style="display: flex; align-items: center;">
            <el-button type="primary" :disabled="disabled" @click="chooseMarksVisible = true">
              选择标签
            </el-button>
            <div v-if="roleIds.length > 0" style="margin-left: 10px; color: #606266;">
              已选择 {{ roleIds.length }} 个标签
            </div>
          </div>
        </template>

      </FormMessage>
    </div>
  </div>
  <ChooseMarks v-model="chooseMarksVisible" @choosed="choosed" :roleIds="roleIds" />
</template>

<script setup>
import * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
import { Plus ,Minus} from "@element-plus/icons-vue";
import FormMessage from "@/components/aboutTable/FormMessage.vue";
import ChooseMarks from "@/components/ChooseList/ChooseMarks/index.vue";
import { ref, reactive, onMounted, getCurrentInstance, watch } from "vue";
import { tbGsxtZdryUpdate } from "@/api/zdr.js";
const { proxy } = getCurrentInstance();
const { D_BZ_XB, D_BZ_ZZMM, D_BZ_HYZK, D_BZ_MZ, D_BZ_XZQHDM, D_BZ_RCBKZT, D_GS_ZDR_RYJB, D_GS_ZDR_YJDJ, D_GS_BK_SSJZ, D_GS_ZDR_CZZT, D_BZ_WHCD, D_ZDRY_ZYLB } =
  proxy.$dict('D_BZ_XB', 'D_BZ_ZZMM', 'D_BZ_HYZK', 'D_BZ_MZ', 'D_BZ_XZQHDM', 'D_BZ_RCBKZT', 'D_GS_ZDR_RYJB', 'D_GS_ZDR_YJDJ', 'D_GS_BK_SSJZ', 'D_GS_ZDR_CZZT', 'D_BZ_WHCD', 'D_ZDRY_ZYLB')
const props = defineProps({
  dataList: {
    type: Object,
    default: () => { },
  }, disabled: {
    type: Boolean,
    default: false
  },
  showBut: {
    type: Boolean,
    default: false
  },
})
const rules = reactive({
  ryXm: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  ...rule.identityCardRule({ validator: true }, 'rySfzh'), //身份证校验
  ...rule.phoneRule({ validator: true }, "ryLxdh"), // 是否必填 是否进行校验,
  rySfzh: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
  ryLxdh: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
  ryXb: [{ required: true, message: "请选择性别", trigger: "change" }],
  zyBm: [{ required: true, message: "请选择职业", trigger: "change" }],
  ryMz: [{ required: true, message: "请选择民族", trigger: "change" }],
  ryCsrq: [{ required: true, message: "请选择出生日期", trigger: "change" }],
  ryJg: [{ required: true, message: "请选择籍贯", trigger: "change" }],
  zdrRyjb: [{ required: true, message: "请选择人员级别", trigger: "change" }],
  zdrYjdj: [{ required: true, message: "请选择预警等级", trigger: "change" }]
});
const listQuery = ref({ryLxdh:[""]}); //表单
const chooseMarksVisible = ref(false); // 控制标签选择弹窗显示
const roleIds = ref([]); // 已选择的标签ID
const formData = ref([
  { label: "人员照片", prop: "ryzp", type: "slot", width: "100%" },
  { label: "姓名", prop: "ryXm", type: "input" },
  { label: "性别", prop: "ryXb", type: "select", options: D_BZ_XB },
  { label: "身份证号", prop: "rySfzh", type: "input" },
  { label: "籍贯", prop: "ryJg", type: "select", options: D_BZ_XZQHDM },
  { label: "曾用名", prop: "cym", type: "input" },
  { label: "文化程度", prop: "whcdBm", type: "select", options: D_BZ_WHCD },
  { label: "民族", prop: "ryMz", type: "select", options: D_BZ_MZ },
  { label: "政治面貌", prop: "zzmm", type: "select", options: D_BZ_ZZMM },
  { label: "职业", prop: "zyBm", type: "select", options: D_ZDRY_ZYLB },
  { label: "人员级别", prop: "zdrRyjb", type: "select", options: D_GS_ZDR_RYJB },
  { label: "预警等级", prop: "zdrYjdj", type: "select", options: D_GS_ZDR_YJDJ },
  { label: "出生日期", prop: "ryCsrq", type: "date" },
  { label: "户籍地区划", prop: "hjdQh", type: "select", options: D_BZ_XZQHDM },
  { label: "户籍地详址", prop: "hjdXz", type: "input" },
  { label: "户籍地派出所", prop: "hjdPcsdm", type: "department" },
  { label: "现住地区划", prop: "xzdQh", type: "select", options: D_BZ_XZQHDM },
  { label: "现住地详址", prop: "xzdXz", type: "input" },
  { label: "现住地派出所", prop: "xzdPcsdm", type: "department" },
  { label: "管辖单位", prop: "gxSsbmdm", depMc: 'gxSsbmmc', type: "department" },
  { label: "诉求单位", prop: "sqSsbmdm", depMc: 'sqSsbmmc', type: "department" },
  { label: "责任单位", prop: "zrSsbmdm", depMc: 'zrSsbmmc', type: "department" },
  { label: "所属警种", prop: "zdrSsjz", type: "select", options: D_GS_BK_SSJZ },
  { label: "涉及警种", prop: "zdrSjjz", type: "select", options: D_GS_BK_SSJZ, multiple: true },
  { label: "婚姻状态", prop: "hyzk", type: "select", options: D_BZ_HYZK },
  { label: "处置状态", prop: "zdrCzzt", type: "select", options: D_GS_ZDR_CZZT },
  { label: "布控状态", prop: "zdrBkZt", type: "select", options: D_BZ_RCBKZT },
  { label: "入库开始时间", prop: "zdrRkkssj", type: "datetime" },
  { label: "入库结束时间", prop: "zdrRkjssj", type: "datetime" },
  { label: "Mac地址", prop: "macDz", type: "input" },
  { label: "联系电话", prop: "ryLxdh", type: "slot", width: "100%" },
  { label: "标签选择", prop: "tags", type: "slot", width: "100%" },
  { label: "管控原因", prop: "zdrLkyy", type: "textarea", width: "100%" },
]);
const loading = ref(false);
const elform = ref();
const disabled = ref(false);
// phoneList已重构为listQuery.value.ryLxdh
// 创建一个工具函数进行深拷贝
const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item));
  }
  const clonedObj = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key]);
    }
  }
  return clonedObj;
};
// 监听props.dataList变化，处理初始化数据
watch(() => props.dataList, (val) => {
  if (val) {
    // 使用深拷贝避免直接引用同一个对象
    listQuery.value = deepClone(val);
    // 处理照片数据
    listQuery.value.ryzp = val.ryzp == null || val.ryzp == '' ? [] : [val.ryzp];
    // 处理标签ID数据，确保数据回显
    if (val.tagIds && Array.isArray(val.tagIds) && val.tagIds.length > 0) {
      roleIds.value = [...val.tagIds];
    } else if (val.bqIds && Array.isArray(val.bqIds) && val.bqIds.length > 0) {
      roleIds.value = [...val.bqIds];
    } else {
      roleIds.value = [];
    }
    // listQuery.value.ryLxdh =listQuery.value.ryLxdh.length>0?listQuery.value.ryLxdh:['11'];
  }
}, { deep: true })
// 提交
const submit = () => {
  loading.value = true
   gettbGsxtZdryUpdate()
};

// 处理标签选择结果
const choosed = (selectedTags) => {
  // 存储选择的标签ID用于回显
  roleIds.value = selectedTags.map(tag => tag.id);
  // 这里可以根据实际需求处理选择的标签数据
};

//
const gettbGsxtZdryUpdate = () => {
  const promes = {
    ...listQuery.value,
    ryzp: listQuery.value.ryzp.length > 0 ? listQuery.value.ryzp.toString() : "",
    ryLxdh: listQuery.value.ryLxdh,
    tagIds: roleIds.value,
    bqIds: roleIds.value,

  }
  tbGsxtZdryUpdate(promes).then((res) => {
    listQuery.value.ryzp = []
    proxy.$message({
      message: '更新成功',
      type: 'success',
    })
  }).catch((err) => {

  }).finally(() => {
    loading.value = false
  });
}
// 添加电话号码
const addPhone = () => {
  // 确保新添加的电话号码与现有数据结构一致
  // 创建深拷贝以避免响应式更新问题
  const newPhoneList = [...listQuery.value.ryLxdh];
  newPhoneList.push('');
  // 用全新数组替换现有数组，确保Vue正确检测到变化
  listQuery.value.ryLxdh = newPhoneList;
}

// 删除电话号码
const removePhone = (index) => {
  if (listQuery.value.ryLxdh .length > 1) {
    listQuery.value.ryLxdh .splice(index, 1);
  } else {
    // 清空输入但保留输入框
    listQuery.value.ryLxdh[0] = '';
    proxy.$message.warning('至少保留一个联系电话');
  }
}

const throwData = () => {
  return new Promise((resolve, reject) => {
    if (elform.value && elform.value.validate) {
      elform.value.validate((valid) => {
        if (valid) {
          // 过滤掉空的电话号码
          const validPhones = listQuery.value.ryLxdh.filter(phone => phone && phone.trim());
          if (validPhones.length === 0) {
            reject(new Error('请至少输入一个有效的联系电话'));
            return;
          }
          resolve({
            ...listQuery.value,
            ryzp: listQuery.value.ryzp && listQuery.value.ryzp.length > 0 ? listQuery.value.ryzp.toString() : '',
            ryLxdh: JSON.stringify(validPhones),
            tagIds: roleIds.value,
            bqIds: roleIds.value
          });
        } else {
          reject(new Error('表单验证失败，请检查输入信息'));
        }
      });
    } else {
      // 如果没有验证方法，直接返回数据
      const validPhones = listQuery.value.ryLxdh.filter(phone => phone && phone.trim());
      if (validPhones.length === 0) {
        reject(new Error('请至少输入一个有效的联系电话'));
        return;
      }
      resolve({
        ...listQuery.value,
        ryzp: listQuery.value.ryzp && listQuery.value.ryzp.length > 0 ? listQuery.value.ryzp.toString() : '',
        ryLxdh: JSON.stringify(validPhones),
        tagIds: roleIds.value,
        bqIds: roleIds.value
      });
    }
  });
};

defineExpose({
  throwData,
});

</script>

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

.left_box {
  width: 200px;
  border: 1px solid #c8c8c89a;
  border-radius: 5px;
  padding: 5px;
}

.right_box {
  width: calc(100% - 230px);
  overflow-y: auto;
  padding: 5px;
}

::v-deep .el-form-item__content {
  display: block !important;
  width: 100%;
  padding: 0 !important;
}

::v-deep .form-item-box {
  width: 100% !important;
}

.headClass {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.headClass::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -2px;
  width: 60px;
  height: 2px;
  background-color: #409eff;
}

h3 {
  margin: 0;
}

.phone-input-container {
  display: flex;
  // flex-direction: column;
  flex-wrap: wrap;
  width: 100%;
  padding: 0;
}

.inputGroup{
    margin-left: 10px;
    width: 100%;
    max-width: 400px;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .group{
      width: 250px;
      margin-right: 10px;
    }
    .but{
      display: flex;
      gap: 5px;
    }
  }

::v-deep .el-button--primary {
  background-color: #409eff !important;
  border-color: #409eff !important;
}

::v-deep .el-button--success {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
}

</style>
