<template>
  <div class="h-full flex flex-col bg-white p-2">
    <p class="font-bold text-lg leading-10 border-b-2">转换订单记录</p>
    <el-form class="pt-2" :model="formState" inline>

      <el-form-item label="订单文件ID">
        <el-input v-model="formState.orderFileId" placeholder="" clearable />
      </el-form-item>

      <el-form-item label="模版文件ID">
        <el-input v-model="formState.templateFileId" placeholder="" clearable />
      </el-form-item>
      <el-form-item label="客户">
        <el-input v-model="formState.customerId_dictText" placeholder="" readonly>
          <template #append>
            <el-button :icon="MoreFilled" @click="visibleModal = true"></el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="创建人">
        <el-input v-model="formState.createby_dict" placeholder="">
          <template #append>
            <el-button :icon="MoreFilled" @click="visibleUserModal = true"></el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="resetForm">重置</el-button>
        <el-button @click="queryConvert" type="primary">查询</el-button>
      </el-form-item>
    </el-form>

    <vxe-toolbar>
      <template #buttons>
        <el-button type="danger" @click="removeRows">删除</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      min-height="460"
      border
      :data="tableData"
      :loading="loading"
      show-overflow="tooltip"
      size="small"
    >
      <vxe-column type="checkbox" width="40"></vxe-column>
      <vxe-column field="orderFileId" title="订单文件ID" width="180">
          <template #default="{ row }">
            <el-link target="_blank" :href="'/preview-excel?fileId=' + row.orderFileId">{{
              row.orderFileId
            }}</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">{{
              row.templateFileId
            }}</el-link>
          </template>
        </vxe-column>
        
      <vxe-column field="customerId_dictText" title="客户名称" width="200"></vxe-column>
      <vxe-column field="filePath" title="订单文件"  width="380">
        <template #default="{ row }">
          <el-link target="_blank" :href="'/preview-excel?path=' + row.filePath">{{
            row.filePath
          }}</el-link>
        </template>
      </vxe-column>
      <vxe-column field="status" title="是否下发" width="80">
        <template #default="{ row }">
          {{ row.status == 'Y' ? '是' : '否' }}
        </template>
      </vxe-column>
      <vxe-column field="createBy_dictText" title="创建人" width="100"></vxe-column>
      <vxe-column field="createTime" title="创建时间" width="200"></vxe-column>
      <vxe-column field="action" title="操作" width="130" :show-overflow="false">
        <template #default="{ row }">
          <el-button type="primary" text size="small" @click="toDetail(row)">查看</el-button>
          <el-button v-if="row.status == 'N'" type="primary" text size="small" @click="resetSend(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="queryConvert"
      :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']"
    >
    </vxe-pager>

    <vxe-modal esc-closable v-model="visible" title="解析详情" width="80%" show-footer>
      <vxe-table
        border
        size="mini"
        height="500"
        show-overflow="tooltip"
        show-header-overflow="tooltip"
        :data="convertData"
      >
        <vxe-column
          width="160"
          v-for="item in tableTitle"
          :title="item"
          :key="item"
          :field="item"
        />
      </vxe-table>
      <template #footer>
        <el-button @click="visible = false">关闭</el-button>
      </template>
    </vxe-modal>


    
    <CustomerModal v-model:visible="visibleModal" @confirm="confirmCustomer" />
    <UserModal v-model:visible="visibleUserModal" @confirm="confirmUser" />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { convertOrderBatchDeleteById, convertOrderPage, convertOrderReSend } from '@/api/order'
import type { VxeTableInstance } from 'vxe-table'
import CustomerModal from '@/components/CustomerModal/CustomerModal.vue'

import { ElMessage } from 'element-plus'
import { MoreFilled } from '@element-plus/icons-vue'

const visibleModal = ref(false)
const visibleUserModal = ref(false)

const loading = ref(false)
const visible = ref(false)
const xTable = ref<VxeTableInstance>()
const tableData = ref([])
const formState = reactive({
  customerId_dictText: '',
  customerId: '',
  orderFileId: '',
  templateFileId:'',
  createBy: '',
  createby_dict: '',
  currentPage: 1,
  pageSize: 10,
  total: 0,
  column: 'createTime',
  order: 'desc'
})

const tableTitle = ref([])
const convertData = ref([])

const toDetail = (row: any) => {
  const titles: string[] = []
  const record = row.orders[0]
  let flatdatas: any = null
  // 获取表头
  for (const key in record) {
    if (key == 'productProperties') {
      if (record[key].length) {
        flatdatas = {}
        record[key].forEach((v) => {
          titles.push(v.productPropertiesTitle)
          flatdatas[v.productPropertiesTitle] = v.productPropertiesValue
        })
      }
    } else {
      titles.push(key)
    }
  }

  tableTitle.value = titles
  convertData.value = row.orders.map((item) => {
    return {
      ...item,
      ...flatdatas
    }
  })
  // 打开弹窗
  visible.value = true
}

const resetSend = async (row: any) => {
  const {data} = await convertOrderReSend(row.convertOrderId)
  if (data.code == 200) {
    ElMessage.success(data.message || '操作成功')
    queryConvert()
  } else {
    ElMessage.error(data.message || '操作失败')
  }
}
const queryConvert = async () => {
  loading.value = true
  try {
    const { data } = await convertOrderPage(formState)
    tableData.value = data.result.records
    formState.total = +data.result.total
  } catch {}
  loading.value = false
}
const resetForm = () => {
  Object.assign(formState, {
    customerId: '',
    customerId_dictText: '',
    createBy: '',
    createby_dict: '',
    templateFileId:'',
    orderFileId: '',
  })
}

const confirmCustomer = (list) => {
  const [item] = list
  if (!item) return
  formState.customerId = item.customerId
  formState.customerId_dictText = item.customerName
}

const confirmUser = (list: any) => {
  const [user] = list
  if (user) {
    formState.createBy = user.userId
    formState.createby_dict = user.nickName
  }
}

const removeRows = async () => {
  const list = xTable.value?.getCheckboxRecords()
  if (list?.length) {
    const ids = list.map((v) => v.convertOrderId).join(',')
    await convertOrderBatchDeleteById(ids)
    ElMessage.success('删除成功')
    queryConvert()
  }
}

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