<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="isDetail"
    >
      <el-form-item label="客户姓名" prop="customerName">
        <el-input v-model="formData.customerName" placeholder="请输入客户姓名" />
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input v-model="formData.contact" maxlength="11" placeholder="请输入联系方式" />
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
      </el-form-item>
      <el-form-item label="性质等级" prop="customerType">
        <el-select v-model="formData.customerType" placeholder="请选择性质等级">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CUSTOMER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所在地区" prop="regionFullName">
        <el-cascader
          placeholder="请选择地区"
          size="default"
          :options="pcaTextArr"
          v-model="selectedOptions"
          @change="handleChange"
        />
      </el-form-item>
      <!--      <el-form-item label="市名称" prop="cityName">-->
      <!--        <el-input v-model="formData.cityName" placeholder="请输入市名称" />-->
      <!--      </el-form-item>-->
      <!--      -->
      <!--      <el-form-item label="区名称" prop="areaName">-->
      <!--        <el-input v-model="formData.areaName" placeholder="请输入区名称" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="所在地区" prop="regionFullName">-->
      <!--        <el-input v-model="formData.regionFullName" placeholder="请输入所在地区" />-->
      <!--      </el-form-item>-->
      <!-- <el-form-item label="详细地址" prop="locationText">
        <el-input v-model="formData.locationText" placeholder="请点击右侧选择" readonly>
          <template #append v-if="formType !== 'detail'">
            <el-link type="primary" @click="openMapPicker">选择地址</el-link>
          </template>
        </el-input>
      </el-form-item> -->
      <el-form-item label="详细地址" prop="locationText">
        <el-input
          v-model="formData.locationText"
          placeholder="点击右侧选择地址后可进行编辑"
          :readonly="formType === 'detail' || !formData.locationText"
        >
          <template #append v-if="formType !== 'detail'">
            <el-link type="primary" @click="openMapPicker">选择地址</el-link>
          </template>
        </el-input>
      </el-form-item>
      <MapPicker ref="mapPickerRef" @update-location="handleLocation" />
      <!--      <el-form-item label="详细地址" prop="locationText">-->
      <!--        <el-input v-model="formData.locationText" placeholder="请输入详细地址" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="经度" prop="longitude">-->
      <!--        <el-input v-model="formData.longitude" placeholder="请输入经度" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="纬度" prop="latitude">-->
      <!--        <el-input v-model="formData.latitude" placeholder="请输入纬度" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="定位静态图 URL" prop="locationImage">-->
      <!--        <UploadImg v-model="formData.locationImage" />-->
      <!--      </el-form-item>-->
      <el-form-item label="产品信息" prop="productNames">
        <el-input v-model="formData.productNames" placeholder="请点击右侧选择" readonly>
          <template #append v-if="formType !== 'detail'">
            <el-link type="primary" @click="openProduct">选择产品</el-link>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="客户部门" prop="department">
        <el-select v-model="formData.department" placeholder="请选择客户部门">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CUSTOMER_DEPT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        v-if="formType !== 'detail'"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <productTable
    ref="productListRef"
    @update-product="handleUpdateProduct"
    :ids="formData.productIds"
  />
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { CustomerInfoApi, CustomerInfoVO } from '@/api/visit/customerinfo'
import { pcaTextArr } from 'element-china-area-data'
import MapPicker from '../util/MapPicker.vue'
import productTable from './productTable.vue'
import { homesApi } from '@/api/visit/home'
/** 客户信息 表单 */
defineOptions({ name: 'CustomerInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const isDetail = computed(() => formType.value === 'detail') //detail说明是查看详情,要只读
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const selectedOptions = ref<string[]>([])
interface CustomerFormData {
  id?: number
  customerName?: string
  contact?: string
  companyName?: string
  customerType?: string
  provinceName?: string
  cityName?: string
  areaName?: string
  regionFullName?: string
  locationText?: string
  longitude?: number
  latitude?: number
  locationImage?: string
  productIds?: string
  productNames?: string
  department?: string
}
const formData = ref<CustomerFormData>({
  id: undefined,
  customerName: undefined,
  contact: undefined,
  companyName: undefined,
  customerType: undefined,
  provinceName: undefined,
  cityName: undefined,
  areaName: undefined,
  regionFullName: undefined,
  locationText: undefined,
  longitude: undefined,
  latitude: undefined,
  locationImage: undefined,
  productIds: undefined,
  productNames: undefined,
  department: undefined
})
const formRules = reactive({
  companyName: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }],
  customerType: [{ required: true, message: '性质等级不能为空', trigger: 'change' }],
  department: [{ required: true, message: '客户部门不能为空', trigger: 'change' }],
  provinceName: [{ required: true, message: '省名称不能为空', trigger: 'blur' }],
  cityName: [{ required: true, message: '市名称不能为空', trigger: 'blur' }],
  areaName: [{ required: true, message: '区名称不能为空', trigger: 'blur' }],
  regionFullName: [{ required: true, message: '所在地区不能为空', trigger: 'change' }],
  locationText: [{ required: true, message: '详细地址不能为空', trigger: 'change' }],
  longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
  latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
  locationImage: [{ required: true, message: '定位静态图不能为空', trigger: 'blur' }],
  productNames: [{ required: false, message: '产品信息名称不能为空', trigger: 'blur|change' }],
  productIds: [{ required: true, message: '产品信息不能为空', trigger: 'blur|change' }]
})
const formRef = ref() // 表单 Ref

//===========================================选择产品相关操作=================================
const productListRef = ref<InstanceType<typeof productTable> | null>(null) //  产品列表 Ref

// 打开二级产品列表弹窗
const openProduct = () => {
  if (formData.value.productNames) {
    return
  }
  productListRef.value?.open() // 调用子组件暴露的方法
}

const handleUpdateProduct = (ids: string, names: string) => {
  //存入表单
  formData.value.productIds = ids
  formData.value.productNames = names
  formRef.value?.validateField('productNames')
}
//===========================================地图相关操作=================================
const mapPickerRef = ref()

const openMapPicker = () => {
  mapPickerRef.value.open()
}

const handleLocation = ({ lat, lng, address }) => {
  console.log('lat:', lat, 'lng:', lng, 'address:', address)
  //经纬度和地址名称
  formData.value.latitude = lat
  formData.value.longitude = lng
  formData.value.locationText = address
  //静态图
  const mapKey = '2OZBZ-WUCE7-SLKXP-HJVOW-3P6RF-WVB7H'
  const mapUrl = `https://apis.map.qq.com/ws/staticmap/v2/?center=${lat},${lng}&zoom=13&size=600*300&maptype=roadmap&markers=size:large|color:0xFFCCFF|label:k|${lat},${lng}&key=${mapKey}`

  formData.value.locationImage = mapUrl

  //逆地址解析
  const params: any = {
    lat: lat,
    lng: lng
  }
  homesApi
    .getMapGeocoder(params)
    .then((res) => {
      console.log('逆地址解析结果:', res)
      if (res.status === 0) {
        const comp = res.result.address_component
        // 赋值到 formData
        formData.value.provinceName = comp.province || ''
        formData.value.cityName = comp.city || ''
        formData.value.areaName = comp.district || ''
        formData.value.regionFullName = comp.province + comp.city + comp.district
        const province = formData.value.provinceName ?? ''
        let city = formData.value.cityName ?? ''
        const area = formData.value.areaName ?? ''
        //将省市区修改格式赋值给selectedOptions
        if (province.match(/(北京|上海|天津|重庆)/)) {
          city = '市辖区'
        }
        selectedOptions.value = [province, city, area] //专门回显用的
        formRef.value?.validateField('regionFullName')
      } else {
        console.warn('逆地址解析失败:', res.data.message)
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CustomerInfoApi.getCustomerInfo(id) //进入页面根据id获取数据
      restoreSelectedOptionsFromForm()
    } finally {
      formLoading.value = false
    }
  }
}

function restoreSelectedOptionsFromForm() {
  const province = formData.value.provinceName ?? ''
  let city = formData.value.cityName ?? ''
  const area = formData.value.areaName ?? ''
  //如果是直辖市，cityName要重新赋值为市辖区，否则无法回显
  if (province.match(/(北京|上海|天津|重庆)/)) {
    city = '市辖区'
  }
  selectedOptions.value = [province, city, area]
}

const handleChange = (value: string[]) => {
  //给省市区和所在地区赋值
  const [province, city, area] = value
  //正常赋值
  formData.value.provinceName = province
  formData.value.cityName = city
  formData.value.areaName = area
  formData.value.regionFullName = province + city + area
  //直辖市需要将city赋值为province一样的值
  if (province.match(/(北京|上海|天津|重庆)/)) {
    formData.value.cityName = province
    formData.value.regionFullName = province + province + area
  }
  console.log(formData.value.regionFullName)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustomerInfoVO
    if (formType.value === 'create') {
      await CustomerInfoApi.createCustomerInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerInfoApi.updateCustomerInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerName: undefined,
    contact: undefined,
    companyName: undefined,
    customerType: undefined,
    provinceName: undefined,
    cityName: undefined,
    areaName: undefined,
    regionFullName: undefined,
    locationText: undefined,
    longitude: undefined,
    latitude: undefined,
    locationImage: undefined,
    productIds: undefined,
    productNames: undefined,
    department: undefined
  }
  formRef.value?.resetFields()
  selectedOptions.value = []
}
</script>
