<template>
  <div class="dialog" v-if="dialogForm">
    <div class="head_box">
      <span class="title">{{ pageInfo[pageType].title }}</span>
      <div>
        <el-button size="small" type="primary" v-if="['add', 'edit'].includes(pageType)" @click="_onSave">保存</el-button>
        <el-button size="small" @click="close">关闭</el-button>
      </div>
    </div>
    <div class="cntinfo">
      <el-form ref="formRef" :model="form" :rules="rules" :inline="true" label-position="top">
        <el-form-item style="width: 40%" prop="sfzh" label="身份证号">
          <el-input v-model="form.sfzh" placeholder="请输入身份证号" clearable />
        </el-form-item>
        <el-form-item style="width: 40%" prop="xm" label="姓名">
          <el-input v-model="form.xm" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item style="width: 40%" prop="rylx" label="人员类型">
          <el-select v-model="form.rylx" placeholder="请选择" style="width: 100%">
            <el-option label="流动人口" value="01" />
            <el-option label="常驻人口" value="02" />
            <el-option label="重点人" value="03" />
          </el-select>
        </el-form-item>
        <el-form-item style="width: 40%" prop="pcsj" label="采集时间">
          <el-date-picker v-model="form.pcsj" type="datetime" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item style="width: 40%" prop="ssbmdm" label="所属部门">
          <MOSTY.Department width="100%" clearable v-model="form.ssbmdm" :placeholder="form.ssbm ? form.ssbm : '请选择所属部门'" />
        </el-form-item>
        <!-- 联系方式与地址在前 -->
        <el-form-item style="width: 40%" prop="lxdh" label="联系电话">
          <el-input v-model="form.lxdh" placeholder="请输入联系电话" clearable />
        </el-form-item>
        <el-form-item style="width: 40%" prop="xjzdz" label="居住地址">
          <el-input v-model="form.xjzdz" placeholder="请输入居住地址" clearable />
        </el-form-item>

        <!-- 经纬度选择放到最后，参考感知源实现 -->
        <el-form-item style="width: 85%" prop="jd" label="坐标位置">
          <div class="latlng">
            <el-input :disabled="true" v-model="form.jd" clearable placeholder="请选择坐标" style="width: 42%" />
            <el-input :disabled="true" v-model="form.wd" clearable placeholder="请选择坐标" style="width: 42%; margin-left: 1%" />
            <el-button @click="selectLocation" size="small" type="primary">选择定位</el-button>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%">
          <div class="mapbox"><GdMap /></div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { RyGjInsertEntity, RyGjEditEntity } from '@/api/mosty-jcz.js'
import * as MOSTY from '@/components/MyComponents/index'
import GdMap from '@/components/GdMap/index.vue'
import emitter from '@/utils/eventBus.js'

const formRef = ref(null)
const dialogForm = ref(false)
const form = ref({})
const pageType = ref('add')
const emit = defineEmits(['refresh'])
const pageInfo = { add: { title: '新增', url: '' }, edit: { title: '编辑', url: '' }, detail: { title: '详情' } }

const rules = {
  sfzh: [{ required: true, message: '请输入身份证号' }],
  rylx: [{ required: true, message: '请选择人员类型' }],
  pcsj: [{ required: true, message: '请选择采集时间', trigger: 'change' }],
  jd: [{ required: true, message: '请输入经度' }],
  wd: [{ required: true, message: '请输入纬度' }]
}

const init = (type, row) => {
  pageType.value = type
  dialogForm.value = true
  if (type === 'detail') {
    form.value = { ...row }
    centerMap()
  } else if (type === 'edit') {
    form.value = { ...row }
  } else {
    form.value = {}
  }
}

const _onSave = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (!valid) return
    enrichFromSfzh()
    if (pageType.value === 'add') {
      RyGjInsertEntity(form.value).then(() => { ElMessage({ message: '新增成功', type: 'success' }); emit('refresh'); close(); })
    } else {
      RyGjEditEntity(form.value).then(() => { ElMessage({ message: '修改成功', type: 'success' }); emit('refresh'); close(); })
    }
  })
}

const close = () => { dialogForm.value = false; form.value = {} }

defineExpose({ init })

const enrichFromSfzh = () => {
  const val = form.value.sfzh || ''
  if (val && val.length >= 18) {
    const y = val.substring(6, 10)
    const m = val.substring(10, 12)
    const d = val.substring(12, 14)
    form.value.csrq = `${y}-${m}-${d}`
    const genderCode = parseInt(val.substring(16, 17))
    form.value.xbdm = (genderCode % 2 === 1) ? '1' : '2' // 1-男 2-女
  }
}

const selectLocation = () => {
  emitter.emit('drawShape', { flag: 'select_point', type: 'point', isclear: true })
}

const coordHandler = (res) => {
  if (res?.type === 'point') {
    form.value.jd = res.coord[0]
    form.value.wd = res.coord[1]
    chackLat()
  }
}

const centerMap = () => {
  if (form.value.jd && form.value.wd) {
    emitter.emit('setMapCenter', { location: [Number(form.value.jd), Number(form.value.wd)], zoomLevel: 12 })
    chackLat()
  }
}

const chackLat = () => {
  const { jd, wd } = form.value
  emitter.emit('deletePointArea', 'jczMap_Gzy')
  if (jd && wd) {
    emitter.emit('addPointArea', {
      coords: [{ jd: Number(jd), wd: Number(wd) }],
      icon: require('@/assets/images/bi/gzy.png'),
      flag: 'jczMap_Gzy'
    })
  }
}

onMounted(() => { emitter.on('coordString', coordHandler) })
onUnmounted(() => { emitter.off('coordString') })
</script>

<style scoped>
.dialog { padding: 20px; }
.head_box { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.cntinfo { height: calc(100% - 70px); overflow: auto; }

.mapbox {
  width: 1000px;
  padding: 0 10px;
  height: 400px;
  box-sizing: border-box;
  background: #000;
}
.latlng { display: flex; align-items: center; gap: 8px; }
</style>
