<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 label="工单号">
        <el-input v-model="formState.workOrderCode" placeholder="工单号"></el-input>
      </el-form-item>
      <el-form-item label="SAP订单编号">
        <el-input v-model="formState.sapOrderNo" placeholder="SAP订单编号"></el-input>
      </el-form-item>
      <el-form-item label="订单变量文件ID">
        <el-input v-model="formState.varOrderFileId" placeholder="订单变量文件ID"></el-input>
      </el-form-item>
      <el-form-item label="模板文件ID">
        <el-input v-model="formState.templateFileId" placeholder="模板文件ID"></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="{row}">
            {{row.sizeListDto.sizeList!==null?'尺码信息':'无尺码'}}
          </template>
          <template #content="{ row }">
            <div style="width: 1024px"  v-if="row.sizeListDto!=null">
            <el-row>
              <el-col :span="24">
                <el-table
                :data="[{}]" size="small"
                border
                style="width: 100%">
                  <el-table-column
                   v-for="(value,key) in row.sizeListDto.referNameJson"
                    :prop="key"
                    :label="key"
                   >
                    <template #default="{ row }">
                            {{ value }}
                        </template>
                  </el-table-column>
              </el-table>
              </el-col>
            </el-row>
            <el-row>

              <el-col :span="24" v-if="row.sizeListDto.sizeList">
                  <vxe-table :data="row.sizeListDto.sizeList" size="mini" max-height="400px" align="center">
                    <vxe-column field="size" title="尺码" width="100"></vxe-column>
                    <vxe-column field="num" title="尺码数量" width="100"></vxe-column>
                    <vxe-column field="lossNum" title="loss" width="100"></vxe-column>
                    <vxe-column field="sampleNum" title="样品数" width="100"></vxe-column>
                    <vxe-colgroup title="全码对照" v-if="row.sizeListDto.referTitles.length>0">
                      <vxe-column   v-for="(title) in row.sizeListDto.referTitles"   :title="title">
                        <template #default="{ row }">
                            {{row.sizeRefer==null?null: row.sizeRefer[title]}}
                        </template>
                    </vxe-column>
                   </vxe-colgroup>
                  </vxe-table>
              </el-col>
            </el-row>
          </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="sapOrderNo" title="SAP订单编码" width="120"></vxe-column>
        <vxe-column field="workOrderCode" 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="clientCmd" title="客户指令号" width="120"></vxe-column>
        <vxe-column field="poNo" title="PO" width="120"></vxe-column>
        <vxe-column field="typeNo" title="型体" width="120"></vxe-column>
        <vxe-column field="colorNo" title="配色" width="120"></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 field="varOrderFileId" title="订单变量文件ID" width="180">
          <template #default="{ row }">
          <el-link target="_blank" :href="'/preview-excel?filePath=' + row.varOrderFileId_dictText+ '&type=var'">
              {{ row.varOrderFileId }}
          </el-link>
          </template>
        </vxe-column>
        <vxe-column field="templateFileId" title="模板文件ID" width="180">
          <template #default="{ row }">
          <el-link target="_blank" :href="'/preview-excel?fileId=' + row.templateFileId + '&type=var'">
              {{ row.templateFileId }}
          </el-link>
          </template>
        </vxe-column>

        <vxe-column title="配置的模板ID" width="180">
          <template #default="{ row }">
            <el-link
              v-for="item in row.varTemplateFileIds"
              :key="item"
              target="_blank"
              :href="'/preview-excel?fileId=' + item + '&type=var'"
              >{{ item }}</el-link>
          </template>
        </vxe-column>

        <vxe-column field="varStatus_dictText" title="变量状态" width="120"></vxe-column>
        <vxe-column title="解析" width="100">
          <template #default="{ row }">
            <el-button v-if="!!row.varOrderFileId&&row.varStatus != 'confirm'" type="text" size="small" @click="toRun(row)"
              >执行解析</el-button
            >
          </template>
        </vxe-column>
        <vxe-column title="操作" width="240">
          <template #default="{ row }">
            <el-button v-if="row.varStatus != 'confirm'"  type="text" size="small" @click="handleImportVar(row)">上传变量</el-button>
            <el-button v-if="row.varStatus == 'converted'" type="text" size="small" @click="hanldeConfirmVar(row)">确认</el-button>
            <el-button  v-if="row.varStatus == 'confirm'" type="text"   size="small" @click="hanldeCancel(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="900px"
      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-item label="订单项次" prop="orderItems">
          <el-button @click="chooseOrderItemVisible =true">选择项次</el-button>
          <el-input v-model="importForm.orderItems" type="textarea" disabled />
        </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" />
    <!-- <ChooseOrderItem v-model:visible="chooseOrderItemVisible"  /> -->

    <CheckOrder ref="checkOrderRef" />
  </div>
</template>

<script lang="ts" setup>

import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  apiOrderVarPage,
  apiOrderVarGetVars,
  apiOrderVarGetOrderNewVars,
  confirmVar,
  cancelVar,
  apiOrderVarSaveUpload,
  apiOrderVarRun,
  getCheckOrder
} from '@/api/var'
import type { VxeTableInstance } from 'vxe-table'
import TemplateVariable from './components/TemplateVariable.vue'
import ChooseOrderItem from './components/ChooseOrderItem.vue'

import { filterVarData } from '@/utils/excel'
import { uploadFile } from '@/api/excel'
import { ElLoading, ElMessage ,ElMessageBox} from 'element-plus'
import { exportExcel } from '@/utils/export-excel'
import type { BookType } from 'xlsx'
import CheckOrder from './components/CheckOrder.vue'
import { spawn } from 'child_process'

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

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

const tableData = ref([])

const tempVisible = ref(false)
const chooseOrderItemVisible = ref(false)
const detailVariable = ref({
  title: '变量文件解析',
  titles: [],
  data: [],
  errors: []
})
const currentRow = ref()
const handleShowVarRun = async (row: any) => {
  loading.value = true
  currentRow.value = row
  const { data } = await apiOrderVarGetOrderNewVars(row.orderItemId)
  if (data?.code === 500) {
    loading.value = false
    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(() => {
    loading.value = false
    tempVisible.value = true

  })
}

const hanldeConfirmVar = async (row: any) => {
 await ElMessageBox.confirm('是否确认转换后的变量？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const { data } = await confirmVar(row.orderItemId)
    if (data.code == 200) {
      ElMessage.success(data.message || '操作成功！')
    } else {
      ElMessage.error(data.message || '操作失败！')
    }
  onQuery()
}

const hanldeCancel = async (row: any) => {
 await ElMessageBox.confirm('是否撤回已确认的变量？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const { data } = await cancelVar(row.orderItemId)
    if (data.code == 200) {
      ElMessage.success(data.message || '操作成功！')
    } else {
      ElMessage.error(data.message || '操作失败！')
    }
  onQuery()
}






const importVisible = ref(false)
const importForm = ref({
  customerName: '',
  productName: '',
  productCode: '',
  customerId: '',
  orderItemId: '',
  orderItems:[],
  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 = () => {
  // console.log("关闭")
  importForm.value.customerName = ''
  importForm.value.productName = ''
  importForm.value.customerId = ''
  importForm.value.productCode = ''
  importForm.value.orderItemId = ''
  importForm.value.orderItems = []
  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 = '',
  formState.varOrderFileId='',
  formState.templateFileId='',
  formState.workOrderCode='',
  formState.sapOrderNo=''
  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>
