<template>
  <div class="comp-content">
    <el-drawer
      v-model="visible"
      :title="`${currentRow?.id ? '编辑' : '新增'}应用`"
      :size="400"
      :close-on-click-modal="false"
      @close="closeFun"
    >
      <div class="content" v-loading="loading">
        <TableForm ref="tableFormRef" :tableName="tableName" />

        <div class="pic-content" ref="appNameRef" v-show="appName">
          <appNameBg :app-name="appName"></appNameBg>
        </div>
      </div>
      <template #footer>
        <div>
          <el-button @click="closeFun">关闭</el-button>
          <el-button type="primary" @click="submitFun">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
import TableForm from '@/components/common/table/tableForm.vue';
import appNameBg from '@/views/task/appCenter/components/appNameBg.vue';
import html2canvas from 'html2canvas';
import { dataUploadAvatarApi } from '@/api/data/data';
import { delayTime } from '@/utils/common';
import { cloneDeep } from 'lodash-es';

const props = defineProps(['currentAppInfo', 'tableName']);
const emit = defineEmits(['cancel', 'submit']);
const currentRow = ref<any>({});
const tableFormRef = ref();
const visible = ref(true);
const appName = ref('');
const appNameRef = ref();
const loading = ref(false);
const closeFun = () => {
  emit('cancel');
};

const submitFun = async () => {
  loading.value = true;
  await delayTime(2000);
  const valid = await tableFormRef.value.validateFun();
  if (valid) {
    const fromData = tableFormRef.value.getFormDataFun();
    const appImage: any = fromData.appImage;
    // 判断是否上传了图片
    if (!appImage) {
      appName.value = fromData.appName;
      nextTick(async () => {
        const ids = await updatePngFun(fromData.appName);
        fromData.appImage = ids;
        emit('submit', fromData);
      });
    } else {
      emit('submit', fromData);
    }
  }
  loading.value = false;
};

const updatePngFun = async (name: any) => {
  try {
    const content = appNameRef.value;
    const canvas = await html2canvas(content);
    const imgData = canvas.toDataURL('image/png');
    // 将DataURL转换为Blob对象
    const blob: any = await new Promise((resolve) => {
      const byteString = atob(imgData.split(',')[1]);
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      resolve(new Blob([ab], { type: 'image/png' }));
    });
    const file = new File([blob], name + '.png', { type: 'image/png' });
    const params = {
      avatar: file,
    };
    let avatarId: any = '';
    const res: any = await dataUploadAvatarApi(params);
    if (res && res.code === 200) {
      avatarId = res.data.avatarId;
    }
    return avatarId;
  } catch (error) {
    console.error(error);
    return '';
  }
};

watch(
  () => props.currentAppInfo,
  (newVal) => {
    if (newVal) {
      currentRow.value = cloneDeep(newVal);
      nextTick(() => {
        if (currentRow.value?.id) {
          tableFormRef.value.setFormDataFun(currentRow.value);
        } else {
          tableFormRef.value.resetFun();
        }
      });
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.pic-content {
  width: 80px;
  height: 80px;
  position: relative;
}
</style>
