<template>
  <div class="upload-main-box">
    <el-upload ref="upload" class="upload-main" drag :auto-upload="false" :on-change="uploadChange" :limit="1"
      :on-exceed="handleExceed" :show-file-list="false">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖动文件到此处 或者<em> 点击上传</em></div>
      <template #tip>
        <div class="tips-box">
          <div class="el-upload__tip">仅支持上传 .xlsx, .xls, .csv 格式的文件</div>
          <el-link type="primary" @click="handleDownloadTemplate">点击此处下载导入模版文件</el-link>
        </div>
      </template>
    </el-upload>
  </div>
</template>

<script setup>
import * as XLSX from 'xlsx'
import { genFileId } from 'element-plus'
import { readFile } from '@/utils/readFile'
import { getSession } from '@/utils/auth'
import useCustomerManage from 'store/modules/customerManage'
import { isContact } from '@/utils/validate'
import _ from 'lodash'

const { proxy } = getCurrentInstance()
const importState = inject('importState')
const dictsDataParent = inject('dictsDataParent')
const upload = ref(null)
const customerManageStore = useCustomerManage()

const uploadChange = async (file) => {
  importState.tableData = []
  importState.tableLoading = true
  let dataBinary = await readFile(file.raw)
  let workBook = XLSX.read(dataBinary, { type: 'binary', cellDates: true })
  let workSheet = workBook.Sheets[workBook.SheetNames[0]]
  const data = XLSX.utils.sheet_to_json(workSheet)
  const arr = []
  const phoneNumArr = []
  const phoneValidate = []

  data.forEach((item) => {
    arr.push({
      i_customer_name: item['客户姓名'],
      i_customer_lxdh: item['联系方式'],
      i_customer_source: item['客户来源'],
      i_customer_bz: item['备注'],
      i_customer_gs: getSession('user_gs'),
      i_customer_gsrybm: getSession('user_bm'),
      // i_customer_gsry: item['关联员工'],
    })
    phoneNumArr.push(item['联系方式'])
  })

  const checkData = (arr) => {
    var duplicates = [];
    // 遍历电话号码数组
    for (var i = 0; i < arr.length; i++) {
      // 检查当前电话号码是否出现过
      if (arr.indexOf(arr[i]) !== i && duplicates.indexOf(arr[i]) === -1) {
        // 如果是重复的电话号码，则将其添加到重复数组中
        duplicates.push(arr[i]);
      }

      phoneValidate.push(isContact(arr[i]))
    }

    return duplicates
  }

  // 1.检查当前导入的数据中是否有重复的信息（电话）
  const innerRegRes = checkData(phoneNumArr)
  if (innerRegRes.length) {
    proxy.$modal.confirm(`导入的列表中存在【重复的联系方式】，请检查！`)
    importState.tableData = arr
    importState.tableLoading = false
  }

  // 2.检查电话格式是否正确
  if (phoneValidate.includes(false)) {
    proxy.$modal.confirm(`导入的列表中存在【不正确的联系方式】，请检查！`)
    importState.tableLoading = false
  }

  // 3.调用接口，检查当前导入的数据中是否有重复的信息（电话）
  const { Data } = await customerManageStore.vifLxPhone({ phones: phoneNumArr.join(',') })
  if (Data != null && Data.length) {
    proxy.$modal.confirm(`当前导入的信息中，已在系统中存在相同的联系方式：${Data.join(',')}，请检查！`)
  }

  importState.tableData = arr
  importState.tableLoading = false
}

const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

const handleDownloadTemplate = () => {
  const baseUrlheader = dictsDataParent.value[3][0].substance
  window.open(baseUrlheader + '潜在客户信息批量导入模板.xls', '_blank')
  // const link = document.createElement('a')
  // link.href = baseUrlheader + 'customer_template.xls'
  // link.download = '潜在客户信息批量导入模板.xls' // 自定义文件名
  // link.click() // 下载文件
}
</script>

<style lang="scss" scoped>
:deep(.el-upload-dragger) {
  padding: 20px 10px;
}

.tips-box {
  margin-top: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}
</style>
