<template>
  <div :class="$style.contain">
    <div class="ant-upload-list-picture-card">
      <div
        v-for="item in attachments"
        :key="item.code"
        class="ant-upload-list-picture-card-container"
        :class="{ [$style.checked]: selectedKeys && selectedKeys.includes(item.code) }"
        @click="select(item)"
      >
        <div
          v-if="item.code"
          class="ant-upload-list-item ant-upload-list-item-done ant-upload-list-item-list-type-picture-card"
        >
          <div class="ant-upload-list-item-info">
            <a class="ant-upload-list-item-thumbnail">
              <img
                :src="(`api/framework/v1/user-signature/download/` + item.code) | sdResource"
                class="ant-upload-list-item-image"/></a
          ></div>
          <span class="ant-upload-list-item-actions"
            ><a
              :href="(`api/framework/v1/user-signature/download/` + item.code) | sdResource"
              target="_blank"
              @click.stop="() => {}"
            >
              <a-icon type="eye-o" />
            </a>
            <a-icon v-if="item.deletable" type="delete" @click.stop="DelFile(item)" />
          </span>
        </div>
      </div>
    </div>
    <div :class="$style.uploadbtn">
      <a-upload
        ref="upload"
        name="signature"
        list-type="picture-card"
        accept=".png"
        :file-list="[]"
        :custom-request="customRequest"
      >
        <div>
          <a-icon type="plus" />
          <div class="ant-upload-text">上传</div>
        </div>
      </a-upload>
    </div>
  </div>
</template>

<script>
import { Modal, Message } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import storeMixin from '@/common/store-mixin'
import components from './_import-components/sd-signature-upload-import'

export default {
  name: 'SdSignatureUpload',
  components,
  mixins: [storeMixin],
  props: {
    groupId: {
      required: true,
      type: [String, Number],
      default: undefined,
    },
    selectedKeys: {
      type: Array,
      default: undefined,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      attachments: [],
    }
  },
  created() {
    this.getFileList(true, true, true)
  },
  methods: {
    getFileList(noTriggerCheck = false, updateList = true, fromField = false) {
      let p
      if (this.groupId) {
        p = axios
          .get(`api/framework/v1/user-signature/info/${this.groupId}`)
          .then((res) => res.data)
      } else {
        p = Promise.resolve({})
      }
      return p.then((data) => {
        const attachments = (data.imageInfos || []).map((item) => ({
          Unid: item.id.toString(),
          code: item.id.toString(),
          deletable: !this.readOnly,
          FileName: item.name,
        }))
        if (updateList) {
          this.attachments = attachments
          this.$emit('input', this.attachments)
        } else {
          return attachments
        }
        if (!noTriggerCheck && updateList) {
          /**
           * 附件添加删除时触发
           * @property {Array} 附件信息
           */
          this.$emit('change', this.attachments)
        }
      })
    },
    select(item) {
      const keys = [...this.selectedKeys]
      if (keys.includes(item.code)) {
        keys.splice(keys.indexOf(item.code), 1)
      } else {
        keys.push(item.code)
      }
      this.$emit('update:selectedKeys', keys)
    },
    DelFile(file) {
      Modal.confirm({
        title: `确认删除附件《${file.FileName}》?`,
        okType: 'danger',
        onOk: () => {
          axios.delete(`api/framework/v1/user-signature/image/${file.code}`, {}).then((_) => {
            if (typeof this.selectedKeys !== 'undefined') {
              // 如果是可选择附件，并且被选中的附件删除，则更新选中的key
              const keys = [...this.selectedKeys]
              if (keys.includes(file.Unid)) {
                keys.splice(keys.indexOf(file.Unid), 1)
              }
              this.$emit('update:selectedKeys', keys)
            }
            this.getFileList()
          })
        },
      })
    },
    customRequest(data) {
      // 前端上传
      if (this.attachments.find((item) => item.FileName === data.file.name)) {
        Message.warn(`已存在文件《${data.file.name}》`)
        return
      }
      if (data.file.size === 0) {
        Message.warn(`不能上传大小为0的文件`)
        return
      }
      const file = {
        FileName: data.file.name,
      }
      this.attachments.push(file)
      this.attachments = [...this.attachments]
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('FileName', data.file.name)
      axios
        .post('api/framework/v1/user-signature/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
        .then((res) => {
          const i = this.attachments.findIndex((item) => item.FileName === data.file.name)
          if (res.status !== 200) {
            this.attachments.splice(i, 1)
            Message.error(`${data.file.name} 上传失败`)
            return
          }
          this.$set(
            this.attachments,
            i,
            Object.assign({}, this.attachments[i], {
              Unid: res.data.toString(),
              code: res.data.toString(),
              deletable: true,
            })
          )
          this.$emit('input', this.attachments)
          this.$emit('change', this.attachments)
        })
        .catch((e) => {
          this.getFileList()
          throw e
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.contain {
  :global(.spin-content) {
    padding: 30px;
    background-color: $alert-info-bg-color;
    border: 1px solid $alert-info-border-color;
  }
}
.uploadbtn {
  > * {
    display: inline-block;
    margin-right: 10px;
  }

  position: relative;
  display: inline-block;
}
.buttons:empty {
  display: none;
}
.checked {
  :global(.ant-upload-list-item-list-type-picture-card) {
    border: 2px solid $primary-5;
  }
}
</style>
