<!-- 批量导入数据dialog -->
<template>
  <div>
    <div class="btn_row">
      <el-button type="primary" icon="Upload" @click="show">批量导入</el-button>
      <el-button icon="Download" @click="downloadTemplateAjax">下载银收客模板</el-button>
    </div>
    <el-dialog title="批量导入" width="800px" v-model="visible" :close-on-click-modal="false" :close-on-press-escape="false"
      @close="dialogClose">
      <div class="row">
        <tabHeader v-model="tabActive" :list="tabs" />
      </div>
      <div class="row mt14">
        <div class="import_container" v-if="tabActive == 0">
          <div class="header_title">第一步：选择模板</div>
          <div class="row mt14 pb50">
            <div class="list">
              <div class="item" :class="{ active: platformActive == index }" v-for="(item, index) in platformList"
                :key="item.id" @click="selectPlatform(item)">
                <img class="img" :src="item.img" alt="">
              </div>
            </div>
          </div>
          <div class="header_title">第二步：上传文件
            <span>单次仅可上传一个文件</span>
          </div>
          <div class="row mt14">
            <GfileUpload v-model="form.files" :accept="platformList[platformActive]?.file_type || ''" :limit="1"
              @file-selected="fileSelected" />
          </div>
          <div class="row mt14">
            <div class="footer_wrap">
              <el-button @click="visible = false">取 消</el-button>
              <el-button type="primary" :disabled="!form.files.length" :loading="loading" @click="startImportHandle">
                <template v-if="!form.files.length">请选择文件</template>
                <template v-else>开始导入</template>
              </el-button>
            </div>
          </div>
        </div>
        <el-table :data="tableData" border stripe v-if="tabActive == 1" height="419px">
          <el-table-column prop="file_name" label="文件名称" width="300" />
          <el-table-column prop="created_time" label="导入时间" width="200" />
          <el-table-column prop="status_text" label="导入状态" width="150">
            <template #default="scope">
              <el-tag v-if="scope.row.status == 0" type="info" disable-transitions>待处理...</el-tag>
              <el-tag v-else-if="scope.row.status == 1" type="warning" disable-transitions>处理中...</el-tag>
              <el-tag v-else-if="scope.row.status == 2" type="success" disable-transitions>处理完成</el-tag>
              <el-tag v-else-if="scope.row.status == -1" type="danger" disable-transitions>导入失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="importResult" label="导入结果">
            <template #default="scope">
              <template v-if="scope.row.status == 2">
                <div class="column">
                  <div>
                    <el-text type="success">成功：{{ scope.row.success_num }} 条</el-text>
                  </div>
                  <div>
                    <el-text type="danger">失败：{{ scope.row.fail_num }} 条</el-text>
                  </div>
                </div>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { getplatlist, uploadFile, importlist, downloadTemp } from '@/importDataApi/index.js';
import GfileUpload from '../Upload/GfileUpload.vue';
import tabHeader from '@/views/marketing_center/components/tabHeader.vue';

const props = defineProps({
  type: {
    type: [String, Number],
    default: 3, // 3商品 4台桌区域 5台桌 6会员 7菜品销售统计 8台桌销售统计 9订单销售统计
  },
});

const platformList = ref([]);
const platformActive = ref(0);
function selectPlatform(item) {
  form.value.files = [];
  platformActive.value = platformList.value.findIndex(i => i.id === item.id);
}

const tabs = ref([
  { label: '导入数据', name: 'importData' },
  { label: '导入记录', name: 'importRecord' },
]);

const tabActive = ref(0)

watch(tabActive, (newVal) => {
  if (newVal === 1) {
    getImportRecord();
  }
});

const visible = ref(false);
const loading = ref(false);
const form = ref({
  files: [],
  platform: ''
})

function fileSelected(file) {
  console.log('fileSelected', file);
}

// 开始导入
async function startImportHandle() {
  try {
    form.value.platform = platformList.value[platformActive.value]?.id;
    const formData = new FormData();
    formData.append('file', form.value.files[0].raw);
    formData.append('shop_id', localStorage.getItem('shopId'));
    formData.append('type', props.type);
    formData.append('platform', form.value.platform);
    loading.value = true;
    await uploadFile(formData);
    ElMessage.success('文件上传成功，正在导入数据，请在导入记录中查看导入结果');
    form.value.files = []
    tabActive.value = 1
  } catch (error) {
    console.log(error);
  }
  setTimeout(() => {
    loading.value = false;
  }, 500);
}

// 获取平台列表
async function getPlatformList() {
  try {
    const res = await getplatlist({ plat_type: props.type });
    platformList.value = res;
  } catch (error) {
    console.log(error);
  }
}

// 导入记录
const tableData = ref([]);
async function getImportRecord() {
  try {
    const res = await importlist({ shop_id: localStorage.getItem('shopId') });
    tableData.value = res;
  } catch (error) {
    console.log(error);
  }
}

// 下载模板
async function downloadTemplateAjax() {
  try {
    const res = await downloadTemp({ plat_type: props.type });
    window.open(res, '_blank');
  } catch (error) {
    console.log(error);
  }
}

const emits = defineEmits(['close'])

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

onMounted(() => {
  getPlatformList()
});

function show() {
  visible.value = true;
}

defineExpose({
  show,
});
</script>

<style scoped lang="scss">
.btn_row {
  display: flex;
  gap: 4px;
  margin-left: 14px;
}

.header_title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  display: flex;
  align-items: center;

  span {
    font-size: 12px;
    color: #999999;
    margin-left: 10px;
  }
}

.row {
  &.mt14 {
    margin-top: 14px;
  }

  &.pb50 {
    padding-bottom: 50px;
  }
}

.import_container {
  .list {
    display: flex;
    gap: 24px;

    .item {
      width: 122px;
      height: 42px;
      border: 1px solid #fff;
      border-radius: 4px;
      overflow: hidden;

      &:hover {
        cursor: pointer;
        border-color: var(--el-color-primary);
      }

      &.active {
        border-color: var(--el-color-primary);
      }

      .img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .footer_wrap {
    display: flex;
    gap: 14px;
    justify-content: flex-end;
  }
}

.column {
  display: flex;
  flex-direction: column;
}
</style>