<template>
  <div class="w-full h-full bg-white p-4">
    <p class="font-bold text-lg leading-10 border-b-2">订单项次列表</p>
    <el-form class="pt-4" :inline="true" :model="formState">
      <el-form-item label="产品编码">
        <el-input v-model="formState.productCode" placeholder="产品编码"></el-input>
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="formState.customerName" placeholder="客户名称"></el-input>
      </el-form-item>
      <el-form-item label="订单编码">
        <el-input v-model="formState.orderCode" placeholder="订单编码"></el-input>
      </el-form-item>
      <el-form-item label="订单项次">
        <el-input v-model="formState.orderItemNo" placeholder="订单项次"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onQuery">查询</el-button>
        <el-button type="info" @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="">
      <vxe-table
        ref="xTable"
        size="small"
        min-height="460"
        border
        :loading="loading"
        :data="tableData"
      >
        <vxe-column type="expand" title="尺码" width="120">
          <template #default>尺码信息</template>
          <template #content="{ row }">
            <div style="padding: 10px">
              <vxe-table :data="row.sizeList" size="mini" max-height="300px" style="width: 300px">
                <vxe-column field="size" title="尺码"></vxe-column>
                <vxe-column field="num" title="尺码数量"></vxe-column>
              </vxe-table>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="orderNo" title="订单编码" width="120"></vxe-column>
        <vxe-column field="rowNo" title="项次行" width="120"></vxe-column>
        <vxe-column field="brandName" title="品牌名称" width="180"></vxe-column>
        <vxe-column field="customerName" title="客户名称" width="240"></vxe-column>
        <vxe-column field="productType" title="产品类型" width="120"></vxe-column>
        <vxe-column field="productCode" title="产品编码" width="120"></vxe-column>
        <vxe-column field="productName" title="产品名称" width="240"></vxe-column>
        <vxe-column title="解析" width="100">
          <template #default="{ row }">
            <el-button v-if="!!row.varOrderFileId" type="text" size="small" @click="toRun(row)"
              >执行解析</el-button
            >
          </template>
        </vxe-column>
        <vxe-column title="操作" width="240">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleImportVar(row)">上传变量</el-button>
            <el-button type="text" size="small" @click="handleShowVarRun(row)">查看解析</el-button>
            <el-button type="text" size="small" @click="handleCheckOrder(row)">检查</el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <vxe-pager
        size="small"
        background
        v-model:current-page="formState.currentPage"
        v-model:page-size="formState.pageSize"
        :total="formState.total"
        @page-change="onQuery"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']"
      >
      </vxe-pager>
    </div>

    <vxe-modal
      v-model="importVisible"
      title="导入"
      width="500px"
      show-footer
      @hide="imporModalHide"
      :z-index="1000"
    >
      <el-form ref="importFormInstance" :model="importForm">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="importForm.customerName" disabled />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="importForm.productName" type="textarea" disabled />
        </el-form-item>
        <el-form-item label="文件" prop="filePath">
          <el-upload
            action=""
            ref="upload"
            accept=".xlsx,.xls"
            :on-remove="handleRemove"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :limit="9"
            :on-change="changeUpload"
          >
            <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>
      <template #footer>
        <el-button @click="importVisible = false">取消</el-button>
        <el-button type="primary" @click="submitImport">执行解析</el-button>
      </template>
    </vxe-modal>

    <TemplateVariable v-model:visible="tempVisible" v-bind="detailVariable" @download="download" />
    <CheckOrder ref="checkOrderRef" />
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  apiOrderVarPage,
  apiOrderVarGetVars,
  apiOrderVarGetOrderNewVars,
  apiOrderVarSaveUpload,
  apiOrderVarRun,
  getCheckOrder
} from '@/api/var'
import type { VxeTableInstance } from 'vxe-table'
import TemplateVariable from './components/TemplateVariable.vue'
import { filterVarData } from '@/utils/excel'
import { uploadFile } from '@/api/excel'
import { ElLoading, ElMessage } from 'element-plus'
import { exportExcel } from '@/utils/export-excel'
import type { BookType } from 'xlsx'
import CheckOrder from './components/CheckOrder.vue'

const loading = ref(false)
const formState = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  productCode: '',
  customerName: '',
  orderCode: '',
  orderItemNo: ''
  // column: 'createTime',
  // order: 'desc'
})

const checkOrderRef = ref()
const xTable = ref<VxeTableInstance>()

const tableData = ref([])

const tempVisible = ref(false)
const detailVariable = ref({
  title: '变量文件解析',
  titles: [],
  data: [],
  errors: []
})
const currentRow = ref()
const handleShowVarRun = async (row: any) => {
  currentRow.value = row
  const { data } = await apiOrderVarGetOrderNewVars(row.orderItemId)
  if (data?.code === 500) {
    return ElMessage.error(data.message || '操作失败！')
  }
  const { res, titles } = filterVarData(data.result.varOrders || [])

  detailVariable.value.titles = titles as any
  detailVariable.value.data = res as any
  detailVariable.value.errors = data.result?.errors || []
  nextTick(() => {
    tempVisible.value = true
  })
}

const importVisible = ref(false)
const importForm = ref({
  customerName: '',
  productName: '',
  productCode: '',
  customerId: '',
  orderItemId: '',
  filePaths: []
})
const handleImportVar = async (row) => {
  importForm.value.customerName = row.customerName
  importForm.value.productName = row.productName
  importForm.value.customerId = row.customerId
  importForm.value.productCode = row.productCode
  importForm.value.orderItemId = row.orderItemId
  importVisible.value = true
}
const imporModalHide = () => {
  importForm.value.filePaths = []
}
const handleRemove = (file) => {
  importForm.value.filePaths = importForm.value.filePaths.filter((item) => item.uid !== file.uid)
}
const handleExceed = () => {}
const changeUpload = (file: any) => {
  const loading = ElLoading.service({
    text: '上传中...',
    background: 'rgba(0, 0, 0, 0.7)',
    lock: true,
    spinner: 'el-icon-loading'
  })
  const formData = new FormData()
  formData.append('file', file.raw)
  console.log(file, 'file')
  uploadFile(formData).then(({ data }) => {
    loading.close()
    if (data?.code === 200) {
      importForm.value.filePaths.push({ uid: file.uid, path: data.message })
    } else {
      return ElMessage.error('上传失败！')
    }
  })
}
const toRun = async (row) => {
  const loading = ElLoading.service({
    text: '解析中...',
    background: 'rgba(0, 0, 0, 0.7)',
    lock: true,
    spinner: 'el-icon-loading'
  })
  try {
    const { data } = await apiOrderVarRun(row.orderItemId)
    loading.close()
    if (data?.code == '200') {
      ElMessage.success(data.message || '解析成功！')
      importVisible.value = false
      onQuery()
      nextTick(() => {
        handleShowVarRun(row)
      })
    } else {
      ElMessage.error(data.message || '解析失败！')
    }
  } catch {
    nextTick(() => {
      loading.close()
    })
  }
}
const submitImport = async () => {
  const params = {
    ...importForm.value,
    filePaths: importForm.value.filePaths.map((item) => item.path)
  }
  await apiOrderVarSaveUpload(params)
  const { data } = await apiOrderVarRun(importForm.value.orderItemId)
  if (data?.code == '200') {
    ElMessage.success(data.message || '解析成功！')
    importVisible.value = false
    onQuery()
    nextTick(() => {
      handleShowVarRun(importForm.value)
    })
  } else {
    ElMessage.error(data.message || '解析失败！')
  }
}

const download = (type: BookType = 'xlsx') => {
  exportExcel(detailVariable.value.data, type, `${currentRow.value.orderNo}.${type}`)
}

const onReset = () => {
  formState.currentPage = 1
  formState.productCode = ''
  formState.customerName = ''
  formState.orderCode = ''
  formState.orderItemNo = ''
  onQuery()
}

const handleCheckOrder = async (row) => {
  const { data } = await getCheckOrder(row.orderItemId)

  if (data?.code == 500) {
    return ElMessage.error(data?.message || data?.msg || '检查出错！')
  }
  if (data.result?.success) {
    ElMessage.success('检查无误！')
  } else {
    checkOrderRef.value.openModal(data.result.errors)
  }
}

const onQuery = async () => {
  loading.value = true
  try {
    const { data } = await apiOrderVarPage(formState)
    tableData.value = data.result.records
    formState.total = +data.result.total
  } catch {}
  loading.value = false
}

onMounted(() => {
  onQuery()
})
</script>
<style lang="scss" scoped></style>
