<template>
  <ContentWrap v-if="visibleSearch">
    <!-- 搜索工作栏 -->
    <Search
      :schema="[
        ...SupplierdeliverRequestMain.allSchemas.searchSchema,
        ...SupplierdeliverRequestDetail.allSchemas.searchSchema
      ]"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
  </ContentWrap>

  <!-- 列表头部 -->
  <TableHead
    :HeadButttondata="HeadButttondata"
    @button-base-click="buttonBaseClick"
    :routeName="routeName"
    @updataTableColumns="updataTableColumns"
    @searchFormClick="searchFormClick"
    :allSchemas="SupplierdeliverRequestMain.allSchemas"
    :detailAllSchemas="SupplierdeliverRequestDetail.allSchemas"
  >
    <template #rightBtn_right>
      <el-tooltip effect="dark" content="查询条件" placement="top-start">
        <el-button @click="foldUpClick">
          <Icon :icon="visibleSearch ? 'ep:arrow-up' : 'ep:arrow-down'" />
        </el-button>
      </el-tooltip>
    </template>
  </TableHead>

  <!-- 列表 -->
  <ContentWrap>
    <Table
      v-clientTable
      :columns="tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      v-model:sort="tableObject.sort"
    >
      <template #asnNumber="{ row }">
        <el-button type="primary" link @click="openDetail(row, '发货单号', row.asnNumber)">
          <span>{{ row.asnNumber }}</span>
        </el-button>
      </template>
      <template #number="{ row }">
        <el-button type="primary" link @click="openDetail(row, '单据号', row.number)">
          <span>{{ row.number }}</span>
        </el-button>
      </template>
      <template #action="{ row, $index }">
        <ButtonBaseMore
          :Butttondata="butttondata(row, $index)"
          @button-base-click="buttonTableClick($event, row)"
        />
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <supplierdeliverBasicForm
    ref="supplierdeliverFormRef"
    @getList="getList"
  ></supplierdeliverBasicForm>
  <!-- <BasicForm
    ref="formRef"
    :isOpenSearchTable="true"
    @success="getList"
    :rules="SupplierdeliverRequestMainRules"
    :formAllSchemas="SupplierdeliverRequestMain.allSchemas"
    :tableAllSchemas="SupplierdeliverRequestDetail.allSchemas"
    :tableFormRules="SupplierdeliverRequestDetailRules"
    :tableData="tableData"
    :apiUpdate="SupplierdeliverRequestMainApi.updateSupplierdeliverRequestMain"
    :apiCreate="SupplierdeliverRequestMainApi.createSupplierdeliverRequestMain"
    :isBusiness="true"
    @handleAddTable="handleAddTable"
    @handleDeleteTable="handleDeleteTable"
    @searchTableSuccess="searchTableSuccess"
    @submitForm="submitForm"
    @formFormDateChange="formFormDateChange"
    @onEnter="onEnter"
  > -->
  <!-- <template  v-slot="{row}">
    <el-date-picker v-bind:modelValue="row['expireTime']?addDay(row['produceDate'],row['expireTime']).format('YYYY-MM-DD'):'2099-12-31'"
    :clearable="true"
    style="width: 100%"
    :disabled="true" 
    placeholder="选择日期"/>
    </template>
  </BasicForm> -->

  <!-- 详情 -->
  <Detail
    ref="detailRef"
    :annexTable="[
      annexInspectionDetail,
      {
        label: '履历表',
        prop: 'uploadFile',
        tableName: 'SupplierdeliverCurriculumVitae',
        hasSubDetail: false, // 附件中是否展示明细表
        showPreview: true, // 附件中是否展示预览按钮
        hiddenUpload:false,
        hiddenDelete:false,
        fileType: ['pdf'],
        limit:999999,
        align: 'left',
      }
    ]"
    :isBasic="false"
    :allSchemas="SupplierdeliverRequestMain.allSchemas"
    :detailAllSchemas="SupplierdeliverRequestDetail.allSchemas"
    :detailAllSchemasRules="SupplierdeliverRequestDetailRules"
    :apiCreate="SupplierdeliverRequestDetailApi.createSupplierdeliverRequestDetail"
    :apiUpdate="SupplierdeliverRequestDetailApi.updateSupplierdeliverRequestDetail"
    :apiPage="SupplierdeliverRequestDetailApi.getSupplierdeliverRequestDetailPage"
    :apiDelete="SupplierdeliverRequestDetailApi.deleteSupplierdeliverRequestDetail"
    @searchTableSuccessDetail="searchTableSuccessDetail"
  />

  <!-- 导入 -->
  <ImportForm
    ref="importFormRef"
    url="/wms/supplierdeliver-request-main/import"
    :importTemplateData="importTemplateData"
    @success="importSuccess"
    :updateIsDisable="true"
    :coverIsDisable="true"
    :mode="2"
  />

  <!-- 创建标签 -->
  <BasicForm
    ref="formLabelRef"
    @success="getList"
    :tableAllSchemas="SupplierdeliverRequestDetailLabel.allSchemas"
    :tableFormRules="SupplierdeliverRequestDetailRules"
    :tableData="detatableData1"
    :isBusiness="true"
    :isShowButton="false"
    @searchTableSuccess="searchTableSuccessLabel"
    :isShowReduceButton="false"
    @clearInput="clearInput"
    :footButttondata="footButttondata"
    @footButtonClick="footButtonClick"
    @formSelectChange="formSelectChangeLabel"
  />
  
  <!-- 上传质量报告 -->
  <BasicForm
    ref="ploadQualityReportRef"
    @success="getList"
    :formAllSchemas="SupplierdeliverInspectionDetail.allSchemas"
    :tableAllSchemas="SupplierdeliverInspectionDetail.allSchemas"
    :tableFormRules="SupplierdeliverInspectionDetailRules"
    :tableData="uploadQualityReportTableData"
    @handleAddTable="handleAddQualityReport"
    @handleDeleteTable="handleDeleteQualityReport"
    @submitForm="submitFormUploadQualityReport"
    :isShowReduceButton="false"
    :isShowButton="false"
  >
    <template #SupplierdeliverInspectionDetail>
      <span>1111</span>
    </template>
  </BasicForm>

  <!-- 标签打印 -->
  <SearchTable width="905px" ref="searchTableRef" @searchTableSuccess="searchTableSuccess1">
    <!-- <template #actions>
      <el-button type="primary" @click="printAllClick">打印全部</el-button>
    </template> -->
  </SearchTable>
  <labelForm
    ref="labelFormRef"
    :tableAllSchemas="SupplierdeliverRequestDetailLabel.allSchemas"
    @submitForm="submitFormLabel"
    :key="count"
  />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { getAccessToken } from '@/utils/auth'
import { formatDate } from '@/utils/formatTime'
import {
  SupplierdeliverRequestMain,
  SupplierdeliverRequestDetail,
  SupplierdeliverRequestDetailRules,
  SupplierdeliverRequestDetailLabel,
  SupplierdeliverRequestPackage
} from './supplierdeliverRequestMain.data'
import {
  SupplierdeliverInspectionDetail,
  SupplierdeliverInspectionDetailRules,
  CurriculumVitae,
  CurriculumVitaeRules
} from '../supplierdeliverInspectionDetail/supplierdeliverInspectionDetail.data'
import * as SupplierdeliverRequestMainApi from '@/api/wms/supplierdeliverRequestMain'
import * as SupplierdeliverRequestDetailApi from '@/api/wms/supplierdeliverRequestDetail'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import * as PurchasePlanDetailApi from '@/api/wms/purchasePlanDetail'
import * as ItembasicApi from '@/api/wms/itembasic'
import * as SupplierdeliverInspectionDetailApi from '@/api/wms/supplierdeliverInspectionDetail'
import * as PackageApi from '@/api/wms/package'
import { PurchasePlanDetail } from '../purchasePlanMain/purchasePlanMain.data'
import * as SupplierApi from '@/api/wms/supplier'
import { Supplier } from '@/views/wms/basicDataManage/supplierManage/supplier/supplier.data'
import supplierdeliverBasicForm from './supplierdeliverBasicForm.vue'
import labelForm from './labelForm.vue'
import { getJmreportBaseUrl } from '@/utils/systemParam'
import { usePageLoading } from '@/hooks/web/usePageLoading'
const { loadStart, loadDone } = usePageLoading()
// 供应商发货申请
defineOptions({ name: 'SupplierdeliverRequestMain' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const genLabelId = ref()
const route = useRoute() // 路由信息
const routeName = ref()
const count = ref(0)
routeName.value = route.name
const annexInspectionDetail = ref({
  label: '质检明细',
  prop: 'uploadFile',
  tableName: 'SupplierdeliverInspectionDetail',
  hasSubDetail: true, // 附件中是否展示明细表
  showPreview: true, // 附件中是否展示预览按钮
  hiddenUpload:false,
  hiddenDelete:false,
  fileType: ['pdf'],
  limit:999999,
  align: 'left',
  //明细表数据
  subDetailTableData: {
    queryParams: [
      {
        queryField: 'masterId',
        rowField: 'masterId'
      }
    ], // 查询参数
    getSubList: SupplierdeliverInspectionDetailApi.getSupplierdeliverInspectionDetailPage, //请求接口
    tableColumns: SupplierdeliverInspectionDetail.allSchemas.tableColumns,
    tableList: [], //表格数据
    total: 1,
    pageSize: 10,
    currentPage: 1
  }
})
const tableColumns = ref([
  ...SupplierdeliverRequestMain.allSchemas.tableColumns,
  ...SupplierdeliverRequestDetail.allSchemas.tableMainColumns
])


// 字段设置 更新主列表字段
const updataTableColumns = (val) => {
  tableColumns.value = val
}

const planArriveTimeStr = ref()
// 查询页面返回
const searchTableSuccess = (formField, searchField, val, formRef, type, row) => {
  nextTick(() => {
    console.log('type:', type)
    console.log('formField:', formField)
    console.log(formField, searchField, val, formRef, type, row)
    if (type == 'tableForm') {
      // 明细查询页赋值
      // row[formField] = val[0][searchField]
      // if (formField == 'poNumber') {
      //   row['poNumber'] = val[0]['poNumber']
      //   row['itemCode'] = val[0]['itemCode']
      //   row['poLine'] = val[0]['poLine']
      //   row['orderQty'] = val[0]['orderQty']
      //   row['uom'] = val[0]['uom']
      // }
      //添加费用明细--点击确定
      const itemCodes = []
      val.forEach((item) => {
        if (tableData.value.find((item1) => item1['id'] == item['id'])) return
        const newRow = { ...row }
        newRow[formField] = item[searchField]
        newRow['poNumber'] = item['poNumber']
        newRow['itemCode'] = item['itemCode']
        newRow['poLine'] = item['poLine']
        newRow['orderQty'] = item['orderQty']
        newRow['uom'] = item['uom']
        itemCodes.push(item['itemCode'])
        tableData.value.push(newRow)
      })
      //有效期
      ItembasicApi.getItembasicPage({
        code: itemCodes.join(',')
      }).then((res) => {
        res.list.forEach((item, index) => {
          const findItem = tableData.value.find((item1) => item1['itemCode'] == item['code'])
          findItem['expireTime'] = findItem['expireTime']
        })
      })
    } else {
      const setV = {}
      setV[formField] = val[0][searchField]
      if (formField == 'ppNumber') {
        //新增--选择完要货计划，自动展示明细
        getSearchTableData(val[0]['number'], formField, searchField)

        // 设置计划到货时间
        let beginTime = val[0]['endTime']
        let deliveryDate = formatDate(val[0]['deliveryDate'], 'YYYY-MM-DD')
        planArriveTimeStr.value = deliveryDate + ' ' + beginTime + ':00'
        setV['planArriveTime'] = new Date(planArriveTimeStr.value).valueOf()
        // 清空子表数据
        tableData.value = []
      }
      if (formField == 'supplierCode') {
        setV['contactName'] = val[0]['contacts']
        setV['contactPhone'] = val[0]['phone']
        setV['contactEmail'] = val[0]['email']
      }
      formRef.setValues(setV)
    }
  })
}
//供应商代码 回车搜索
const onEnter = async (field, value) => {
  console.log(field, value)
  formRef.value.opensearchTable(
    'supplierCode',
    'code',
    '供应商信息',
    Supplier.allSchemas,
    SupplierApi.getSupplierPage,
    [
      {
        key: 'code',
        value: value
      }
    ]
  )
}

const getSearchTableData = async (number, formField, searchField) => {
  const { tableObject, tableMethods } = useTable({
    defaultParams: { number },
    getListApi: PurchasePlanDetailApi.getPurchasePlanDetailPage // 分页接口
  })
  // 获得表格的各种操作
  const { getList: getList1 } = tableMethods
  await getList1()
  const tableColumns = PurchasePlanDetail.allSchemas.tableFormColumns
  tableColumns.forEach((item) => {
    item.width = item.table?.width || 150
  })
  tableData.value = []
  const itemCodes = []
  tableObject.tableList.forEach((row) => {
    const newRow = JSON.parse(JSON.stringify({ ...tableFormKeys, ...row }))
    newRow[formField] = row[searchField]
    newRow['poNumber'] = row['poNumber']
    newRow['itemCode'] = row['itemCode']
    newRow['poLine'] = row['poLine']
    newRow['orderQty'] = row['orderQty']
    newRow['uom'] = row['uom']
    tableData.value.push(newRow)
    itemCodes.push(row['itemCode'])
  })
  //有效期
  ItembasicApi.getItembasicPage({
    code: itemCodes.join(',')
  }).then((res) => {
    res.list.forEach((item, index) => {
      const findItem = tableData.value.find((item1) => item1['itemCode'] == item['code'])
      findItem['expireTime'] = findItem['expireTime']
    })
  })
}
// 查询页面返回——详情
const searchTableSuccessDetail = (formField, searchField, val, formRef) => {
  nextTick(() => {
    const setV = {}
    setV[formField] = val[0][searchField]
    if (formField == 'poNumber') {
      setV['poNumber'] = val[0]['poNumber']
      setV['itemCode'] = val[0]['itemCode']
      setV['poLine'] = val[0]['poLine']
      setV['uom'] = val[0]['uom']
      setV['orderQty'] = val[0]['orderQty']
    }
    formRef.setValues(setV)
  })
}
// 查询页面返回
const searchTableSuccessLabel = (formField, searchField, val, formRef, type, row) => {
  nextTick(() => {
    console.log('formField:', formField)
    console.log('val:', val)
    if (type == 'tableForm') {
      // 明细查询页赋值
      row[formField] = val[0][searchField]
      if (formField == 'packUnit') {
        row['packUnit'] = val[0]['packUnit']
        row['packName'] = val[0]['packName']
        row['packQty'] = val[0]['packQty']
      }
      if (formField == 'secondPackUnit') {
        row['secondPackUnit'] = val[0]['packUnit']
        row['secondPackName'] = val[0]['packName']
        row['secondPackQty'] = val[0]['packQty']
      }
    }
  })
}
// 为了折叠
const visibleSearch = ref(false)
const foldUpClick = () => {
  visibleSearch.value = !visibleSearch.value
  tableObject.loading = true
  let timer = setTimeout(() => {
    tableObject.loading = false
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
  }, 500)
}

const { tableObject, tableMethods } = useTable({
  getListApi: SupplierdeliverRequestDetailApi.getSupplierdeliverRequestDetailPage // 分页接口
})

// 获得表格的各种操作
const { getList, setSearchParams } = tableMethods

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultAddBtn({ hasPermi: 'wms:supplierdeliver-request-main:create' }), // 新增
  // defaultButtons.defaultImportBtn({ hasPermi: 'wms:supplierdeliver-request-main:import' }), // 导入 7.15喜婷说先拿掉
  defaultButtons.defaultExportBtn({ hasPermi: 'wms:supplierdeliver-request-main:export' }), // 导出
  defaultButtons.defaultFreshBtn(null), // 刷新
  defaultButtons.defaultFilterBtn(null), // 筛选
  defaultButtons.defaultSetBtn(null) // 设置
  // {
  //   label: '自定义扩展按钮',
  //   name: 'zdy',
  //   hide: false,
  //   type: 'primary',
  //   icon: 'Select',
  //   color: ''
  // },
]

// 头部按钮事件
const buttonBaseClick = (val, item) => {
  if (val == 'add') {
    // 新增
    openForm('create')
  } else if (val == 'import') {
    // 导入
    handleImport()
  } else if (val == 'export') {
    // 导出
    handleExport()
  } else if (val == 'refresh') {
    // 刷新
    if (tableObject.params.filters && tableObject.params.filters.length > 0) {
      searchFormClick({
        filters: tableObject.params.filters
      })
    } else {
      getList()
    }
  } else if (val == 'filtrate') {
    // 筛选
  }
}

// 根据状态返回该按钮是否显示
const isShowMainButton = (row, val) => {
  if (val.indexOf(row.status) > -1) {
    return false
  } else {
    return true
  }
}

// 根据状态返回该按钮是否显示
const isShowMainButtonLabel = (row, val) => {
  if (val.indexOf(row.status) > -1) {
    if (row.labelStatus == '2') {
      return true
    } else {
      return false
    }
  } else {
    return true
  }
}

// 根据状态返回该按钮是否显示
const isReGenLabelShowMainButtonLabel = (row, val) => {
  if (val.indexOf(row.status) > -1) {
    if (row.labelStatus == '1') {
      return true
    } else {
      return false
    }
  } else {
    return true
  }
}

// 列表-操作按钮
const butttondata = (row, $index) => {
  const findIndex = row['masterId']
    ? tableObject.tableList.findIndex((item) => item['masterId'] == row['masterId'])
    : -1
  if (findIndex > -1 && findIndex < $index) {
    return []
  }
  return [
    //202408111354需求变更供应商发货申请关闭后不能打开 去掉打开按钮
    // defaultButtons.mainListPurchasePlanOpeBtn({
    //   hide: isShowMainButton(row, ['5']),
    //   hasPermi: 'wms:supplierdeliver-request-main:open'
    // }), // 打开
    defaultButtons.mainListPlanUploadQualityReportBtn({
      hide: isShowMainButton(row, ['1', '2', '3']),
      hasPermi: 'wms:supplierdeliver-request-main:uploadCheck'
    }), // 上传质量报告
    {
      label: t('ts.上传履历表'),
      name: 'mainPlanCurriculumVitae',
      hide: row.status==5,
      type: 'primary',
      icon: '',
      color: '',
      hasPermi: '',
      link: true // 文本展现按钮
    }, // 上传履历表
    defaultButtons.mainListPlanSubBtn({
      hide: isShowMainButton(row, ['1']),
      hasPermi: 'wms:supplierdeliver-request-main:sub'
    }), // 提交审批
    defaultButtons.mainListPlanAppBtn({
      hide: isShowMainButton(row, ['2']),
      hasPermi: 'wms:supplierdeliver-request-main:app'
    }), // 审批通过
    defaultButtons.mainListPlanTurBtn({
      hide: isShowMainButton(row, ['2']),
      hasPermi: 'wms:supplierdeliver-request-main:rej'
    }), // 驳回按钮
    defaultButtons.mainListEditBtn({
      hide: isShowMainButton(row, ['1']),
      hasPermi: 'wms:supplierdeliver-request-main:update'
    }), // 编辑
    // defaultButtons.mainListDeleteBtn({ hasPermi: 'wms:supplierdeliver-request-main:delete' }), // 删除
    {
      label: t('ts.生成标签'),
      name: 'ssbq',
      hide: isShowMainButtonLabel(row, ['3']),
      type: 'primary',
      icon: '',
      color: '',
      hasPermi: 'wms:supplierdeliver-request-main:genLabels',
      link: true // 文本展现按钮
    },
    {
      label: t('ts.重新生成标签'),
      name: 'ressbq',
      hide: isReGenLabelShowMainButtonLabel(row, ['3']),
      type: 'primary',
      icon: '',
      color: '',
      hasPermi: 'wms:supplierdeliver-request-main:genLabels',
      link: true // 文本展现按钮
    },
    defaultButtons.mainListPointBtn({
      hide: isShowMainButton(row, ['3', '8']),
      hasPermi: 'wms:supplierdeliver-request-main:printLabel'
    }), // 标签打印
    //defaultButtons.mainListDocumentPrintBtn({ hide: isShowMainButton(row, ['3','8']) }), // 单据打印
    // 生成记录
    {
      label: t('ts.发货'),
      name: 'genRecords',
      hide: isShowMainButton(row, ['3']),
      type: 'primary',
      icon: '',
      color: '',
      hasPermi: 'wms:supplierdeliver-request-main:genRecords',
      link: true // 文本展现按钮
    },
    defaultButtons.mainListPurchasePlanCloBtn({
      hide: isShowMainButton(row, ['1', '2', '4', '3']),
      hasPermi: 'wms:supplierdeliver-request-main:close'
    }) // 关闭
  ]
}

const detatableData1 = ref([])
// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'mainPurPlanOpe') {
    // 打开
    handleOpe(row.masterId)
  } else if (val == 'mainPurPlanClo') {
    // 关闭
    handleClo(row.masterId)
  } else if (val == 'mainPlanUploadQualityReport') {
    // 上传质量报告
    handleUploadQualityReport(row)
  }else if (val == 'mainPlanCurriculumVitae') {
    // 上传履历表
    handleUploadCurriculumVitae(row,'发货单号', row.asnNumber)
  } else if (val == 'mainPlanSub') {
    // 提交审批
    handleSub(row.masterId)
  } else if (val == 'mainPlanApp') {
    // 审批通过
    handleApp(row.masterId)
  } else if (val == 'mainPlanTur') {
    // 驳回按钮
    handleTur(row.masterId)
  } else if (val == 'genRecords') {
    // 处理
    genRecords(row.masterId)
  } else if (val == 'edit') {
    // 编辑
    openForm('update', row)
  } else if (val == 'delete') {
    // 删除
    handleDelete(row.masterId)
  } else if (val == 'ssbq') {
    // 生成标签
    try {
      tableObject.loading = true
      detatableData.params = {
        masterId: row.masterId
      }
      genLabelId.value = row.masterId
      // await getDetailList()
      await getGenerateLabelList(row)
      count.value++
      formLabelRef.value.open('create', row, null, 'createLabel') //创建标签页面 createLabel 标题
    } finally {
      tableObject.loading = false
    }
  } else if (val == 'ressbq') {
    console.log('重新生成标签')
    // ElMessageBox.confirm(`<div style="color:red">
    //   重新生成标签后必须撕毁原标签，打印并粘贴新标签，如标签错误将拒绝收货！！
    //   </div>`,'提示',{
    //   dangerouslyUseHTMLString: true,
    // })
    tableObject.loading = true
    ElMessageBox.confirm(
      `<div>
    <strong style="color:red;font-size:18px">重新生成标签后必须撕毁原标签，打印并粘贴新标签，如标签错误将拒绝收货！！</strong>
    <br>
    <span>重新生成标签会删除上次生成的标签，是否确认继续？</span>
    </div>`,
      '提示',
      {
        confirmButtonText: t('ts.确 认'),
        cancelButtonText: t('ts.取 消'),
        dangerouslyUseHTMLString: true
      }
    )
      .then(async () => {
        try {
          await SupplierdeliverRequestMainApi.deleteOldLabels(row.masterId).then(async (res) => {
            if (res) {
              // 生成标签
              detatableData.params = {
                masterId: row.masterId
              }
              genLabelId.value = row.masterId
              // await getDetailList()
              count.value++
              await getGenerateLabelList(row)
              formLabelRef.value.open('create', row, null, 'createLabel') //创建标签页面 createLabel 标题
            }
          })
        } finally {
          tableObject.loading = false
        }
      })
      .catch(() => {
        console.info('操作取消')
        tableObject.loading = false
      })
  } else if (val == 'point') {
    // 标签打印
    labelPrint(row)
  } else if (val == 'documentPrint') {
    // 单据打印
    handleDocumentPrint(row.masterId)
  }
}
const footButttondata = ref([
  defaultButtons.formNextStepBtn(null), // BOM下一步
  defaultButtons.formCloseBtn(null) // BOM关闭
])
// 获取箱规格
const getGenerateLabelList = async (row) => {
  const params1 = {
    masterId: row.masterId,
    pageSize: '500',
    pageNo: '1',
    sort: '',
    by: 'ASC'
  }
  await SupplierdeliverRequestDetailApi.getGenerateLabelList(params1).then((res) => {
    detatableData1.value = res
    detatableData1.value.forEach((item) => {
      // console.log(3333, item?.boxPackaging[0])
      item.boxPackaging = item.boxPackaging ? item.boxPackaging : []
      item.packUnitInitOptions = item.boxPackaging
      item.secondPackUnitInitOptions = item.palletPackaging || []
      let obj = item?.boxPackaging[0]
      if (obj) {
        item.packUnit = obj.packUnit
        item.packQty = obj.packQty
      }
      // 有托规格显示托规格，没有显示第一条规格
      item.secondPackUnit = obj?.parentPackUnit
        ? obj.parentPackUnit
        : item?.secondPackUnitInitOptions[0]?.packUnit
      item.secondPackQty = obj?.parentPackUnit
        ? obj.parentPackQty
        : item?.secondPackUnitInitOptions[0]?.packQty
    })
  })
}
// 下一步
const labelFormRef = ref()
const footButtonClick = async (val) => {
  if (val == 'nextStep') {
    const validateForm = await formLabelRef.value.tableFormRef.validateForm()
    if (!validateForm) {
      return
    }
    let isNext = detatableData1.value.some((item) => {
      return !item.packUnit || !item.packQty
    })
    if (isNext) {
      message.warning('有数据没有选择箱规格')
      return
    }
    let isNext1 = detatableData1.value.some((item) => {
      return (
        item.secondPackQty &&
        item.packQty &&
        parseFloat(item.packQty) > parseFloat(item.secondPackQty)
      )
    })
    if (isNext1) {
      message.warning('托的包装数量要大于箱的包装数量,请修改')
      return
    }
    const data = JSON.parse(JSON.stringify(detatableData1.value))
    labelFormRef.value.openLabel(data)
  } else if (val == 'close') {
    formLabelRef.value.dialogVisible = false
  }
}
// 选择箱规格 拖规格
const formSelectChangeLabel = (field, val, row) => {
  if (field == 'packUnit') {
    let obj = row.boxPackaging.find((item) => item.packUnit == val)
    if (obj) {
      row.packQty = obj.packQty
      // 获取托规格
      const params1 = {
        itemCode: row.itemCode,
        packUnit: row.packUnit
      }
      SupplierdeliverRequestDetailApi.getGenerateLabelParentList(params1).then((res) => {
        if (res?.length > 0) {
          row.secondPackUnit = res[0].packUnit
          row.secondPackQty = res[0].packQty
        } else {
          row.secondPackUnit = row?.secondPackUnitInitOptions[0]?.packUnit
          row.secondPackQty = row?.secondPackUnitInitOptions[0]?.packQty
        }
      })
    } else {
      row.packQty = ''
      row.secondPackUnit = ''
      row.secondPackQty = ''
    }
  }
  // 设置托
  if (field == 'secondPackUnit') {
    let obj = row.secondPackUnitInitOptions.find((item) => item.packUnit == val)
    if (obj) {
      row.secondPackQty = obj.packQty
    } else {
      row.secondPackQty = ''
    }
  }
}

// 获取部门 用于详情 部门回显
const { wsCache } = useCache()
/** 详情操作 */
const detailRef = ref()
const openDetail = (row: any, titleName: any, titleValue: any) => {
  const departmentCode = wsCache
    .get(CACHE_KEY.DEPT)
    .find((account) => account.id == row.departmentCode)?.name
  if (departmentCode) row.departmentCode = JSON.parse(JSON.stringify(departmentCode))
  annexInspectionDetail.value.hiddenDelete = row.status==8 //HL-5838质检明细-删除按钮只有status=8隐藏，其他都展示
  detailRef.value.openDetail(row, titleName, titleValue, 'requestSupplierdeliverMain')
}
/** 上传履历表 */
const handleUploadCurriculumVitae = async (row: any, titleName: any, titleValue: any) => {
  const departmentCode = wsCache
    .get(CACHE_KEY.DEPT)
    .find((account) => account.id == row.departmentCode)?.name
  if (departmentCode) row.departmentCode = JSON.parse(JSON.stringify(departmentCode))
  annexInspectionDetail.value.hiddenDelete = row.status==8 //HL-5838质检明细-删除按钮只有status=8隐藏，其他都展示
  detailRef.value.openDetail(row, titleName, titleValue, 'requestSupplierdeliverMain')
  nextTick(()=>{
    detailRef.value.changeTabCurrent({
      label:'履历表'
    })
  })
}
//添加/修改操作
const formRef = ref()
const supplierdeliverFormRef = ref()

const openForm = async (type: string, row?: number) => {
  supplierdeliverFormRef.value.openForm(type, row, defaultSupplierCode.value)
  // if(type == "update"){
  //   SupplierdeliverRequestMain.allSchemas.formSchema.forEach((item) => {
  //     if(item.field == 'supplierCode'){
  //       item.componentProps.isSearchList = false
  //       item.componentProps.disabled = true
  //     }
  //     if(item.field == 'ppNumber'){
  //       item.componentProps.isSearchList = false
  //       item.componentProps.disabled = true
  //     }
  //     if(item.field == 'asnNumber'){
  //       item.componentProps.disabled = true
  //     }
  //     if(item.field == 'planArriveTime'){
  //       item.componentProps.disabled = true
  //     }
  //   })
  // }else {
  //   SupplierdeliverRequestMain.allSchemas.formSchema.forEach((item) => {
  //     if(item.field == 'supplierCode'){
  //       item.componentProps.isSearchList = true
  //     }
  //     if(item.field == 'ppNumber'){
  //       item.componentProps.isSearchList = true
  //     }
  //     if(item.field == 'asnNumber'){
  //       item.componentProps.disabled = false
  //     }
  //     if(item.field == 'planArriveTime'){
  //       item.componentProps.disabled = false
  //     }
  //   })
  // }
  // tableData.value = [] // 重置明细数据
  // formRef.value.open(type, row)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    tableObject.loading = true
    // 发起删除
    await SupplierdeliverRequestMainApi.deleteSupplierdeliverRequestMain(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 关闭按钮操作 */
const handleClo = async (id: number) => {
  try {
    // 关闭的二次确认
    await message.confirm(t('ts.是否关闭所选中数据？'))
    tableObject.loading = true
    // 发起关闭
    await SupplierdeliverRequestMainApi.cloSupplierdeliverRequestMain(id)
    message.success(t('ts.关闭成功!'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 打开按钮操作 */
const handleOpe = async (id: number) => {
  try {
    // 打开的二次确认
    await message.confirm(t('ts.是否打开所选中数据？'))
    tableObject.loading = true
    // 发起打开
    await SupplierdeliverRequestMainApi.opeSupplierdeliverRequestMain(id)
    message.success(t('ts.打开成功!'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}
const ploadQualityReportRef = ref()
const uploadQualityReportTableData = ref([])

const handleAddQualityReport = () => {
  const tableFormKeys = {}
  SupplierdeliverInspectionDetail.allSchemas.tableFormColumns.forEach((item) => {
    tableFormKeys[item.field] = item.default ? item.default : ''
  })
  uploadQualityReportTableData.value.push(tableFormKeys)
  console.log('handleAddQualityReport')
}
const handleDeleteQualityReport = (row, index) => {
  uploadQualityReportTableData.value.splice(index, 1)
  console.log('handleDeleteQualityReport', row)
}

/** 上传质量报告 */
const handleUploadQualityReport = async (row) => {
  console.log('SupplierdeliverInspectionDetail', SupplierdeliverInspectionDetail.allSchemas)
  const uploadFile = SupplierdeliverInspectionDetail.allSchemas.formSchema.find(
    (item) => item.field == 'uploadFile'
  )
  if (uploadFile) {
    uploadFile['componentProps']['upData']['tableId'] = row.masterId
  }
  ploadQualityReportRef.value.open(
    'create',
    null,
    { masterId: row.masterId },
    t('ts.上传质检报告'),
    t('ts.上传质检报告')
  ) //创建标签页面 createLabel 标题
  const tableFormKeys = {}

  SupplierdeliverInspectionDetail.allSchemas.tableFormColumns.forEach((item) => {
    tableFormKeys[item.field] = item.default ? item.default : ''
  })
  await SupplierdeliverInspectionDetailApi.getSupplierdeliverDetailInfo(row.masterId).then(
    (res) => {
      if (res) {
        // console.log("返回结果:",res)
        uploadQualityReportTableData.value = res
      }
    }
  )
  //uploadQualityReportTableData.value = [tableFormKeys]
}




const submitFormUploadQualityReport = async (formType, data) => {
  delete data.number
  data.subList = uploadQualityReportTableData.value // 拼接子表数据参数
  if (formType === 'create') {
    await SupplierdeliverInspectionDetailApi.createSupplierdeliverInspectionDetail(data)
    message.success(t('common.createSuccess'))
  } else {
    await SupplierdeliverInspectionDetailApi.updateSupplierdeliverInspectionDetail(data)
    message.success(t('common.updateSuccess'))
  }
  ploadQualityReportRef.value.dialogVisible = false
  getList()
}

/** 提交审批按钮操作 */
const handleSub = async (id: number) => {
  try {
    // 提交审批的二次确认
    await message.confirm(t('ts.是否提交审批所选中数据？'))
    tableObject.loading = true
    // 发起提交审批
    await SupplierdeliverRequestMainApi.subSupplierdeliverRequestMain(id)
    message.success(t('ts.提交审批成功!'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 审批通过按钮操作 */
const handleApp = async (id: number) => {
  try {
    // 审批通过的二次确认
    await message.confirm(t('ts.是否审批通过所选中数据？'))
    tableObject.loading = true
    // 发起审批通过
    await SupplierdeliverRequestMainApi.appSupplierdeliverRequestMain(id)
    message.success(t('ts.审批通过成功!'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 驳回按钮操作 */
const handleTur = async (id: number) => {
  try {
    // 驳回的二次确认
    await message.confirm(t('ts.是否驳回所选中数据？'))
    tableObject.loading = true
    // 发起驳回
    await SupplierdeliverRequestMainApi.rejSupplierdeliverRequestMain(id)
    message.success(t('ts.驳回成功!'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 处理按钮操作 */
const genRecords = async (id: number) => {
  let getLoading = null
  await SupplierdeliverRequestMainApi.selfCheckReport(id)
    .then(async (res) => {
      if (!res) {
        message.warning(t('ts.请先上传自检报告!'))
        return
      } else {
        // 处理的二次确认
        await message.confirm(t('ts.是否处理所选中数据？'))
        getLoading = ElLoading.service({
          lock: true,
          text: 'loading...',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        // 发起处理
        SupplierdeliverRequestMainApi.genRecordsSupplierdeliverRequestMain(id)
          .then((res) => {
            message.success(t('ts.处理成功!'))
            console.log('resresresresres', res)
            // 刷新列表
            getList()
            console.log('刷新列表')
            getLoading?.close()

            // 单据打印
            handleDocumentPrint(res)
          })
          .catch((err) => {
            console.log('发起处理', err)
            getLoading?.close()
          })
      }
    })
    .catch((err) => {
      console.log('自检报告校验异常', err)
      getLoading?.close()
    })
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    loadStart()
    const excelTitle = ref(route.meta.title)
    const data = await SupplierdeliverRequestMainApi.exportSupplierdeliverRequestMain(
      tableObject.params
    )
    download.excel(data, `【${excelTitle.value}】【${formatDate(new Date())}】.xlsx`)
  } catch {
  } finally {
    loadDone()
  }
}

// 生成标签
const isCreateLabel = ref(false)
const formLabelRef = ref()
const { tableObject: detatableData, tableMethods: detatableMethods } = useTable({
  getListApi: SupplierdeliverRequestDetailApi.getSupplierdeliverRequestDetailPage
})
detatableData.pageSize = 500
const { getList: getDetailList } = detatableMethods

// 生成标签按钮操作
const submitFormLabel = async (list) => {
  try {
    const data = {
      subList: list
    }
    await message.confirm(t('ts.是否为此数据生成标签？'))
    labelFormRef.value.isLoading = true
    await SupplierdeliverRequestMainApi.genLabel(data)
    isCreateLabel.value = true
    message.success(t('ts.创建标签成功'))
    getList()
  } finally {
    formLabelRef.value.formLoading = false
    formLabelRef.value.dialogVisible = false
    labelFormRef.value.formLoading = false
    labelFormRef.value.dialogTableVisible = false
    labelFormRef.value.isLoading = false
  }
}
const clearInput = async (field, row, index) => {
  row[field] = ''
  row['secondPackQty'] = ''

  SupplierdeliverRequestDetailRules.secondPackQty[0].required = false
}

const BASE_URL = getJmreportBaseUrl()
const src = ref(BASE_URL + '/jmreport/view/922729953438072832?token=' + getAccessToken())
getListApi: PurchasePlanDetailApi.getPurchasePlanDetailPage // 分页接口

// 标签打印
const searchTableRef = ref()
const labelPrint = async (row) => {
  tableObject.loading = true
  const defaultParams = { moduleName: 'supplier', recordNumber: row.number }
  const { tableObject: tableObjectPrint, tableMethods } = useTable({
    defaultParams,
    getListApi: PackageApi.getLabelDetailPage // 分页接口
  })

  // 获得表格的各种操作
  const { getList: getListPrint } = tableMethods
  getListPrint()
  tableObject.loading = false
  const tableColumns = SupplierdeliverRequestPackage.allSchemas.tableFormColumns
  tableColumns.forEach((item) => {
    item.width = item.table?.width
  })
  searchTableRef.value.openData(t('ts.标签信息'), tableObjectPrint, { tableColumns }, true)
}

// 打印全部
const printAllClick = () => {}

// 批量打印--供应商发货申请
const searchTableSuccess1 = async (formField, searchField, val, formRef, type, row) => {
  console.log('批量打印', val)
  // let rows:any = []
  // val.forEach(item=>{
  //   rows = [...rows,...item.selectionRows.map(item1=>item1.number)]
  // })
  if (val.length == 0) {
    message.warning(t('ts.请先选择要打印的数据'))
    return
  }
  // window.open(src.value + '&asn_number=' + val.map(item1=>item1.number).join(','))

  await PackageApi.batchPrintingLable(val.map((item1) => item1.number).join(','))
    .then((res) => {
      console.log(res)
      window.open(src.value + '&asn_number=' + res)
    })
    .catch((err) => {
      console.log(err)
      message.error(t('ts.创建标签失败'))
    })
}

const print = async () => {
  window.open(src.value + '&number=' + detatableData.tableList[0].number)
}

// 单据打印
// const documentSrc = ref(BASE_URL + '/jmreport/view/884680688168280064?token=' + getAccessToken())
const documentSrc = ref(BASE_URL + '/jmreport/view/932556833517789184?token=' + getAccessToken())
const handleDocumentPrint = async (id) => {
  window.open(documentSrc.value + '&id=' + id)
}

/**
 * tableForm方法
 */
const tableFormKeys = {}
SupplierdeliverRequestDetail.allSchemas.tableFormColumns.forEach((item) => {
  tableFormKeys[item.field] = item.default ? item.default : ''
})
const tableData = ref([])

// 添加明细
const handleAddTable = () => {
  tableData.value.push(JSON.parse(JSON.stringify(tableFormKeys)))
}
// 删除明细
const handleDeleteTable = (item, index) => {
  let itemIndex = tableData.value.findIndex(item)
  tableData.value.splice(itemIndex, 1)
}

// 主子数据 提交
const submitForm = async (formType, submitData) => {
  let data = { ...submitData }
  if (data.masterId) {
    data.id = data.masterId
  }
  data.subList = tableData.value // 拼接子表数据参数
  let isHave = data.subList.some((item) => {
    console.log('CCCCC', item.expireDate)
    if (item.expireDate != null) {
      item.produceDate > item.expireDate
    }
  })
  if (isHave) {
    message.error(t('ts.生产日期不可以大于过期日期'))
    formRef.value.formLoading = false
    return
  }
  try {
    if (formType === 'create') {
      let planArriveStr = formatDate(data.planArriveTime)
      if (planArriveStr > planArriveTimeStr.value) {
        let confirmFlag = false
        await message
          .confirm(`${t('ts.计划到货时间大于')}${planArriveTimeStr.value}${t('ts.是否继续？')}`)
          .then(() => {
            console.log('选择了OK')
            //选择OK
          })
          .catch(() => {
            //选择取消
            console.log('选择了cancel')
            confirmFlag = true
            formRef.value.formLoading = false
            return
          })
        if (confirmFlag) {
          return
        }
      }
      if (tableData.value.length <= 0) {
        message.warning(t('ts.子表明细不能为空!'))
        formRef.value.formLoading = false
        return
      }
      await SupplierdeliverRequestMainApi.createSupplierdeliverRequestMain(data)
      message.success(t('common.createSuccess'))
    } else {
      await SupplierdeliverRequestMainApi.updateSupplierdeliverRequestMain(data)
      message.success(t('common.updateSuccess'))
    }
    formRef.value.dialogVisible = false
    // 刷新当前列表
    getList()
  } finally {
    formRef.value.formLoading = false
  }
}

/** 导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

// 导入附件弹窗所需的参数
const importTemplateData = reactive({
  templateUrl: '',
  templateTitle: `【${route.meta.title}】导入模版.xlsx`
})

// 导入成功之后
const importSuccess = () => {
  getList()
}

// 筛选提交
const searchFormClick = (searchData) => {
  tableObject.params = {
    isSearch: true,
    filters: searchData.filters
  }
  getList() // 刷新当前列表
}

const formFormDateChange = (field, val, row, index) => {
  if (field == 'produceDate') {
    let produceDateStr = formatDate(val, 'YYYYMMDD')
    row.batch = produceDateStr
    row.supplierBatch = produceDateStr
  }
}
const defaultSupplierCode = ref('')
const getDefaultSupplier = async () => {
  let supplier = await SupplierApi.getSupplierPageSCP({ isSearch: false })
  if (supplier.list && supplier.list.length > 0) {
    defaultSupplierCode.value = supplier.list[0]['code']
  } else {
    defaultSupplierCode.value = ''
  }
  console.log('defaultSupplierCode', defaultSupplierCode)
}

/** 初始化 **/
onMounted(async () => {
  getDefaultSupplier()

  getList()
  importTemplateData.templateUrl = await SupplierdeliverRequestMainApi.importTemplate()
})
</script>
