<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <Search
      :schema="[
        ...PreparetoissueMain.allSchemas.searchSchema,
        ...PreparetoissueDetail.allSchemas.searchSchema
      ]"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
  </ContentWrap>

  <!-- 列表头部 -->
  <TableHead
    :HeadButttondata="HeadButttondata"
    @button-base-click="buttonBaseClick"
    :routeName="routeName"
    @updataTableColumns="updataTableColumns"
    @searchFormClick="searchFormClick"
    :allSchemas="PreparetoissueMain.allSchemas"
    :detailAllSchemas="PreparetoissueDetail.allSchemas"
  />

  <!-- 列表 -->
  <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 #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>

  <!-- 表单弹窗：添加/修改 -->
  <BasicForm
    ref="formRef"
    :isOpenSearchTable="true"
    fieldTableColumn="workStation"
    @success="getList"
    :rules="PreparetoissueMainRules"
    :formAllSchemas="PreparetoissueMain.allSchemas"
    :tableAllSchemas="PreparetoissueDetail.allSchemas"
    :tableFormRules="PreparetoissueDetailRules"
    :tableData="tableData"
    :apiUpdate="PreparetoissueMainApi.updatePreparetoissueMain"
    :apiCreate="PreparetoissueMainApi.createPreparetoissueMain"
    :isBusiness="true"
    :isShowButton="isShowButton"
    @handleAddTable="handleAddTable"
    @handleDeleteTable="handleDeleteTable"
    :isShowReduceButtonSelection="true"
    @tableSelectionDelete="tableSelectionDelete"
    @searchTableSuccess="searchTableSuccess"
    @submitForm="submitForm"
  />

  <!-- 详情 -->
  <Detail
    ref="detailRef"
    :isBasic="false"
    :allSchemas="PreparetoissueMain.allSchemas"
    :detailAllSchemas="PreparetoissueDetail.allSchemas"
    :detailAllSchemasRules="PreparetoissueDetailRules"
    :apiCreate="PreparetoissueDetailApi.createPreparetoissueDetail"
    :apiUpdate="PreparetoissueDetailApi.updatePreparetoissueDetail"
    :apiPage="PreparetoissueDetailApi.getPreparetoissueDetailPage"
    :apiDelete="PreparetoissueDetailApi.deletePreparetoissueDetail"
    @searchTableSuccessDetail="searchTableSuccessDetail"
  />

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

<script setup lang="ts">
import download from '@/utils/download'
import {
  PreparetoissueMain,
  PreparetoissueMainRules,
  PreparetoissueDetail,
  PreparetoissueDetailRules
} from './preparetoissueMain.data'
import * as PreparetoissueMainApi from '@/api/wms/preparetoissueMain'
import * as PreparetoissueDetailApi from '@/api/wms/preparetoissueDetail'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import * as ProductionlineitemApi from '@/api/wms/productionlineitem'
import { formatDate } from '@/utils/formatTime'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { getBaseUrl, getJmreportBaseUrl } from '@/utils/systemParam'
import { getAccessToken } from '@/utils/auth'

const { loadStart, loadDone } = usePageLoading()
// 备料计划
defineOptions({ name: 'PreparetoissueMain' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const tableColumns = ref([
  ...PreparetoissueMain.allSchemas.tableColumns,
  ...PreparetoissueDetail.allSchemas.tableMainColumns
])

const isShowButton = ref(true)

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

// 查询页面返回
const searchTableSuccess = (formField, searchField, val, formRef, type, row) => {
  nextTick(() => {
    if (type == 'tableForm') {
      // 明细查询页赋值
      if (formField == 'itemCode') {
        if (tableData.value.find((item1) => item1['itemCode'] == val[0]['componentItemCode'])) {
          message.warning(`物料${val[0]['componentItemCode']}已经存在`)
          return
        }
        val.forEach((item, index) => {
          let tableForm = JSON.parse(JSON.stringify(tableFormKeys))
          if (index == 0) {
            row['itemCode'] = item['componentItemCode']
            row['uom'] = item['componentUom']
          } else {
            const newRow = JSON.parse(JSON.stringify({ ...tableForm, ...item }))
            newRow['itemCode'] = item['componentItemCode']
            newRow['uom'] = item['componentUom']
            newRow['workStation'] = row['workStation']
            newRow['toLocationCode'] = row['toLocationCode']
            newRow['remark'] = ''
            tableData.value.push(newRow)
          }
        })
      } else if (formField == 'workStation') {
        if (isShowButton.value) {
          val.forEach((item) => {
            const newRow = JSON.parse(JSON.stringify({ ...tableFormKeys, ...item }))
            newRow[formField] = item[searchField]
            newRow['toLocationCode'] = item['rawLocationCode']
            tableData.value.push(newRow)
          })
        } else {
          row['toLocationCode'] = val[0]['rawLocationCode']
          row[formField] = val[0][searchField]
        }

        console.log(77, formField)
        console.log(66, searchField)
        console.log(88, tableData.value)
        console.log(99, val)
      } else {
        row[formField] = val[0][searchField]
      }
    } else {
      const setV = {}
      setV[formField] = val[0][searchField]
      if (formField == 'productionPlanNumber') {
        setV['workshop'] = val[0]['workshop']
        setV['prodLine'] = val[0]['productionLine']
        setV['shift'] = val[0]['shift']
        setV['team'] = val[0]['team']
        isShowButton.value = false
        PreparetoissueDetail.allSchemas.tableFormColumns.map((item) => {
          if (item.field == 'workStation') {
            item.tableForm.isInpuFocusShow = true
          }
        })

        // 获取子表数据 getBomDisassemble
        PreparetoissueMainApi.getBomDisassemble(val[0]['id'])
          .then((res) => {
            if (res) tableData.value = res
            // 根据子表品番 和主表生产线 查询生产线物料关系 获取 原料库位赋值目标库位
            tableData.value.map((item) => {
              ProductionlineitemApi.getProductionlineitemPage({
                productionLineCode: val[0]['productionLine'],
                itemCode: item.itemCode,
                pageSize: 100,
                pageNo: 1,
                sort: '',
                by: 'ASC'
              }).then((res) => {
                item.toLocationCode = res.list[0].rawLocationCode
              })
            })
            // 修改 tableform 属性
            PreparetoissueDetail.allSchemas.tableFormColumns.map((item) => {
              if (item.field == 'itemCode') {
                item.isInpuFocusShow = false
                item.tableForm.isInpuFocusShow = false
                item.tableForm.disabled = true
              }
              if (item.field == 'planQty') {
                item.tableForm.disabled = true
              }
              if (item.field == 'available') {
                item.tableForm.disabled = true
              }
            })
          })
          .catch((err) => {
            console.log(err)
            message.error('错误')
          })
      }
      if (formField == 'workshop') {
        //车间代码
        tableData.value = []
      }
      if (formField == 'prodLine') {
        //车间代码
        tableData.value = []
      }
      formRef.setValues(setV)
    }
  })
}
// 查询页面返回——详情
const searchTableSuccessDetail = (formField, searchField, val, formRef) => {
  nextTick(() => {
    const setV = {}
    setV[formField] = val[0][searchField]
    if (formField == 'itemCode') {
      setV['itemCode'] = val[0]['componentItemCode']
    } else {
      setV['toLocationCode'] = val[0]['rawLocationCode']
    }
    formRef.setValues(setV)
  })
}

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

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

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultAddBtn({ hasPermi: 'wms:preparetoissue-main:create' }), // 新增
  defaultButtons.defaultImportBtn({ hasPermi: 'wms:preparetoissue-main:import' }), // 导入
  defaultButtons.defaultExportBtn({ hasPermi: 'wms:preparetoissue-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')
    resetShow()
  } 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') {
    // 筛选
  } else {
    // 其他按钮
    console.log('其他按钮', item)
  }
}

// 根据状态返回该按钮是否显示
const isShowMainButton = (row, val) => {
  if (val.indexOf(row.status) > -1) {
    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 [
    // defaultButtons.mainListPlanOpeBtn({hide:isShowMainButton(row,['5']),hasPermi:'wms:preparetoissue-main:open'}), // 打开
    defaultButtons.mainListPlanCloBtn({
      hide: isShowMainButton(row, ['1', '2', '3', '4']),
      hasPermi: 'wms:preparetoissue-main:close'
    }), // 关闭
    defaultButtons.mainListPlanSubBtn({
      hide: isShowMainButton(row, ['1']),
      hasPermi: 'wms:preparetoissue-main:submit'
    }), // 提交审批
    defaultButtons.mainListPlanTurBtn({
      hide: isShowMainButton(row, ['2']),
      hasPermi: 'wms:preparetoissue-main:reject'
    }), // 驳回
    defaultButtons.mainListPlanAppBtn({
      hide: isShowMainButton(row, ['2']),
      hasPermi: 'wms:preparetoissue-main:agree'
    }), // 审批通过
    defaultButtons.mainListPlanPubBtn({
      hide: isShowMainButton(row, ['3']),
      hasPermi: 'wms:preparetoissue-main:publish'
    }), // 发布
    defaultButtons.mainListPlanResBtn({
      hide: isShowMainButton(row, ['4']),
      hasPermi: 'wms:preparetoissue-main:resetting'
    }), // 重置
    defaultButtons.mainListEditBtn({
      hide: isShowMainButton(row, ['1']),
      hasPermi: 'wms:preparetoissue-main:update'
    }), // 编辑
    // defaultButtons.mainListDeleteBtn({hide:isShowMainButton(row,['1']),hasPermi:'wms:preparetoissue-main:delete'}), // 删除
    {
      label: '生成发料申请',
      name: 'scflsq',
      hide: isShowMainButton(row, ['6']),
      type: 'primary',
      icon: 'Select',
      hasPermi: 'wms:preparetoissue-main:publish',
      link: true, // 文本展现按钮
      color: ''
    },
    {
      label: '打印补给品备料单',
      name: 'printSupplyList',
      type: 'primary',
      icon: 'Select',
      hasPermi: 'wms:preparetoissue-main:publish',
      link: true, // 文本展现按钮
      color: ''
    }
  ]
}

// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'mainPlanOpe') {
    // 打开
    tableObject.loading = true
    PreparetoissueMainApi.open(row.masterId)
      .then(() => {
        message.success(t('common.updateSuccess'))
        tableObject.loading = false
        buttonBaseClick('refresh', null)
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanClo') {
    // 关闭
    await message.confirm('确认要关闭吗？')
    tableObject.loading = true
    PreparetoissueMainApi.close(row.masterId)
      .then(() => {
        message.success(t('common.updateSuccess'))
        tableObject.loading = false
        buttonBaseClick('refresh', null)
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanSub') {
    // 提交审批
    if (row.available == 'FALSE') return message.warning('当前数据：【不可用】')
    await message.confirm('确认要提交审批吗？')
    tableObject.loading = true
    PreparetoissueMainApi.submit(row.masterId)
      .then(() => {
        message.success(t('common.updateSuccess'))
        tableObject.loading = false
        buttonBaseClick('refresh', null)
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanTur') {
    // 驳回
    await message.confirm('确认要驳回吗？')
    tableObject.loading = true
    PreparetoissueMainApi.reject(row.masterId)
      .then(() => {
        message.success(t('common.updateSuccess'))
        tableObject.loading = false
        buttonBaseClick('refresh', null)
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanApp') {
    // 审批通过
    if (row.available == 'FALSE') return message.warning('当前数据：【不可用】')
    await message.confirm('确认要审批通过吗？')
    tableObject.loading = true
    PreparetoissueMainApi.agree(row.masterId)
      .then(() => {
        message.success(t('common.updateSuccess'))
        tableObject.loading = false
        buttonBaseClick('refresh', null)
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanPub') {
    // 发布
    await message.confirm('确认要发布吗？')
    tableObject.loading = true

    try {
      await PreparetoissueMainApi.publish(row.masterId)
      message.success(t('common.updateSuccess'))
      await PreparetoissueMainApi.generateIssueRequest(row.number)
    } catch (err) {
      console.log(err)
    } finally {
      tableObject.loading = false
      buttonBaseClick('refresh', null)
    }
  } else if (val == 'mainPlanRes') {
    // 重置
    await message.confirm('确认要重置吗？')
    tableObject.loading = true
    PreparetoissueMainApi.resetting(row.masterId)
      .then(() => {
        message.success(t('common.updateSuccess'))
        tableObject.loading = false
        buttonBaseClick('refresh', null)
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'scflsq') {
    // 生成发料申请
    if (row.available == 'FALSE') return message.warning('当前数据：【不可用】')
    await message.confirm('确认要生成发料申请吗？')
    tableObject.loading = true

    await PreparetoissueMainApi.generateIssueRequest(row.number)
      .then((res) => {
        console.log('返回数据', res)
        if (res.errorCount > 0) {
          message.confirm('存在物料库存不足，创建失败。').then(() => {
            window.open(getBaseUrl() + '/admin-api' + res.errorFile, '222')
          })
        } else {
          message.success(t('common.createSuccess'))
        }
        tableObject.loading = false
        buttonBaseClick('refresh', null)
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'edit') {
    // 编辑
    openForm('update', row)
  } else if (val == 'delete') {
    // 删除
    handleDelete(row.masterId)
  } else if (val == 'printSupplyList') {
    await PreparetoissueMainApi.getNumber(row.masterId).then((res) => {
      if (!res.isHaveProductionPlanNumber) {
        message.warning('发料申请未关联生产计划，不可打印')
        return
      }
      else if (!res.isHaveIssueRequestNumber) {
        message.warning('发料任务未完成，不可打印')
        return
      }else{
    // 打印补给品备料单
    handlePrintSupplyList(row.masterId)
      }
    })
  }
}

const BASE_URL = getJmreportBaseUrl()
const documentSrc = ref(BASE_URL + '/jmreport/view/1024904872747347968?token=' + getAccessToken())
const handlePrintSupplyList = async (id) => {
  window.open(documentSrc.value + '&id=' + id)
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = async (type: string, row?: number) => {
  tableData.value = [] // 重置明细数据
  if (type == 'update') {
    // 修改 tableform 属性
    PreparetoissueMain.allSchemas.formSchema.map((item) => {
      if (
        item.field == 'productionPlanNumber' ||
        item.field == 'workshop' ||
        item.field == 'prodLine' ||
        item.field == 'shift' ||
        item.field == 'team'
      ) {
        item.componentProps.isSearchList = false
        item.componentProps.disabled = true
      }
    })
  } else {
    // 修改 tableform 属性
    PreparetoissueMain.allSchemas.formSchema.map((item) => {
      if (
        item.field == 'productionPlanNumber' ||
        item.field == 'workshop' ||
        item.field == 'prodLine' ||
        item.field == 'shift' ||
        item.field == 'team'
      ) {
        item.componentProps.isSearchList = true
        item.componentProps.disabled = false
      }
    })
  }
  formRef.value.open(type, row)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (row: any, titleName: any, titleValue: any) => {
  detailRef.value.openDetail(row, titleName, titleValue, 'planPreparetoissueMain')
}

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

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

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

// 添加明细
const handleAddTable = () => {
  if (formRef.value.formRef.formModel.prodLine === '') {
    message.warning('请选择生产线代码')
    return
  }
  tableData.value.push(JSON.parse(JSON.stringify(tableFormKeys)))
}
// 删除明细
const handleDeleteTable = (item, index) => {
  let itemIndex = tableData.value.indexOf(item)
  if (itemIndex > -1) {
    tableData.value.splice(itemIndex, 1)
  }
}
const tableSelectionDelete = (selection) => {
  tableData.value = tableData.value.filter((item) => !selection.includes(item))
}
// 主子数据 提交
const submitForm = async (formType, submitData) => {
  let data = { ...submitData }
  if (data.masterId) {
    data.id = data.masterId
  }
  data.subList = tableData.value // 拼接子表数据参数
  formRef.value.formLoading = true

  try {
    if (formType === 'create') {
      await PreparetoissueMainApi.createPreparetoissueMain(data).then(async (res) => {
        if (res.status == '6') {
          // 生成发料申请
          await PreparetoissueMainApi.generateIssueRequest(res.number)
        }
        getList()
      })
      message.success(t('common.createSuccess'))
    } else {
      await PreparetoissueMainApi.updatePreparetoissueMain(data)
      message.success(t('common.updateSuccess'))
      buttonBaseClick('refresh', null)
    }
    formRef.value.dialogVisible = false
    // 刷新当前列表
  } 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 resetShow = async () => {
  isShowButton.value = true // tableform按钮恢复到显示
  // 修改 tableform 属性
  PreparetoissueDetail.allSchemas.tableFormColumns.map((item) => {
    if (item.field == 'itemCode') {
      item.isInpuFocusShow = true
      item.tableForm.isInpuFocusShow = true
      item.tableForm.disabled = false
    }
    if (item.field == 'planQty') {
      item.tableForm.disabled = false
    }
    if (item.field == 'available') {
      item.tableForm.disabled = false
    }
  })
}

/** 初始化 **/
onMounted(async () => {
  getList()
  importTemplateData.templateUrl = await PreparetoissueMainApi.importTemplate()
})
</script>
