<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="750px"
      title="Upload Statement"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <div
        v-loading="loading"
        class="flex start"
      >
        <el-form
          ref="mainForm"
          :rules="formRule"
          class="flex-auto"
          :model="form"
          label-width="150px"
        >
          <el-form-item
            label="Statement Name"
            prop="statement_name"
          >
            <el-input
              v-model="form.statement_name"
              style="width: 190px"
              type="textarea"
              rows="3"
            />
          </el-form-item>

          <el-form-item label="Currency">
            <el-select v-model="form.currency">
              <el-option
                v-for="option in currencyList as IOptionItem[]"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="Payment Type">
            <el-select v-model="form.paymentType">
              <el-option
                v-for="option in paymentOption"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="Upload Mode">
            <el-select v-model="form.mode">
              <el-option
                v-for="option in uploadOption"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div
          class="flex-auto drag-area"
          @dragenter="stop"
          @dragover="stop"
          @dragleave="stop"
          @drop="processExcel"
        >
          <label for="fileInput">
            <div
              class="flex column stretch"
              style="text-align: center; padding: 44px 20px; cursor: pointer"
            >
              <div>
                <el-icon
                  size="60px"
                  color="#999"
                >
                  <upload-filled />
                </el-icon>
              </div>
              <br />

              <div class="el-upload__text">拖动文件到这或者点击选择</div>
              <br />
              <div class="el-upload">
                单个Excel数据最好控制在100行内, 处理起来会慢
              </div>
              <br>
              <div
                v-if="tableData.length"
                style="color: green"
              >
                读取文件成功!
              </div>
            </div>
          </label>
        </div>
      </div>
      <br />
      <div class="flex end">
        <el-button
          :loading="loading"
          @click="handleClose"
        >
          关闭
        </el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="next(mainForm)"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
    <!-- multiple -->
    <input
      id="fileInput"
      type="file"
      style="display: none"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      @change="processExcel"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'DialogUploadExcel',
})
</script>
<script lang="ts" setup>
import { watchEffect, ref } from 'vue'
import {
  ElDialog,
  ElMessage,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElButton,
  ElIcon,
} from 'element-plus'

import { UploadFilled } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import type { FormInstance, FormRules } from 'element-plus'
import { IPoItem, IOptionItem } from '../inteface'
import request from '@/utils/axios'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  currencyList: {
    type: Array,
    default: () => {
      return []
    },
  },
})

const emit = defineEmits(['update:visible', 'update-table-data'])

const dialogVisible = ref(false)

watchEffect(() => {
  dialogVisible.value = props.visible
})

const tableData = ref([] as IPoItem[])

const handleClose = function (done: any) {
  emit('update:visible', false)
  tableData.value = []
  form.value = {
    statement_name: '',
    currency: 'CNY',
    mode: 'Replace',
    paymentType: '货款',
  }
  const target = document.getElementById('fileInput') as HTMLInputElement
  if (target) {
    target.value = ''
  }

  if (typeof done === 'function') {
    done()
  }
}
const mainForm = ref<FormInstance>()
const formRule = ref<FormRules>({
  statement_name: {
    required: true,
    message: '必填项',
    trigger: 'blur',
  },
})
const form = ref({
  statement_name: '',
  currency: 'CNY',
  mode: 'Replace',
  paymentType: '货款',
})
const uploadOption = [
  {
    label: '追加(Append)',
    value: 'Append',
  },
  {
    label: '替换(Replace)',
    value: 'Replace',
  },
]

const paymentOption = [
  {
    label: '货款',
    value: '货款',
  },
  {
    label: '快递款',
    value: '快递款',
  },
]

const stop = (e: any) => {
  e.preventDefault()
  e.stopPropagation()
}
const processExcel = (event: any) => {
  const files = event.target.files || event.dataTransfer.files
  // console.log('files:', files)
  let str = ''
  let arr: IPoItem[] = []
  tableData.value = []
  try {
    for (let i = 0; i < files.length; i++) {
      if (
        ![
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'application/vnd.ms-excel',
        ].includes(files[i].type)
      ) {
        ElMessage.error('读取数据出错, 请确认选择了正确的Excel文件')
        return
      }
      str =
        str +
        `${str.length ? ', ' : ''}` +
        (files[i].name.replace(/\.xlsx?/, '') || 'unNameFile')
      const fileReader = new FileReader()

      fileReader.onload = (e: any) => {
        const data = XLSX.read(e.target.result, { type: 'binary' })
        // 重命名列名
        data.Sheets[data.SheetNames[0]].A1.w = 'po_number'
        data.Sheets[data.SheetNames[0]].B1.w = 'sku'
        data.Sheets[data.SheetNames[0]].C1.w = 'description'
        data.Sheets[data.SheetNames[0]].D1.w = 'unit_price'
        data.Sheets[data.SheetNames[0]].E1.w = 'quantity'
        data.Sheets[data.SheetNames[0]].F1.w = 'sample_fee'
        data.Sheets[data.SheetNames[0]].G1.w = 'setup_service_fee'
        data.Sheets[data.SheetNames[0]].H1.w = 'total'

        const jsonData = XLSX.utils.sheet_to_json(
          data.Sheets[data.SheetNames[0]],
        ) as IPoItem[]
        jsonData.forEach((i) => {
          tableData.value.push(i)
        })
        // tableData.value = tableData.value.concat(jsonData)
      }

      fileReader.readAsBinaryString(files[i])
    }

    form.value.statement_name = str
  } catch (error) {
    console.log('处理文件出错:', error)
  }

  event.preventDefault()
  event.stopPropagation()
}
const loading = ref(false)
const next = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      request
        .post('/payment_request/createStatementData', [
          {
            Name: form.value.statement_name,
          },
        ])
        .then((response) => {
          if (response.data.code !== 1) return
          const res = response.data.result

          let result = {
            mode: form.value.mode,
            data: tableData.value.map((i) => {
              return {
                ...i,
                po_number: i.po_number.toUpperCase(),
                payment_type: form.value.paymentType,
                statement_name: form.value.statement_name,
                currency: form.value.currency,
                statement_id: res.data[0].details.id,
              }
            }),
          }
          emit('update-table-data', result)
          handleClose(false)
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      console.log('check form has not pass!', fields)
      ElMessage.error('请检查表单必填项')
    }
  })
}
</script>

<style lang="scss" scoped>
.drag-area {
  height: 240px;
  border: 1px solid #ddd;
  border-radius: 4px;
  // padding: 24px;
}
</style>
