<script setup lang="ts">
import { useAttrs, ref, getCurrentInstance, watch, computed, inject } from 'vue'
import { usePropBind, getFormInstance } from './common'
import GdFormItem from './GdFormItem.vue';
import {
  downloadApplyFile
} from '@/api/workflowManagement';
import { createDownloadFile } from '@/utils/exportExcel';
import key from '@/constant/key';
import Cookies from 'js-cookie';
import { ElMessageBox } from 'element-plus'
import { getToken } from "@/utils/auth";

// const { VITE_BASE_URL } = import.meta.env
const { VITE_APP_BASE_API } = import.meta.env
const $t: any = getCurrentInstance()?.appContext.config.globalProperties.$t
const form: any = getFormInstance()
const disabled = computed(() => form.props.disabled)
const currentFile = inject("currentFile")
const previewable = inject("previewable")

const props = withDefaults(defineProps<{
  label: string,
  rules?: [],
  previewable?: boolean
  formId: string,
  i_apply_id: string
}>(), { label: '', previewable: true })

const emit = defineEmits<{
  (e: 'preview', name: string): void
  (e: 'change', name: string): void
}>();

const { propValue, handleChange } = usePropBind()
const attrs = <any>useAttrs()

const i_form_id = computed(() => props.formId ? props.formId.toString() : '')
const i_apply_id = computed(() => props.i_apply_id ? props.i_apply_id.toString() : '')

// const uploadData = computed(() => {
//   const i_language= localStorage.getItem(key.languageKey)
//   const login_user= Cookies.get(key.user)
//   const i_form_id = props.formId ? props.formId : ''
//   const i_apply_id = props.i_apply_id ? props.i_apply_id : ''
//   return { i_language, login_user, i_form_id, i_apply_id }
// })

const uploadData = {
  i_language: localStorage.getItem(key.languageKey),
  login_user: Cookies.get(key.user),
  // i_key: '',
  i_form_id: i_form_id.value,
  i_apply_id: i_apply_id.value,
  applyPass : 'false'
} as Record<string, any>

const fileList = ref<any[]>([])
watch(propValue, () => {
  const value = propValue.value

  if (value && value.split('|').length !== fileList.value.length) {
    fileList.value = value.split('|').map((fullName: string) => {
      var filename = fullName.slice(0, fullName.lastIndexOf('_'))
      filename = filename.slice(0, filename.lastIndexOf('_'))+ fullName.slice(fullName.lastIndexOf('.'))
      return {
        uid: fullName,
        name: filename,
        status: 'success',
        response: {
          i_file_name: filename,
          i_file_name_new: fullName
        }
      }
    })
  }
}, { immediate: true })
const handleFileListChange = (file: any, files: any) => {
  if (file?.status === 'success') {
    handlePreview(file)
  }
  const value = files
    .filter((item: any) => item.status === 'success' && item.response)
    .map((item: any) => item.response.i_file_name_new)
    .join('|')
  handleChange(value)
  emit('change', value)
  form.exposed.validateField([attrs.prop])
}
const handleRemove = (file: any) => {
  ElMessageBox.confirm(
    `${$t('common_0070')}`,
  ).then(
    () => {
      const index = fileList.value.map(item => item.uid).indexOf(file.uid)
      fileList.value.splice(index, 1)
      handleFileListChange(null, fileList.value)
      emit('preview', '');
      return true;
    },
    () => false,
  );
}
const handlePreview = (file: any) => {
  emit('preview', file?.response?.i_file_name_new || '');
}
const handleDownload = async (file: any) => {
  const res: any = await downloadApplyFile({
    i_file_name_new: file.response.i_file_name_new,
    i_form_id: i_form_id.value,
    i_apply_id: i_apply_id.value
  });
  createDownloadFile(res);
}
const checkPreviewable = (file: any) => {
  const fullName = file.response.i_file_name_new
  return ['.pdf', '.png', '.jpg'].includes(fullName?.slice(fullName.lastIndexOf('.')))
}

const headers = ref({ Authorization: "Bearer " + getToken() });
</script>

<template>
  <GdFormItem :label="label" :rules="props.rules">
    <!-- <el-upload v-model:file-list="fileList" :action='`${VITE_BASE_URL}/ashx/upload.ashx`' :data='uploadData' -->
    <!-- :on-change="handleFileListChange" v-bind="attrs" class='w-full'> -->
    <el-upload v-model:file-list="fileList" :action='`${VITE_APP_BASE_API}/fileTransfer/upload`' :data='uploadData'
      :on-change="handleFileListChange" v-bind="attrs" class='w-full' :headers="headers">
      <el-button type='primary' v-if="!attrs.viewerMode">{{ $t('Upload') }}</el-button>
      <template #file="{ file }">
        <div class="el-upload-list__item-info" style="width: calc(100% - 70px);">
          <a class="el-upload-list__item-name">
            <el-icon class="el-icon el-icon--document" style="top:0px">
              <Document />
            </el-icon>
            <span class="el-upload-list__item-file-name">
              {{ file.name }}
            </span>
          </a>
          <el-progress v-if="file.status === 'uploading'" :type="'line'" :stroke-width="2"
            :percentage="Number(file.percentage)" :style="'margin-top: 0.5rem'" />
        </div>


        <el-icon class="el-icon mr-2" style="cursor: pointer;"
          v-if="previewable && props.previewable && file.response && checkPreviewable(file)"
          @click="handlePreview(currentFile === file.response.i_file_name_new ? '' : file)">
          <View v-if="currentFile === file.response.i_file_name_new" />
          <Hide v-else />
        </el-icon>

        <span v-else class="mr-5" />
        <el-icon class="el-icon" style="cursor: pointer;" v-if="file.response" @click="handleDownload(file)">
          <Download />
        </el-icon>
        <div class="close-icon" v-if="!disabled" style="top:3px">
          <label class="el-upload-list__item-status-label">
            <el-icon class="el-icon el-icon--upload-success el-icon--circle-check">
              <circle-check />
            </el-icon>
          </label>
          <el-icon class="el-icon el-icon--close" @click="handleRemove(file)">
            <Close />
          </el-icon>
        </div>
      </template>
    </el-upload>

  </GdFormItem>
</template>

<style>
  .w-full {
    width: 100%;
  }
  .mr-2 {
    margin-right: 0.5rem;
  }
  .mr-5 {
    margin-right: 1.25rem;
  }
</style>