<template>
  <vxe-modal v-model="show" :z-index="1006" @hide="onClose" title="导入" width="600" esc-closable mask-closable
    show-footer>
    <template #default>
      <el-form ref="formRef" :model="form" :rules="rules" label-position="left" label-width="100px">
        <el-form-item label="品牌编码" prop="brandCode">
          <el-input v-model="form.brandCode" disabled>
            <template #append>
              <el-button :icon="MoreFilled" @click="brandVisible = true" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="客户编码" prop="customerCode">
          <el-input v-model="form.customerCode" disabled>
          <template #append>
            <el-button :icon="MoreFilled" @click="customerVisible = true" />
          </template>
        </el-input>
        </el-form-item>

        <el-form-item label="资料类型" prop="informationType">
          <el-input v-model="form.informationType" :disabled="!!route.query.informationType" clearable />
        </el-form-item>
        <el-form-item label="文件" prop="filePath">
          <el-upload action="" ref="uploadRef" accept=".xlsx,.xls" :on-remove="handleRemove" :auto-upload="false"
            :on-exceed="handleExceed" :limit="1" :on-change="handleUpload">
            <el-button type="primary">上传文件</el-button>
            <template #tip>
              <div class="el-upload__tip">选择你要上传的excel文件，仅支持xlsx、xls格式</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-card>
        <template #header>
          <div class="card-header">
            <span>默认字段</span>
          </div>
        </template>
        <el-button type="primary" style="margin-bottom: 12px;" @click="handleAdd">新增</el-button>
        <el-table :data="tableData" border max-height="250" style="width: 100%">
          <el-table-column prop="key" label="字段名称" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.key" />
            </template>
          </el-table-column>
          <el-table-column prop="value" label="字段值" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.value" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template #default="scope">
              <el-button link type="primary" @click="handleDelete(scope.row, scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </template>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onSubmit">确认</el-button>
    </template>
  </vxe-modal>

  <CustomerModal v-model:visible="customerVisible" @confirm="confirmCustomer" />
  <BrandModal v-model:visible="brandVisible" @confirm="confirmBrand" />

</template>

<script lang="ts" setup name="UploadInformationInfoDialog">
import { ref, reactive, watch } from 'vue'
import { useRoute } from 'vue-router'
import { uploadFile } from '@/api/excel'
import { importInformationApi } from '@/api/customer'
import { MoreFilled } from '@element-plus/icons-vue'
import CustomerModal from '@/components/CustomerModal/CustomerModal.vue'
import BrandModal from '@/components/BrandModal/BrandModal.vue'

import { ElMessage, genFileId, type FormInstance, type UploadInstance } from 'element-plus'

const route = useRoute()
const customerVisible = ref(false)
const brandVisible = ref(false)


const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['onImportChange'])

const show = ref(false)
const formRef = ref<FormInstance>()
const form = reactive<any>({
  informationType: "",
  filePath: "",
  defaultJson: ""
})
const rules = reactive({
  informationType: { required: true, message: '请输入资料类型', trigger: 'change' },
  filePath: { required: true, message: '请选择要导入的文件', trigger: 'change' }
})
const uploadRef = ref<UploadInstance>()
const tableData = ref<any>([])

watch(
  () => props.visible,
  (val) => {
    show.value = val
    onReset()
    if (route.query.informationType) {
      form.informationType = route.query.informationType;
    }
  }
)
const confirmCustomer = (list: any) => {
  const [item] = list
  if (!item) return
  form.customerCode = item.customerCode
}

const confirmBrand = (list: any) => {
  const [item] = list
  if (!item) return
  form.brandCode = item.brandCode
}



const importInformation = async () => {
  const temp = tableData.value.reduce((acc: any, cur: any) => {
    acc[cur.key] = cur.value || ''
    return acc
  }, {})
  const params = {
    informationType: form.informationType,
    customerCode:form.customerCode,
    brandCode:form.brandCode,
    filePath: form.filePath,
    defaultJson: temp
  }
  const { data } = await importInformationApi(params)
  if (data?.code == 200) {
    ElMessage.success(`${data?.message}`)
    emits('onImportChange', 'submit')
  } else {
    ElMessage.error(`${data?.message}`)
  }
}

const handleRemove = () => {
  form.filePath = ''
}

const handleExceed = (files: any) => {
  uploadRef.value!.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

const handleUpload = (file: any) => {
  const formData = new FormData()
  formData.append('file', file.raw)
  uploadFile(formData).then(({ data }) => {
    if (data?.code === 200) {
      form.filePath = data.message
    } else {
      return ElMessage.error('上传失败！')
    }
  })
}

const handleAdd = () => {
  tableData.value.push({})
}

const handleDelete = (row: any, index: any) => {
  tableData.value.splice(index, 1)
}

const onReset = () => {
  if (formRef?.value) {
    formRef?.value.resetFields()
  }
  tableData.value = []
}

const onSubmit = () => {
  importInformation()
}

const onClose = () => {
  emits('onImportChange', 'close')
}

</script>

<style lang="scss" scoped></style>