<template>
  <uni-popup ref="popup" type="bottom" :mask-click="false">
    <view class="bg-white" :style="elderVarStyle">
      <view class="border-b flex items-center justify-between px-15 py-12">
        <view class="text-lg text-dark font-semibold">缺货登记</view>
        <uni-icons type="closeempty" :size="elderMode ? 32 : 24" color="#999" @click="close"></uni-icons>
      </view>
      <scroll-view scroll-y="true" class="popup-content-scroll bg-gray">
        <view class="px-15 py-12 bg-white shadow-lg">
          <view>
            <text class="is-required">*</text>
            <text class="text-base text-dark">药品名称:</text>
          </view>
          <view class="px-10 py-5 mt-12 border rounded-sm">
            <input v-model="form.drugName" class="w-full text-base text-dark" placeholder-class="text-base text-gray"
              placeholder="请输入药品名称" :maxlength="100" />
          </view>
        </view>
        <view class="mt-12 px-15 py-12 bg-white shadow-lg">
          <view>
            <text class="text-dark text-base mr-5">药品图片：</text>
            <text class="text-sm text-gray">务必上传图片，以便我们更好地获悉你的药品需求</text>
          </view>
          <view class="flex flex-wrap">
            <view v-for="i in form.images" :key="i.key" class="relative lack-image mt-12 mr-5"
              :class="i.uploaded ? 'uploaded' : ''">
              <image :src="i.tempPath || i.url" class="lack-image"></image>
              <view class="remove-icon" @click="removeImage(idx)">
                <uni-icons type="closeempty" size="24" color="red"></uni-icons>
              </view>
            </view>
            <view v-if="form.images.length < 5" class="mt-12 lack-image border rounded" @click="chooseImage()">
              <uni-icons type="camera" size="70" />
            </view>
          </view>
        </view>
        <view class="mt-12 px-15 py-12 bg-white shadow-lg">
          <view class="text-base text-dark">需求补充描述：</view>
          <view class="px-10 py-5 mt-12 border rounded-sm">
            <textarea v-model="form.description" class="w-full text-base text-dark min-h-100"
              placeholder-class="text-base text-gray" placeholder="可以补充描述药品的规格、厂家等详细信息，以便我们更好地获悉你的药品需求"
              :auto-height="true" :maxlength="500" :show-count="false" />
          </view>
        </view>

      </scroll-view>
      <view class="footer-buttons">
        <footer-buttons confirmText="提交" @cancel="close()" @confirm="submit()" />
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, watch } from 'vue';
import useElder from '@/hooks/useElder';
import { uploadUrl, getFullPath } from '@/utils/http';
import { loading, hideLoading, toast } from '@/utils/widget';
import { addLackMedicineReg } from '@/utils/api';

import FooterButtons from '@/components/footer-buttons.vue';

const emits = defineEmits(['close', 'confirm'])
const props = defineProps({
  order: {
    type: Object,
    default: () => ({})
  },
  visible: {
    type: Boolean,
    default: false
  }
})

const popup = ref();
const form = ref({
  drugName: '',
  images: [],
  description: ''
})
const { elderMode, elderVarStyle } = useElder();

function init() {
  form.value.drugName = '';
  form.value.images = [];
  form.value.description = '';
}

function chooseImage() {
  uni.chooseImage({
    count: 5 - form.value.images.length,
    sizeType: ['compressed'],
    sourceType: ['album'],
    success: (res) => {
      form.value.images = res.tempFilePaths.map((i, idx) => ({ key: `${Date.now()}-${idx}`, tempPath: i, uploaded: false, url: '' }))
    }
  })
}

function removeImage(idx) {
  form.value.images.splice(idx, 1)
}

function close() {
  emits('close')
}

async function submit() {
  if (form.value.drugName.trim() === '') {
    toast('请输入药品名称')
    return
  }
  if (form.value.images.length) {
    await uploadImages()
  }
  const data = {
    accountId: props.order.accountId,
    patientName: props.order.name,
    patientId: props.order.patientId,
    phone: props.order.mobile,
    regType: 'manual',
    drugName: form.value.drugName.trim(),
    images: form.value.images.map(i => i.url).filter(Boolean),
    description: form.value.description.trim(),
  }
  loading()
  const res = await addLackMedicineReg(data)
  hideLoading()
  if (res && res.success) {
    close()
    toast('登记成功', { icon: 'success' })
  } else {
    toast(res?.message || '提交失败')
  }
}

async function uploadImages() {
  const tempFilePaths = form.value.images.map(i => i.uploaded ? '' : i.tempPath).filter(Boolean);
  if (tempFilePaths.length === 0) {
    return
  }
  loading('正在上传图片...')
  const res = await Promise.all(tempFilePaths.map(upload));

  hideLoading()
  tempFilePaths.forEach((tempPath, idx) => {
    const url = res[idx];
    if (url) {
      const index = form.value.images.findIndex(i => i.tempPath === tempPath);
      if (index > -1) {
        form.value.images[index].url = url;
        form.value.images[index].uploaded = true;
      }
    }
  })
  const successCount = res.filter(Boolean).length;
  const failedCount = tempFilePaths.length - successCount;
  if (failedCount > 0) {
    toast(`上传失败${failedCount}张图片`)
    return Promise.reject()
  }
}

function upload(path) {
  return new Promise((resolve) => {
    uni.uploadFile({
      url: uploadUrl, // 替换为你的上传接口地址
      filePath: path,
      name: 'file',
      fileType: 'image',
      success: (res) => {
        try {
          const url = JSON.parse(res.data).filePath;
          resolve(url ? getFullPath(url) : '')
        } catch (e) {
          resolve()
        }
      },
      fail: res => {
        resolve()
      }
    })
  })
}

watch(() => props.visible, n => {
  if (n) {
    popup.value && popup.value.open()
    init()
  } else {
    popup.value && popup.value.close()
  }
})

</script>

<style lang="scss" scoped>
.popup-title {
  font-size: var(--text-base);
  font-weight: bold;
  color: #333;
}

.popup-content-scroll {
  max-height: 75vh;
}

.min-h-100 {
  min-height: 100px;
}

.is-required {
  color: red;
  margin: 10rpx;
  font-weight: bold;
}

.lack-image {
  width: 70px;
  height: 70px;
}

.uploaded::after {
  content: "已上传";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
  font-size: var(--text-sm);
  color: white;
  line-height: 1.4;
  background: rgba(0, 0, 0, 0.4);
}

.remove-icon {
  position: absolute;
  right: 0;
  top: 0;
  padding-left: 40rpx;
}
</style>