<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>
          </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" />
  </div>
</template>

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

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

const xTable = ref<VxeTableInstance>()

const tableData = ref([])

const tempVisible = ref(false)
const detailVariable = ref({
  title: '变量文件解析',
  titles: [],
  data: []
})
const currentRow = ref()
const handleShowVarRun = async (row: any) => {
  currentRow.value = row
  const { data } = await apiOrderVarGetNewVars(row.orderItemId)
  const { res, titles } = filterRunData2(data.result || [], false)

  detailVariable.value.titles = titles
  detailVariable.value.data = res
  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 formData = new FormData()
  formData.append('file', file.raw)
  console.log(file, 'file')
  uploadFile(formData).then(({ data }) => {
    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 = () => {
  exportExcel(detailVariable.value.data, `${currentRow.value.orderNo}.xlsx`)
}

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

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>
