<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <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" 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="provinceName">-->
<!--        <el-input v-model="formData.provinceName" placeholder="请输入省名称" />-->
<!--      </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="areaName">-->
<!--        <el-input v-model="formData.regionFullName" 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="请输入定位地址文字描述" />-->
<!--      </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="locationText">
        <el-input
          v-model="formData.locationText"
          placeholder="请点击右侧选择"
          readonly
        >
          <template #append>
            <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="date"
          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="visitProductIds">
        <el-input
          v-model="formData.visitProductIds"
          placeholder="请点击右侧选择"
          readonly
        >
          <template #append>
            <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">
        <Editor v-model="formData.serviceContent" height="150px" />
      </el-form-item>
      <el-form-item label="客户反馈" prop="customerFeedback">
        <el-input v-model="formData.customerFeedback" placeholder="请输入客户反馈" />
      </el-form-item>
      <el-form-item label="服务记录图片URL列表" prop="serviceImages">
        <UploadImgs v-model="formData.serviceImages" :limit="9"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <productTable ref="productListRef" @updateProduct="handleUpdateProduct" :ids="formData.visitProductIds"/>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { InfoApi, InfoVO } from '@/api/visit/info'
import productTable from "@/views/visit/customerinfo/productTable.vue";
import { pcaTextArr  } from 'element-china-area-data'
import MapPicker from '../util/MapPicker.vue'
import dayjs from 'dayjs';

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

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const selectedOptions = ref<string[]>([])
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: undefined,
  customerStatus: undefined,
  visitProductIds: undefined,
  visitMethod: undefined,
  visitType: undefined,
  serviceContent: undefined,
  customerFeedback: undefined,
  serviceImages: [],
})
const formRules = reactive({
  customerName: [{ required: true, message: '拜访人姓名不能为空', trigger: 'blur' }],
  contact: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
  companyName: [{ required: true, message: '客户公司名称不能为空', trigger: 'blur' }],
  provinceName: [{ required: true, message: '省名称不能为空', trigger: 'blur' }],
  cityName: [{ required: true, message: '市名称不能为空', trigger: 'blur' }],
  areaName: [{ required: true, message: '区名称不能为空', trigger: 'blur' }],
  regionFullName: [{ required: true, message: '所在地区不能为空', trigger: 'blur' }],
  locationText: [{ required: true, message: '定位地址文字描述不能为空', trigger: 'blur' }],
  longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
  latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
  locationImage: [{ required: true, message: '定位静态图URL不能为空', trigger: 'blur' }],
  visitDate: [{ required: true, message: '拜访日期不能为空', trigger: 'blur' }],
  customerStatus: [{ required: true, message: '性质等级不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

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

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

const handleUpdateProduct = (ids: string) => {
  console.log('来自子组件的产品ID：', ids);
  //存入表单
  formData.value.visitProductIds = ids;
};
//===========================================地图相关操作=================================
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 = 'KHXBZ-OVYYZ-N4NXF-7JCZ2-PR4FT-RYF4E'
  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 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(',');
  }
  //时间戳转换成字符串
  formData.value.visitDate = dayjs(formData.value.visitDate).format('YYYY-MM-DD');
  // 提交请求
  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: undefined,
    customerStatus: undefined,
    visitProductIds: undefined,
    visitMethod: undefined,
    visitType: undefined,
    serviceContent: undefined,
    customerFeedback: undefined,
    serviceImages: []
  }
  formRef.value?.resetFields()
  selectedOptions.value = [];
}
</script>
