<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-autocomplete
          v-model="formData.companyName"
          :fetch-suggestions="querySearch"
          clearable
          class="inline-input w-50"
          @select="handleSelect"
          placeholder="请输入客户公司名称"
        />
      </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="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="visitDate">
        <el-date-picker
          v-model="formData.visitDate"
          type="datetime"
          value-format="x"
          placeholder="选择拜访日期"
        />
      </el-form-item>
      <el-form-item label="性质等级" prop="customerStatus">
        <el-select v-model="formData.customerStatus" 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="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-item label="拜访品种" prop="visitProductNames">
        <el-input v-model="formData.visitProductNames" 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="visitMethod">
        <el-select v-model="formData.visitMethod" placeholder="请选择拜访方式">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.VISIT_METHOD)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="拜访类型" prop="visitType">
        <el-select v-model="formData.visitType" placeholder="请选择拜访类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.VISIT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务内容" prop="serviceContent">
        <el-input
          v-model="formData.serviceContent"
          type="textarea"
          placeholder="请输入服务内容"
          maxlength="500"
          show-word-limit
          :autosize="{ minRows: 4, maxRows: 6 }"
        />
      </el-form-item>
      <el-form-item label="客户反馈" prop="customerFeedback">
        <el-input
          v-model="formData.customerFeedback"
          type="textarea"
          placeholder="请输入客户反馈"
          maxlength="500"
          show-word-limit
          :autosize="{ minRows: 4, maxRows: 6 }"
        />
      </el-form-item>
      <el-form-item label="服务记录图片" prop="serviceImages">
        <UploadImgs
          :class="{ hide_box: isDetail }"
          v-model="formData.serviceImages"
          :limit="9"
          @change="onServiceImageChange"
          :disabled="isDetail"
        />
      </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.visitProductIds"
  />
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { InfoApi, InfoVO } from '@/api/visit/info'
import { CustomerInfoApi } from '@/api/visit/customerinfo'
import productTable from '@/views/visit/customerinfo/productTable.vue'
import { pcaTextArr } from 'element-china-area-data'
import MapPicker from '../util/MapPicker.vue'
import { onMounted } from 'vue'
import { homesApi } from '@/api/visit/home'

/** 客户拜访记录 表单 */
defineOptions({ name: 'InfoForm' })

const upload_btn = ref(true) //定义图片上传展示隐藏

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 查看
const selectedOptions = ref<string[]>([])
const isDetail = computed(() => formType.value === 'detail') //detail说明是查看详情,要只读
const formData = ref({
  id: undefined,
  customerName: undefined,
  contact: undefined,
  companyName: undefined,
  provinceName: undefined,
  cityName: undefined,
  areaName: undefined,
  regionFullName: undefined,
  locationText: undefined,
  longitude: undefined,
  latitude: undefined,
  locationImage: undefined,
  visitDate: Date.now(),
  customerStatus: undefined,
  department: undefined,
  visitProductIds: undefined,
  visitProductNames: undefined,
  visitMethod: undefined,
  visitType: undefined,
  serviceContent: undefined,
  customerFeedback: undefined,
  serviceImages: []
})
const formRules = reactive({
  companyName: [{ required: true, message: '客户公司名称不能为空', trigger: 'blur|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' }],
  visitDate: [{ required: true, message: '拜访日期不能为空', trigger: 'blur' }],
  customerStatus: [{ required: true, message: '性质等级不能为空', trigger: 'change' }],
  department: [{ required: true, message: '客户部门不能为空', trigger: 'change' }],
  visitMethod: [{ required: true, message: '拜访方式不能为空', trigger: 'change' }],
  visitType: [{ required: true, message: '拜访类型不能为空', trigger: 'change' }],
  visitProductNames: [{ required: true, message: '拜访品种名称不能为空', trigger: 'blur|change' }],
  visitProductIds: [{ required: true, message: '拜访品种不能为空', trigger: 'blur|change' }],
  serviceContent: [
    { required: true, message: '请输入服务内容', trigger: 'blur' },
    { max: 500, message: '最多输入 500 个字符', trigger: 'blur' }
  ],
  customerFeedback: [
    { required: true, message: '请输入客户反馈', trigger: 'blur' },
    { max: 500, message: '最多输入 500 个字符', trigger: 'blur' }
  ],
  serviceImages: [{ required: true, message: '请上传服务记录图片', trigger: 'blur|change' }]
})
const formRef = ref() // 表单 Ref
//===========================================下拉搜索相关====================================
interface RestaurantItem {
  companyName: string
  contact: string
}

const restaurants = ref<RestaurantItem[]>([])
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  console.log(results)
  cb(results)
}
const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}
const loadAll = async () => {
  try {
    const res = await CustomerInfoApi.getAll()

    if (!res || !Array.isArray(res)) {
      console.warn('返回结果格式不符合预期:', res)
      restaurants.value = []
      return
    }

    restaurants.value = res.map((item) => ({
      value: item?.companyName || '',
      companyName: item?.companyName || '',
      contact: item?.contact || '',
      customerName: item?.customerName || '',
      provinceName: item?.provinceName || '',
      cityName: item?.cityName || '',
      areaName: item?.areaName || '',
      regionFullName: item?.regionFullName || '',
      locationText: item?.locationText || '',
      longitude: item?.longitude || '',
      latitude: item?.latitude || '',
      locationImage: item?.locationImage || '',
      customerStatus: item?.customerType ?? '',
      department: item?.department || ''
    }))
  } catch (error) {
    console.error('加载公司信息失败:', error)
    restaurants.value = []
  }
}

/** 选中后自动带出公司名称和联系方式 */
const handleSelect = (item: Record<string, any>) => {
  formData.value.companyName = item.companyName
  formData.value.contact = item.contact
  formData.value.customerName = item.customerName
  formData.value.regionFullName = item.regionFullName
  formData.value.provinceName = item.provinceName
  formData.value.cityName = item.cityName
  formData.value.areaName = item.areaName
  formData.value.locationText = item.locationText
  formData.value.longitude = item.longitude
  formData.value.latitude = item.latitude
  formData.value.locationImage = item.locationImage
  formData.value.customerStatus = item.customerStatus
  formData.value.department = item.department
  restoreSelectedOptionsFromForm()
  formRef.value?.validateField('companyName')
  formRef.value?.validateField('regionFullName')
  formRef.value?.validateField('locationText')
  formRef.value?.validateField('customerStatus')
  formRef.value?.validateField('department')
}
//===========================================选择产品相关操作=================================
const productListRef = ref<InstanceType<typeof productTable> | null>(null) //  产品列表 Ref

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

const handleUpdateProduct = (ids: string, names: string) => {
  //存入表单
  formData.value.visitProductIds = ids
  console.log(names)
  formData.value.visitProductNames = names
  formRef.value?.validateField('visitProductNames')
}
//===========================================地图相关操作=================================
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 InfoApi.getInfo(id)
      restoreSelectedOptionsFromForm()
      //将图片url数组从字符串转为数组
      formData.value.serviceImages = formData.value.serviceImages.split(',')
      console.log(formData.value.serviceImages)
    } 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()
  //将图片url数组从数组变为string字符串
  const raw = formData.value
  if (Array.isArray(raw.serviceImages)) {
    raw.serviceImages = raw.serviceImages.join(',')
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as InfoVO
    if (formType.value === 'create') {
      await InfoApi.createInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await InfoApi.updateInfo(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,
    provinceName: undefined,
    cityName: undefined,
    areaName: undefined,
    regionFullName: undefined,
    locationText: undefined,
    longitude: undefined,
    latitude: undefined,
    locationImage: undefined,
    visitDate: Date.now(),
    customerStatus: undefined,
    department: undefined,
    visitProductIds: undefined,
    visitProductNames: undefined,
    visitMethod: undefined,
    visitType: undefined,
    serviceContent: undefined,
    customerFeedback: undefined,
    serviceImages: []
  }
  formRef.value?.resetFields()
  selectedOptions.value = []
}
const onServiceImageChange = () => {
  // 强制触发校验
  formRef.value?.validateField('serviceImages')
}
onMounted(() => {
  loadAll()
})
</script>
<style lang="scss" scoped>
.hide_box ::v-deep .el-upload--picture-card {
  display: none;
}
</style>
