<script setup>
import RPC from '@/utils/rpc'
import MapSelector from '@/components/MapSelector.vue'
import UploadFile from '@/components/UploadFile.vue'
import dayjs from 'dayjs'
import { VueDraggable } from 'vue-draggable-plus'
const props = defineProps({
  type: {
    type: String,
    required: true,
  },
  row: [Object],
  categoryList: {
    type: Array,
    default: [],
  },
})

const emit = defineEmits(['closed', 'onSuccess'])

const dialogVisible = ref(false)

const product_images_list = ref([])
const qualification_images_list = ref([])
const product_pdfs_list = ref([])

const isAdd = computed(() => props.type === 'add')

onMounted(() => {
  dialogVisible.value = true
})

const formRef = ref(null)
const formField = ref({})
const formRules = reactive({
  store_name: [{ required: true, message: '不可为空', trigger: 'change' }],
  latitude: [{ required: true, message: '不可为空', trigger: 'change' }],
  longitude: [{ required: true, message: '不可为空', trigger: 'change' }],
})

const loading = ref(false)
const showMapSelector = ref(false)

function closed() {
  emit('closed')
}

const submitForm = async () => {
  await formRef.value.validate()
  const api = isAdd.value ? '/store/create' : '/store/update'
  const params = {
    store: {
      ...formField.value,
      product_images: product_images_list.value.join(','),
      qualification_images: qualification_images_list.value.join(','),
      product_pdfs: JSON.stringify(product_pdfs_list.value),
    },
    // category_ids: formField.value.category_ids,
    id: isAdd.value ? null : props.row.id,
  }
  RPC.post(api, params)
    .then((res) => {
      ElMessage.success('操作成功')
      emit('onSuccess')
      emit('closed')
    })
    .finally(() => {
      loading.value = false
    })
}

if (!isAdd.value) {
  formField.value = {
    ...props.row,
  }
  product_images_list.value = props.row.product_images ? props.row.product_images.split(',') : []
  qualification_images_list.value = props.row.qualification_images
    ? props.row.qualification_images.split(',')
    : []
  product_pdfs_list.value = props.row.product_pdfs ? JSON.parse(props.row.product_pdfs) : []
}

const chooseCoordinates = () => {
  showMapSelector.value = true
}

// 处理地图坐标选择确认
const handleCoordinateConfirm = (coordinates) => {
  console.log('接收到坐标确认事件:', coordinates)
  formField.value.longitude = coordinates.longitude
  formField.value.latitude = coordinates.latitude
}

const set_main_image = (val) => {
  console.log('val', val)
  formField.value.main_image = val.fullUrl
}

const set_video = (val) => {
  formField.value.video_intro = val.fullUrl
}
const set_product_images = (val) => {
  product_images_list.value.push(val.fullUrl)
}
const set_qualification_images = (val) => {
  qualification_images_list.value.push(val.fullUrl)
}
const set_product_pdfs = (val, file) => {
  console.log(val, file)
  product_pdfs_list.value.push({
    url: val.fullUrl,
    name: file.name,
    size: (file.size / 1024 / 1024).toFixed(2),
    date: dayjs().format('YYYY-MM-DD HH:mm'),
  })
}

const delImage = (arr, index) => {
  arr.splice(index, 1)
}

const openPdf = (item) => {
  if (item.url) {
    window.open(item.url)
  }
}
</script>

<template>
  <el-dialog
    align-center
    :title="isAdd ? '新增' : '修改'"
    width="80%"
    v-model="dialogVisible"
    @closed="closed"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      label-position="right"
      label-suffix=":"
      :model="formField"
      :rules="formRules"
      v-loading="loading"
      label-width="100"
    >
      <el-form-item prop="store_name" label="门店名称">
        <el-input placeholder="请输入" v-model="formField.store_name" />
      </el-form-item>
      <el-form-item prop="location" label="地区">
        <el-input placeholder="请输入" v-model="formField.location" />
      </el-form-item>
      <el-form-item prop="address" label="地址详情">
        <el-input placeholder="请输入" v-model="formField.address" />
      </el-form-item>
      <el-form-item prop="business_hours" label="工作时间">
        <el-input placeholder="请输入" v-model="formField.business_hours" />
      </el-form-item>
      <el-form-item prop="contact_phone" label="联系电话">
        <el-input placeholder="请输入" v-model="formField.contact_phone" />
      </el-form-item>
      <el-form-item prop="tags" label="分类标签">
        <el-input placeholder="请输入,多个以,分隔" v-model="formField.tags" />
      </el-form-item>
      <!-- <el-form-item prop="category_ids" label="分类">
        <el-select
          clearable
          default-first-option
          filterable
          multiple
          placeholder="请选择"
          v-model="formField.category_ids"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item prop="main_image" label="门店主图">
        <div class="main_image_box" v-if="formField.main_image">
          <!-- <img :src="formField.main_image" alt="" /> -->
          <el-image
            ref="imageRef"
            style="width: 100%; height: 100%"
            :src="formField.main_image"
            show-progress
            :preview-src-list="[formField.main_image]"
            fit="cover"
          />
          <div class="closeBox" @click="formField.main_image = ''">
            <el-icon size="20"><CircleClose /></el-icon>
          </div>
        </div>
        <UploadFile v-else @on-success="set_main_image"></UploadFile>
      </el-form-item>
      <el-form-item prop="longitude" label="经度">
        <el-input-number
          style="width: 200px"
          :controls="false"
          placeholder="请输入"
          v-model="formField.longitude"
        />
      </el-form-item>
      <el-form-item prop="latitude" label="纬度">
        <el-input-number
          style="width: 200px"
          :controls="false"
          placeholder="请输入"
          v-model="formField.latitude"
        />
      </el-form-item>
      <el-form-item prop="" label="">
        <el-button type="primary" @click="chooseCoordinates">选择坐标</el-button>
      </el-form-item>

      <el-form-item prop="video_intro" label="视频">
        <video
          controls
          muted
          :src="formField.video_intro"
          alt=""
          class="video_box"
          v-if="formField.video_intro"
        />
        <UploadFile v-else accept="video/*" @on-success="set_video"></UploadFile>
      </el-form-item>
      <el-form-item prop="product_images" label="产品图片">
        <VueDraggable ghost-class="ghost" target=".sort-target" v-model="product_images_list">
          <TransitionGroup class="sort-target" name="list" tag="div">
            <div class="imgBox" v-for="(item, index) in product_images_list" :key="item">
              <el-image
                ref="imageRef"
                style="width: 100%; height: 100%"
                :src="item"
                show-progress
                :preview-src-list="[item]"
                fit="cover"
              />
              <div class="closeBox" @click="delImage(product_images_list, index)">
                <el-icon size="20"><CircleClose /></el-icon>
              </div>
            </div>
          </TransitionGroup>
        </VueDraggable>
        <UploadFile @on-success="set_product_images"></UploadFile>
      </el-form-item>
      <el-form-item prop="qualification_images" label="企业资质">
        <VueDraggable
          ghost-class="ghost"
          target=".sort-target2"
          v-model="qualification_images_list"
        >
          <TransitionGroup class="sort-target2" name="list" tag="div">
            <div class="imgBox" v-for="(item, index) in qualification_images_list" :key="item">
              <el-image
                ref="imageRef"
                style="width: 100%; height: 100%"
                :src="item"
                show-progress
                :preview-src-list="[item]"
                fit="cover"
              />
              <div class="closeBox" @click="delImage(qualification_images_list, index)">
                <el-icon size="20"><CircleClose /></el-icon>
              </div>
            </div>
          </TransitionGroup>
        </VueDraggable>
        <UploadFile @on-success="set_qualification_images"></UploadFile>
      </el-form-item>
      <el-form-item prop="product_pdfs" label="产品资料PDF">
        <VueDraggable ghost-class="ghost" target=".sort-target-pdf" v-model="product_pdfs_list">
          <TransitionGroup class="sort-target-pdf" name="list" tag="div">
            <div
              class="pdfBox"
              v-for="item in product_pdfs_list"
              @click="openPdf(item)"
              :key="item"
            >
              <div class="pdf_item">
                <el-icon size="40"><Document /></el-icon>
                <div class="name">{{ item.name }}</div>
                <div class="info">
                  <div class="size">{{ item.size }}MB</div>
                  <div class="date">{{ item.date }}</div>
                </div>
              </div>
              <div class="closeBox">
                <el-icon
                  size="20"
                  @click="
                    () =>
                      (product_pdfs_list = product_pdfs_list.filter((ele) => ele.url !== item.url))
                  "
                  ><CircleClose
                /></el-icon>
              </div>
            </div>
          </TransitionGroup>
        </VueDraggable>
        <div class="pdfBox">
          <UploadFile accept="pdf" @on-success="set_product_pdfs"></UploadFile>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed"> 取 消 </el-button>
        <el-button type="primary" :loading="loading" @click="submitForm"> 确 定 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 地图坐标选择器 -->
  <MapSelector
    v-model="showMapSelector"
    :longitude="formField.longitude"
    :latitude="formField.latitude"
    @confirm="handleCoordinateConfirm"
  />
</template>

<style lang="scss" scoped>
.main_image_box {
  width: 370px;
  height: 130px;
  position: relative;
  img {
    width: 100%;
    height: 100%;
  }
  .closeBox {
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
  }
}

.video_box {
  width: 370px;
  height: 130px;
}
.sort-target,
.sort-target2,
.sort-target-pdf {
  display: flex;
  flex-wrap: wrap;
}
.imgBox {
  width: 200px;
  height: 200px;
  margin-right: 10px;
  margin-bottom: 10px;
  position: relative;
  .closeBox {
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
  }
}

.list-enter-active,
.list-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: scale(0);
}

.ghost {
  opacity: 0.5;
}

.pdfBox {
  width: 200px;
  height: 100px;
  margin-right: 10px;
  margin-bottom: 10px;
  overflow: hidden;
  position: relative;
  .closeBox {
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
  }
}

.pdf_item {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  height: 99%;
  border-radius: 10px;
  padding: 0 10px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  cursor: pointer;
  .name {
    font-weight: 700;
  }
  .info {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #999;
    font-size: 12px;
  }
}
</style>
