<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="queryParams">
      <!-- <el-form-item label="文件名称">
        <el-input v-model="queryParams.excelOrderId" placeholder="" clearable />
      </el-form-item> -->
      <el-form-item label="订单文件ID">
        <el-input v-model="queryParams.fileId" placeholder="" clearable />
      </el-form-item>
      <el-form-item label="模版文件ID">
        <el-input v-model="queryParams.templateFileId" placeholder="" clearable />
      </el-form-item>
      <el-form-item label="客户">
        <el-input v-model="queryParams.customerId_dict" placeholder="" readonly>
          <template #append>
            <el-button :icon="MoreFilled" @click="visible = true"></el-button>
          </template>
        </el-input>
      </el-form-item>
      
      <el-form-item label="收单条码">
        <el-input v-model="queryParams.acquiringBarcode" placeholder="" clearable />
      </el-form-item>

      <el-form-item label="订单状态">
        <el-select v-model="queryParams.status" placeholder="" clearable>
          <template v-for="item in statusOptions">
            <el-option :value="item.value" :label="item.label"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryParams.createTime"
          type="daterange"
          value-format="YYYY-MM-DD"
          unlink-panels
          placeholder="选择创建时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="创建人">
        <el-input v-model="queryParams.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 type="default" @click="onReset">重置</el-button>
        <el-button type="primary" @click="onQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <div class="">
      <vxe-toolbar>
        <template #buttons>
          <el-button type="danger" @click="removeRows">删除</el-button>
          <el-button type="primary" @click="importVisible = true">导入</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="xTable"
        size="small"
        min-height="460"
        show-overflow="tooltip"
        border
        :loading="loading"
        :data="tableData"
      >
        <vxe-column type="checkbox" width="50"></vxe-column>

        <vxe-column field="fileId" title="订单文件ID" width="180">
          <template #default="{ row }">
            <el-link target="_blank" :href="'/preview-excel?fileId=' + row.fileId">{{
              row.fileId
            }}</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="fileId_dictText" title="订单文件" minWidth="300">
          <template #default="{ row }">
            <el-link target="_blank" :href="'/preview-excel?fileId=' + row.fileId">{{
              row.fileId_dictText
            }}</el-link>
          </template>
        </vxe-column>

        <vxe-column field="acquiringBarcode" title="收单条码" width="120"></vxe-column>
        <vxe-column field="status_dictText" title="订单状态" width="120"></vxe-column>
        <vxe-column field="createTime" title="创建时间" width="180"></vxe-column>
        <vxe-column field="createBy_dictText" title="创建人" width="180"></vxe-column>
        <vxe-column field="action" title="操作" min-width="280">
          <template #default="{ row }">
            <el-link style="font-size: 12px" type="primary" @click="toDetail(row)">查看</el-link>
            <el-divider direction="vertical"
            v-if="row.status == 'un_convert'|| row.status == 'converted' || row.status == 'un_confirm'"
            ></el-divider>
            <el-link
              class="ml-1"
              style="font-size: 12px"
              type="primary"
              v-if="row.status == 'un_convert'|| row.status == 'converted'||row.status == 'un_confirm'"
              @click="confirmChange(row)"
              >转换</el-link
            >
            <el-divider direction="vertical"
            v-if="row.status == 'converted' || row.status == 'converted'"
            ></el-divider>
            <el-link
              class="ml-1"
              style="font-size: 12px"
              v-if="row.status == 'converted' || row.status == 'converted'"
              type="primary"
              @click="confirmOrderStatus(row)"
              >确认</el-link
            >
            <el-divider direction="vertical"></el-divider>
            <el-link class="ml-1" style="font-size: 12px" type="primary" @click="exportTmp(row)"
              >导出</el-link
            >
            <el-divider direction="vertical"
            v-if="row.status == 'converted' || row.status == 'confirm'"
            ></el-divider>
            <el-link class="ml-1" style="font-size: 12px" type="primary" @click="toSaleOrderDetail(row)"
            v-if="row.status == 'converted' || row.status == 'confirm'"
              >转换后</el-link
            >

          </template>
        </vxe-column>
      </vxe-table>

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

  <vxe-modal v-if="detailVisible" v-model="detailVisible" title="解析详情" width="80%" show-footer>
    <vxe-table
      border
      size="mini"
      height="500"
      show-overflow="tooltip"
      show-header-overflow="tooltip"
      :data="detailTable"
    >

      <!-- 转换下使用 -->
      <vxe-column title="行号" width="120">
        <template #default="{ row }">{{ row.sortNum }}</template>
      </vxe-column>
      <vxe-column title="数据区" width="120">
        <template #default="{ row }">{{ row['数据区'] }}</template>
      </vxe-column>

      <vxe-column title="操作" width="120">
        <template #default="{ row }">
          <el-button type="primary" plain @click="copyOrders(row)">复制订单</el-button>
        </template>
      </vxe-column>

      <!-- 转换下使用 -->
      <template>
        <vxe-colgroup v-for="item in tableTitle" :key="item" :title="item">
          <vxe-column :title="item" :field="item" width="200">
            <template #header>
              <div class="header-cell" @click="(e) => showPopover(e, item)">

                <el-tooltip v-if="showScriptNumber(getAllMapConfigs[item].orderFiledConfs) !=0" class="item" effect="dark" 
                :content="showScriptNames(getAllMapConfigs[item].orderFiledConfs)" placement="top-start">
                   <el-button type="danger" size="small" circle>{{ showScriptNumber(getAllMapConfigs[item].orderFiledConfs) }}</el-button>
                </el-tooltip>

                <template v-for="cf in getAllMapConfigs[item].orderFiledConfs">
                   <span>{{ cf.orderFiled.fliedTitle }}  </span>
                </template>
                <el-icon><Setting /></el-icon>
              </div>
            </template>
          </vxe-column>
        </vxe-colgroup>
      </template>
    </vxe-table>

    <el-popover
      ref="popoverRef"
      placement="bottom"
      :virtual-ref="buttonRef"
      trigger="click"
      :title="currentConfigTitle"
      :visible="popoverVisible"
      virtual-triggering
      width="400"
      transition=""
    >
      <ConfigForm
        :title="currentConfigTitle"
        :current-conf="currentColConf"
        :current-row="currentRow"
        @cancel="popoverVisible = false"
        @confirm="confirmConfig"
      />
    </el-popover>

    <template #footer>
      <el-button type="primary" @click="onCopy">复制</el-button>
      <el-button type="primary" v-if="isCopying" @click="onPaste">引入</el-button>
      <!-- <el-button @click="confirmChange" v-if="currentRow.status == 'un_convert'">确认转换</el-button> -->
      <el-button @click="saveOrderField" type="primary">保存</el-button>
    </template>
  </vxe-modal>

  <vxe-modal
    v-model="importVisible"
    title="导入"
    width="500px"
    show-footer
    @hide="imporModalHide"
    :z-index="1000"
  >
    <el-form ref="importFormInstance" :model="importForm" :rules="importRules">
      <el-form-item label="客户名称" prop="customerId">
        <!-- <el-input v-model="importForm.customerName"></el-input> -->
        <el-input v-model="importForm.customerName" disabled>
          <template #append>
            <el-button :icon="MoreFilled" @click="visible = true" />
          </template>
        </el-input>
      </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="1"
          :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>

  <vxe-modal esc-closable v-model="convertVisible" 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 convertTableTitle"
          :title="item"
          :key="item"
          :field="item"
        />
      </vxe-table>
      <template #footer>
        <el-button @click="convertVisible = false">关闭</el-button>
      </template>
    </vxe-modal>

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

<script lang="ts" setup>
import { onMounted, reactive, ref, watch, nextTick } from 'vue'
import { Setting, MoreFilled } from '@element-plus/icons-vue'
import { cloneDeep } from 'lodash-es'
import {
  confirmExcelFileOrderById,
  convertExcelFileOrder,
  deleteExcelFileOrderById,
  getExcelFileOrderPage,
  getConfByExcelOrderId,
  listSaleOrdersByExcelId,
  saveConfExcelFileOrderPage,
  excelFileOrderExportExcel,
  excelFileOrderImportExcel
} from '@/api/order'
import {
  ElMessage,
  ElMessageBox,
  genFileId,
  type FormInstance,
  type UploadInstance
} from 'element-plus'
import type { VxeTableInstance } from 'vxe-table'
import type { Recordable } from '@/types/global'
import { filterRunData } from '@/utils/excel'
import { apiDictList } from '@/api/common'
import ConfigForm from './components/ConfigForm1.vue'
import { useExcelChangeStore } from '@/stores/excel'
import { storeToRefs } from 'pinia'
import { saveAs } from 'file-saver'
import { uploadFile } from '@/api/excel'
import CustomerModal from '@/components/CustomerModal/CustomerModal.vue'
import UserModal from '@/components/UserModal/UserModal.vue'
import { useOrderChangeCopy } from '@/hooks/useOrderChangeCopy'

const visible = ref(false)
const visibleUserModal = ref(false)
const uploadRef = ref<UploadInstance>()
const importFormInstance = ref<FormInstance>()
const loading = ref(false)
const importVisible = ref(false)
const excelChangeStore = useExcelChangeStore()
const { getAllMapConfigs } = storeToRefs(excelChangeStore)
const { copyInfo, isCopying, handleCopy } = useOrderChangeCopy()

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


/**查询参数 */
const queryParams = reactive({
  status: '',
  fileId:'',
  createTime: '',
  customerId_dict:'',
  createBy: '',
  createby_dict: '',
  templateFileId:'',
  currentPage: 1,
  acquiringBarcode:'',
  pageSize: 10,
  total: 0,
  column: 'createTime',
  order: 'desc'
})
const importForm = reactive({
  customerId: '',
  customerName: '',
  filePath: ''
})
const importRules = reactive({
  customerId: { required: true, message: '请选择客户', trigger: 'change' },
  filePath: { required: true, message: '请选择要导入的文件', trigger: 'change' }
})
const currentColConf = reactive({
  excelOrderFiledConfId: '',
  title: '',
  orderFiledConfs: [],
  templateFileId: ''
})
const currentConfigTitle = ref('')

const xTable = ref<VxeTableInstance>()
const tableData = ref([])
/**当前选择行 */
const currentRow = reactive<Recordable>({})
/**弹窗显示 */
const detailVisible = ref(false)
/**详情表格数据 */
const detailTable = ref<Recordable[]>([])
/**表格title */
const tableTitle = ref<string[]>([])

const convertVisible = ref(false)

const statusOptions = ref([])

const queryDict = async (code: string) => {
  const { data } = await apiDictList({
    dictCodes: code
  })
  statusOptions.value = data.result[code]
}

const popoverRef = ref()
const buttonRef = ref()
const popoverVisible = ref(false)
const showPopover = (e: any, title: string) => {
  buttonRef.value = e.target
  // 设置标题
  currentConfigTitle.value = title

  const hasConf = !!getAllMapConfigs.value[title].orderFiledConfs.length
  const conf = hasConf
    ? getAllMapConfigs.value[title]
    : {
        excelOrderFiledConfId: '',
        title,
        orderFiledConfs: [
          {
            mapField: '',
            orderFiled: null,
            scripts: []
          }
        ],
        templateFileId: currentRow.templateFileId
      }
  Object.assign(currentColConf, conf)
  // 打开popover
  popoverVisible.value = true
}

/**监听popover和modal显示状态。重置表单信息 */
watch([detailVisible, popoverVisible], (val) => {
  // 关闭弹窗或者关闭popover
  if (val.includes(false)) {
    // 解决关闭弹窗之后，popover未关闭情况
    popoverVisible.value = false
  }
})

/** 确认字段映射及脚本的配置 */
const confirmConfig = (configList: any) => {
  // 便利一下是否有变量字段
  excelChangeStore.setSingleFieldMap({
    ...currentColConf,
    orderFiledConfs: cloneDeep(
      configList
        .map((item) => {
          if (item.mapField && item?.isVariable) {
            item.orderFiled = {
              fliedTitle: item.mapField,
              filedName: item.mapField,
              variable: true
            }
          }
          return item
        })
        .filter((v) => !!v.mapField)
    )
  })
  // 关闭popover
  popoverVisible.value = false
}

/**确认解析/转换的订单的状态 */
const confirmOrderStatus = async (row: any) => {
  await ElMessageBox.confirm('是否确认转换后的订单？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

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

  onQuery()
}

/**保存订单字段 */
const saveOrderField = async () => {
  const params = {
    templateFileId: currentRow.templateFileId,
    confs: Object.values(getAllMapConfigs.value).filter(
      (v) => v.title !== '' && !!v.orderFiledConfs.length
    )
  }

  saveConfExcelFileOrderPage(params).then(({ data }) => {
    if (data.code == 200) {
      ElMessage.success(data.message || '保存成功！')
    } else {
      ElMessage.error(data.message || '保存失败！')
    }
  })
}


const showScriptNames =  (array) => {
  let value = array?array.map(item => item.scripts.map(scrip=> scrip.scriptName)).join('\n'):''
  return value
}

const showScriptNumber =  (array) => {
  let arr = []
  let value = 0;
  if(array){
      console.log("过滤前",array)
      let val =  array.map(item=> item.scripts.map(scrip=> scrip.scriptName))
      val.forEach(item=>{
          console.log("item=",item)
          item.forEach(v=>{
            arr.push(v)
          })
      })
     let val1 = arr.filter(item => item&&item!='')
    value = val1.length
  } 
  return value
}


const copyOrders = (item)=>{
    
  let arr = []
  for (let key in item) {
    arr.push({
      title:key,
      value: item[key]
    })
   
  }
  const text = JSON.stringify(arr);
  const textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.style.position = "absolute";
  textarea.style.opacity = "0";
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
  ElMessage({
          type: 'success',
          message: '复制订单数据到粘贴板'
        })
}


/** 确认订单转换 */
const confirmChange = async (row) => {
  await ElMessageBox.confirm('是否确认订单转换？', '提示', {
    confirmButtonText: '转换',
    cancelButtonText: '取消',
    type: 'warning'
  })
  const { data } = await convertExcelFileOrder(row.excelOrderId)
  if (data.code == 200) {
    ElMessage.success(data.message || '转换成功！')
    detailVisible.value = false
    onQuery()
    return
  }
  ElMessage.error(data.message || '转换失败！')
}

const toDetail = async (row: any) => {
  Object.assign(currentRow, row)
  const { data } = await getConfByExcelOrderId(row.excelOrderId)
  const { res, titles, configs } = filterRunData(data.result.orders, true)


  data.result.confs?.forEach((item: any) => {
    configs[item.title] = item
  })
  // 排除通过循环不显示的column
  const excludeTitles = ['sortNum', '数据区', 'expendData']
  detailTable.value = res
  tableTitle.value = titles.filter((v) => !excludeTitles.includes(v))
  // console.log(tableTitle.value)
  
  nextTick(() => {
    // detailVisible.value = true
        detailVisible.value = true
  })

  excludeTitles.forEach((key) => {
    Reflect.deleteProperty(configs, key)
  })

  excelChangeStore.setAllMapConfigs(configs)
}


const toSaleOrderDetail = async (row: any) => {
  loading.value = true
  const titles: string[] = []
  const { data } = await listSaleOrdersByExcelId(row.excelOrderId)
  let flatdatas: any = null

  const record = data.result[0]

  // 获取表头
  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)
    }
  }

  convertTableTitle.value = titles

  convertData.value = data.result?.map((item) => {
    return {
      ...item,
      ...flatdatas
    }
  })
  loading.value = false
  // 打开弹窗
  convertVisible.value = true
}



/**批量删除行 */
const removeRows = async () => {
  const list = xTable.value?.getCheckboxRecords()
  if (list?.length) {
    const ids = list.map((v) => v.excelOrderId).join(',')
    await deleteExcelFileOrderById(ids)
    ElMessage.success('删除成功')
    onQuery()
  }
}

const handleExceed = (files: any) => {
  uploadRef.value!.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

const handleRemove = () => {
  importForm.filePath = ''
}
const confirmCustomer = (list: any) => {
  const [item] = list
  if (!item) return
  queryParams.customerId = item.customerId
  queryParams.customerId_dict = item.customerName
}

/**导出 */
const exportTmp = async (row: any) => {
  const res = await excelFileOrderExportExcel(row.excelOrderId)
  saveAs(new Blob([res.data]), `${row.customerId_dictText}-${Date.now()}.xlsx`)
}

const imporModalHide = () => {
  Object.assign(importForm, {
    customerId: '',
    customerName: '',
    filePath: ''
  })
}

const changeUpload = (file: any) => {
  const formData = new FormData()
  formData.append('file', file.raw)

  uploadFile(formData).then(({ data }) => {
    if (data?.code === 200) {
      importForm.filePath = data.message
    } else {
      return ElMessage.error('上传失败！')
    }
  })
}
const submitImport = async () => {
  await importFormInstance.value?.validate()
  const { data } = await excelFileOrderImportExcel(importForm)
  if (data?.code == '200') {
    ElMessage.success(data.msg || '导入成功！')
    importVisible.value = false
    onQuery()
  } else {
    ElMessage.error(data.msg || '导入失败')
  }
}

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

const onCopy = () => {
  const confs = Object.values(getAllMapConfigs.value).filter(
    (v) => v.title !== '' && !!v.orderFiledConfs.length
  )

  handleCopy(confs)
}

const onPaste = () => {
  // console.log(copyInfo)

  // 将复制的配置信息，一条一条设置
  copyInfo.value.forEach((item: any) => {
    item.templateFileId = currentRow.templateFileId
    item.excelOrderFiledConfId = ''
    excelChangeStore.setSingleFieldMap(item)
  })

  // 自动保存
  saveOrderField()
}

const onReset = () => {


  Object.assign(queryParams, {
    status: '',
    fileId:'',
    templateFileId:'',
    createTime: '',
    createBy: '',
    createby_dict: '',
    customerId_dict:'',
    acquiringBarcode:'',
    customerId:''
  })
}
const onQuery = async () => {
  loading.value = true
  let createTime = queryParams.createTime
  try {
    if (queryParams.createTime != null && queryParams.createTime != '') {
      queryParams.createTime_begin = queryParams.createTime[0]
      queryParams.createTime_end = queryParams.createTime[1]
      queryParams.createTime = null
    } else {
      queryParams.createTime = null
    }
    const { data } = await getExcelFileOrderPage(queryParams)
    tableData.value = data.result.records
    queryParams.total = +data.result.total
  } catch {}
  finally{
    queryParams.createTime = createTime
  }
  loading.value = false
}

onMounted(() => {
  onQuery()
  queryDict('excel_order_status')
})
</script>
<style lang="scss" scoped>
.header-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 178px;
}
.expandTableHeader {
  background: #e8eaec;
}
</style>
