<template>
  <div class="container m-auto pt-10">
    <el-form ref="formRef" :model="formState" label-width="100px">
      <el-form-item label="客户：">
        <el-input v-model="formState.customerName" disabled>
          <template #append>
            <el-button :icon="MoreFilled" @click="visible = true" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="产品：">
        <!-- <el-input v-model="formState.productName" disabled>
          <template #append>
            <el-button :icon="MoreFilled" @click="prodVisible = true" />
          </template>
        </el-input> -->
        <el-tag
          class="mr-1"
          v-for="prod in selectProdList"
          :key="prod.productCode"
          closable
          size="large"
          :disable-transitions="false"
          @close="handleCloseTag(prod)"
        >
          {{ prod.productName }}
        </el-tag>

        <el-button type="primary" @click="prodVisible = true">选择产品</el-button>
      </el-form-item>

      <el-form-item label="选择文件：">
        <el-upload
          action=""
          accept=".xlsx,.xls"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="changeUpload"
        >
          <el-button type="primary">上传文件</el-button>
          <template #tip>
            <div class="el-upload__tip">选择你要上传的excel文件，仅支持xlsx、xls格式</div>
          </template>
        </el-upload>

        <el-table :data="tableData" border size="small" style="width: 100%">
          <el-table-column prop="filename" label="文件名称" />
          <el-table-column
            prop="filesize"
            label="文件大小"
            :formatter="(r, c, v) => v + ' B'"
            width="180"
          />
          <el-table-column prop="action" label="操作" width="90">
            <template #default="{ $index }">
              <el-button type="danger" size="small" @click="removeFile($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <p class="text-red-600 text-sm mt-2">
          tip：必须通过产品编码进行过滤.如果没有，则需要手动添加一列编码;否则不会进行数据过滤
        </p>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button type="default" @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>

  <CustomerModal v-model:visible="visible" @confirm="confirmCustomer" />
  <MultipleProductModal v-model:visible="prodVisible" :select-prod="selectProdList" @confirm="confirmProduct" />
</template>

<script lang="ts" setup>
import axios from 'axios'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useCommentExcel } from '@/stores/commentExcel'

import { MoreFilled } from '@element-plus/icons-vue'
import CustomerModal from '@/components/CustomerModal/CustomerModal.vue'
import MultipleProductModal from '@/components/ProductModal/MultipleProductModal.vue'
import { apiSaveUpload } from '@/api/varExcel'
import { uploadFile } from '@/api/excel'

const visible = ref(false)
const prodVisible = ref(false)
const formRef = ref()
const tableData = ref([])
const formState = reactive({
  customerName: '',
  customerId: '',
  productName: '',
  productCode: ''
})
const emit = defineEmits(['upload'])
const selectProdList = ref([])

const removeFile = (i: number) => tableData.value.splice(i, 1)

const changeUpload = (file: any) => {
  const formData = new FormData()
  formData.append('file', file.raw)

  uploadFile(formData).then(({ data }) => {
    if (data?.code === 200) {
      tableData.value.push({
        filename: file.name,
        filesize: file.size,
        url: data.message
      })
    } else {
      return ElMessage.error('上传失败！')
    }
  })
}
const confirmProduct = (list: any) => {
  selectProdList.value = list
}
const handleCloseTag = (prod) => {
  selectProdList.value = selectProdList.value.filter(
    (item) => item.productCode !== prod.productCode
  )
}

const confirmCustomer = (list: any) => {
  const [item] = list
  if (!item) return

  formState.customerId = item.customerId
  formState.customerName = item.customerName
}

const submitForm = async () => {
  await formRef.value.validate()

  if (!tableData.value.length) {
    return ElMessage.warning('请选择文件！')
  }
  const params = {
    filePaths: tableData.value.map((item) => item.url),
    customerId: formState.customerId,
    productCode: selectProdList.value.map((v) => v.productCode).join(',')
  }

  apiSaveUpload(params).then(({ data }) => {
    // const { setFileInfo } = useCommentExcel()
    // setFileInfo(data.result)
    emit('upload', data.result)
  })
}

const goBack = () => {
  const router = useRouter()
  router.go(-1)
}
</script>
<style lang="scss" scoped></style>
