<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="170px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('mall.storeName')" prop="name">
        <el-input v-model="formData.name" :placeholder="t('mall.pleaseEnterStoreName')" />
      </el-form-item>
      <el-form-item :label="t('mall.storePhone')" prop="mobile">
        <el-input v-model="formData.mobile" :placeholder="t('mall.pleaseEnterStorePhone')" />
      </el-form-item>
      <el-form-item :label="t('mall.storeAvatar')" prop="image">
          <Materials v-model="formData.image" num="1" type="image" />
      </el-form-item>
      <el-form-item :label="t('mall.storeGroupImages')" prop="images">
        <Materials v-model="formData.images" num="5" type="image" />
      </el-form-item>
      <el-form-item :label="t('mall.businessStartTime')" prop="startTime">
        <el-time-picker v-model="formData.startTime" :placeholder="t('mall.selectBusinessStartTime')" />
      </el-form-item>
      <el-form-item :label="t('mall.businessEndTime')" prop="endTime">
        <el-time-picker v-model="formData.endTime" :placeholder="t('mall.selectBusinessEndTime')" />
      </el-form-item>
      <el-form-item :label="t('mall.selectMapLocation')" prop="addressMap">
        <el-button @click="openForm"  type="primary">{{t('mall.clickToSelectAddressToGetLongitudeAndLatitude')}}</el-button>
      </el-form-item>
      <el-form-item :label="t('mall.mapLocationAddress')" prop="addressMap">
        <el-input v-model="formData.addressMap" :placeholder="t('mall. pleaseEnterMapLocationAddress')" />
      </el-form-item>
      <el-form-item :label="t('mall.longitude')" prop="lng">
        <el-input v-model="formData.lng" :placeholder="t('mall. pleaseEnterLongitude')" />
      </el-form-item>
      <el-form-item :label="t('mall.latitude')" prop="lat">
        <el-input v-model="formData.lat" :placeholder="t('mall. pleaseEnterLatitude')" />
      </el-form-item>
      <el-form-item :label="t('mall.detailedAddress')" prop="address">
        <el-input v-model="formData.address" :placeholder="t('mall. pleaseEnterDetailedAddress')" />
      </el-form-item>
      <el-form-item :label="t('mall.takeoutDeliveryDistance')" prop="distance">
        <el-input v-model="formData.distance" :placeholder="t('mall.pleaseEnterTakeoutDeliveryDistance')" />
      </el-form-item>
      <el-form-item :label="t('mall.minimumOrderPrice')" prop="minPrice">
        <el-input v-model="formData.minPrice" :placeholder="t('mall.pleaseEnterMinimumOrderPrice')" />
      </el-form-item>
      <el-form-item :label="t('mall.deliveryPrice')" prop="deliveryPrice">
        <el-input v-model="formData.deliveryPrice" :placeholder="t('mall.pleaseEnterDeliveryPrice')" />
      </el-form-item>
      <el-form-item :label="t('mall.announcement')" prop="notice">
        <el-input type="textarea" rows="5"  v-model="formData.notice" :placeholder="t('mall.pleaseEnterAnnouncement')" />
      </el-form-item>
      <el-form-item :label="t('mall.bindAdministrator')" prop="adminId" v-if ='isShow'>
        <el-select
          v-model="formData.adminId"
          multiple
          :placeholder="t('mall.selectUser')"
        >
          <el-option
            v-for="item in adminUsers"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
        <div style="color: red;">{{t('mall.bindAdministratorForBranchManagement')}}</div>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="t('mall.isStoreReceiptPrintingEnabled')" prop="open01">
            <el-radio-group v-model="formData.open01">
              <el-radio :label="1">{{t('common.yes')}}</el-radio>
              <el-radio :label="0">{{t('common.no')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
           <el-form-item :label="t('mall.bindPrinter')" prop="uniprintId" v-if="formData.open01 == 1">
            <el-select
              v-model="formData.uniprintId"
              :placeholder="t('mall.selectPrinter')"
            >
              <el-option
                v-for="item in webPrints"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="t('mall.isCustomerReceiptPrintingEnabled')" prop="open02">
            <el-radio-group v-model="formData.open02">
              <el-radio :label="1">{{t('common.yes')}}</el-radio>
              <el-radio :label="0">{{t('common.no')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
           <el-form-item :label="t('mall.bindPrinter')" prop="userUniprintId" v-if="formData.open02 == 1">
            <el-select
              v-model="formData.userUniprintId"
              :placeholder="t('mall.selectPrinter')"
            >
              <el-option
                v-for="item in webPrints"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="t('mall.isKitchenReceiptPrintingEnabled')" prop="open03">
            <el-radio-group v-model="formData.open03">
              <el-radio :label="1">{{t('common.yes')}}</el-radio>
              <el-radio :label="0">{{t('common.no')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
           <el-form-item :label="t('mall.bindPrinter')" prop="kitchenUniprintId" v-if="formData.open03 == 1">
            <el-select
              v-model="formData.kitchenUniprintId"
              :placeholder="t('mall.selectPrinter')"
            >
              <el-option
                v-for="item in webPrints"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="t('mall.isOpen')" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">{{t('common.yes')}}</el-radio>
          <el-radio :label="0">{{t('common.no')}}</el-radio>
        </el-radio-group>
      </el-form-item>

     
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{t('common.confirm')}}</el-button>
      <el-button @click="dialogVisible = false">{{t('common.cancel')}}</el-button>
    </template>
  </Dialog>
  <MyMap ref="formRef1" @mapConfirm="mapConfirm" />
</template>
<script setup lang="ts">
import * as ShopApi from '@/api/mall/store/shop'
import * as UserApi from '@/api/system/user'
import * as WebPrintApi from '@/api/mall/store/webPrint'
import MyMap from './map.vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache()

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 formData = ref({
  id: undefined,
  name: undefined,
  mobile: undefined,
  image: undefined,
  images: undefined,
  address: undefined,
  addressMap: undefined,
  lng: undefined,
  lat: undefined,
  distance: undefined,
  minPrice: undefined,
  deliveryPrice: undefined,
  notice: undefined,
  status: undefined,
  adminId: undefined,
  uniprintId: undefined,
  userUniprintId: undefined,
  kitchenUniprintId: undefined,
  startTime: undefined,
  endTime: undefined
})
const formRules = reactive({
  name: [{ required: true, message: t('mall.storeNameCannotBeEmpty'), trigger: 'blur' }],
  mobile: [{ required: true, message: t('mall.storePhoneCannotBeEmpty'), trigger: 'blur' }],
  image: [{ required: true, message: t('mall.imageCannotBeEmpty'), trigger: 'blur' }],
  images: [{ required: true, message: t('mall.multipleImagesCannotBeEmpty'), trigger: 'blur' }],
  address: [{ required: true, message: t('mall.detailedAddressCannotBeEmpty'), trigger: 'blur' }],
  addressMap: [{ required: true, message: t('mall.mapLocationAddressCannotBeEmpty'), trigger: 'blur' }],
  lng: [{ required: true, message: t('mall.longitudeCannotBeEmpty'), trigger: 'blur' }],
  lat: [{ required: true, message: t('mall.latitudeCannotBeEmpty'), trigger: 'blur' }],
  distance: [{ required: true, message: t('mall.takeoutDeliveryDistanceTips'), trigger: 'blur' }],
  minPrice: [{ required: true, message: t('mall.minimumOrderPriceCannotBeEmpty'), trigger: 'blur' }],
  deliveryPrice: [{ required: true, message: t('mall.deliveryPriceCannotBeEmpty'), trigger: 'blur' }],
  notice: [{ required: true, message: t('mall.announcementCannotBeEmpty'), trigger: 'blur' }],
  status: [{ required: true, message: t('mall.isOpenTips'), trigger: 'blur' }],
  adminId: [{ required: true, message: t('mall.administratorIdCannotBeEmpty'), trigger: 'blur' }],
  // uniprintId: [{ required: true, message: t('mall.printerIdCannotBeEmpty'), trigger: 'blur' }],
  startTime: [{ required: true, message: t('mall.businessStartTimeCannotBeEmpty'), trigger: 'blur' }],
  endTime: [{ required: true, message: t('mall.businessEndTimeCannotBeEmpty'), trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const adminUsers = ref([])
const webPrints = ref([])
const isShow = ref(true)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  const user = wsCache.get(CACHE_KEY.USER)

  //console.log('user:',user.user.shopId)
  if(user.user.shopId > 0) {
    isShow.value = false
  }
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  getList()
  getPrintList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ShopApi.getShop(id)
      formData.value.adminId = formData.value.adminId.map(Number)
      formData.value.uniprintId = parseInt(formData.value.uniprintId)
      if(formData.value.uniprintId){
        formData.value.open01 = 1
      }else{
        formData.value.open01 = 0
      }
      formData.value.userUniprintId = parseInt(formData.value.userUniprintId)
      if(formData.value.userUniprintId){
        formData.value.open02 = 1
      }else{
        formData.value.open02 = 0
      }
      formData.value.kitchenUniprintId = parseInt(formData.value.kitchenUniprintId)
      if(formData.value.kitchenUniprintId){
        formData.value.open03 = 1
      }else{
        formData.value.open03 = 0
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ShopApi.ShopVO
    if(data.open01 == 1 && !data.uniprintId){
      message.error(t('mall.pleaseBindStorePrinter'))
      return
    }else if(data.open01 == 0 && data.uniprintId){
      data.uniprintId = ''
    }
    if(data.open02 == 1 && !data.userUniprintId){
      message.error(t('mall.pleaseBindCustomerPrinter'))
      return
    }else if(data.open02 == 0 && data.userUniprintId){
      data.userUniprintId = ''
    }
    if(data.open03 == 1 && !data.kitchenUniprintId){
      message.error(t('mall.pleaseBindKitchenPrinter'))
      return
    }else if(data.open03 == 0 && data.kitchenUniprintId){
      data.kitchenUniprintId = ''
    }
    if (formType.value === 'create') {
      await ShopApi.createShop(data)
      message.success(t('common.createSuccess'))
    } else {
      await ShopApi.updateShop(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const formRef1 = ref() // 表单 Ref
const openForm = () => {
  formRef1.value.open()
}

const mapConfirm = (mapResult) => {
  console.log('mapResult:',mapResult)
  formData.value.addressMap = mapResult.address
  formData.value.lng = mapResult.point.lng
  formData.value.lat = mapResult.point.lat
}

const getList = async () => {
  try {
    const data = await UserApi.getSimpleUserList()
    let arr = data.filter(elem => elem.id !== 1);
    adminUsers.value = arr

  } finally {
    
  }
}

const getPrintList = async () => {
  try {
    const data = await WebPrintApi.getWebPrintList()
    webPrints.value = data

  } finally {
    
  }
}


/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    mobile: undefined,
    image: undefined,
    images: undefined,
    address: undefined,
    addressMap: undefined,
    lng: undefined,
    lat: undefined,
    distance: undefined,
    minPrice: undefined,
    deliveryPrice: undefined,
    notice: undefined,
    status: 1,
    open01: 1,
    open02: 1,
    open03: 1,
    adminId: undefined,
    uniprintId: undefined,
    userUniprintId: undefined,
    kitchenUniprintId: undefined,
    startTime: undefined,
    endTime: undefined
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>
.map {
  width: 100%;
  height: 300px;
}
</style>
