<template>
  <view>
    <u-form-item
        :label="label"
        :label-position="labelPosition"
        :prop="prop"
        :required="required"
    >
      <view class="mt-10" style="flex: 1">
        <u-upload
            :file-list="value"
            :multiple="multiple"
            :max-count="maxCount"
            width="76"
            height="76"
            :accept="accept"
            :disabled="disabled"
            :deletable="!deletable"
            :capture="capture"
            @afterRead="fnAfterRead"
            @delete="fnDelete"
        />
      </view>
    </u-form-item>
    <u-line/>
  </view>
</template>

<script>
import {setFileDelete} from "@/api/api";

export default {
  props: {
    value: {
      type: Array,
      required: true,
      default: () => [],
    },
    label: {
      type: String,
      default: "图片",
    },
    labelPosition: {
      type: String,
      default: "top",
    },
    prop: {
      type: String,
      default: "",
    },
    required: {
      type: Boolean,
      default: true,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    maxCount: {
      type: Number,
      default: 4,
    },
    accept: {
      type: String,
      default: "image",
    },
    defineUpload: {
      type: Boolean,
      default: true,
    },
    defineDelete: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    deletable: {
      type: Boolean,
      default: false,
    },
    capture: {
      type: Array,
      default: () => ["album", "camera"],
    },
  },
  methods: {
    fnAfterRead(event) {
      if (this.multiple) {
        if (this.defineUpload) {
          this.$emit('input', [...this.value, ...event.file])
        }
      } else {
        if (this.defineUpload) {
          this.$emit('input', [...this.value, event.file])
        }
      }
      this.$emit('after-read', event.file)
    },
    fnDelete(event) {
      uni.showModal({
        title: "提示",
        content: "是否删除该图片",
        success: async (res) => {
          if (res.confirm) {
            if (this.defineDelete) {
              if (event.file.IMGFILES_ID) {
                await setFileDelete({
                  IMGFILES_ID: event.file.IMGFILES_ID,
                  postMethod: 'application/json',
                });
              }
              const value = uni.$u.deepClone(this.value)
              value.splice(event.index, 1)
              this.$emit('input', value)
            } else {
              this.$emit('delete', event)
            }
          }
        },
      });
    }
  },
}
</script>

<style scoped lang="scss"></style>
