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

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

  <!-- 列表 -->
  <ContentWrap>
    <Table
      :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 #planNoDay="{ row }">
        <el-button type="primary" link @click="openDetail(row, '计划编码', row.planNoDay)">
          <span>{{ row.planNoDay }}</span>
        </el-button>
      </template>
      <template #action="{ row }">
        <ButtonBase
          :Butttondata="butttondata(row)"
          @button-base-click="buttonTableClick($event, row)"
        />
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BasicFormV2
    ref="basicFormRef"
    @success="formsSuccess"
    :rules="OrderDayRules"
    :formAllSchemas="OrderDay.allSchemas"
    :apiUpdate="OrderDayApi.updateOrderDay"
    :apiCreate="OrderDayApi.createOrderDay"
    @searchTableSuccess="searchTableSuccess"
    :isBusiness="false"
    :isSearchFilterButtonHide="true"
    @onChange="valueChange"
   
  />

  <!-- 详情 -->
  <orderDetail ref="detailRef" :all-schemas="OrderDay.allSchemas" />
  <scheduleDetail ref="scheduleDetailRef"  :all-schemas="OrderDay.allSchemas" :basicFormWidth="75" @close="publishClosed" />
  <!-- 导入 -->
  <ImportForm
    ref="importFormRef"
    url="/mes/orderday/import"
    :importTemplateData="importTemplateData"
    @success="importSuccess"
  />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { OrderDay,OrderDayRules } from './orderDay.data'
import * as OrderDayApi from '@/api/mes/orderDay'
import BasicFormV2 from './components/BasicFormV2.vue'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import TableHead from '@/components/TableHead/src/TableHead.vue'
import ImportForm from '@/components/ImportForm/src/ImportForm.vue'
import orderDetail from './components/orderDetail.vue'
import scheduleDetail from './components/schedule.vue'
import { async } from '@antv/x6/lib/registry/marker/async'

defineOptions({ name: 'MesOrderDay' })

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

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const tableColumns = ref(OrderDay.allSchemas.tableColumns)
const  lineOptions=ref([])
const  processRouteOptions=ref([])


//**获取 产品工艺路由列表 */
const getProcessroutes = async (code: String) => {
  processRouteOptions.value = await OrderDayApi.getProcessroutes(code)
  OrderDay.allSchemas.formSchema.forEach(item => {
      if (item.field == 'processrouteCode') {
        //console.log('processrouteCode',item.field)
        item.componentProps.options = processRouteOptions.value
      }
    })
}
//**获取 车间产线列表 */
const getProductlines = async (code: String) => {
  lineOptions.value = await OrderDayApi.getProductlines(code)
  OrderDay.allSchemas.formSchema.forEach(item => {
      if (item.field == 'lineCode') {
        item.componentProps.options = lineOptions.value
      }
    })
}
//跟现在情况需要填写BOM版本号即可，其他跟随产品编码
// const getBoms = async (code: String) => {
//   bomOptions.value = await OrderDayApi.getBoms(code)
//   OrderDay.allSchemas.formSchema.forEach(item => {
//       if (item.field == 'standardBom') {
//         item.componentProps.options = bomOptions.value
//       }
//     })
// }
// 查询页面返回
const searchTableSuccess = (formField, searchField, val, formRef) => {
  nextTick(() => {
    const setV = {}
    setV[formField] = val[0][searchField]
    formRef.setValues(setV)
    if(formField=='productCode'){
      //formRef.setValues({standardBom:'bomddd'})
      getProcessroutes(val[0][searchField])
      //getBoms(val[0][searchField])
    }
    if(formField=='workroomCode'){
      getProductlines(val[0][searchField])
    }
    
})

}
const valueChange=(filed,cur)=>{
  if(filed=='noAutoFlag'){
    OrderDay.allSchemas.formSchema.forEach(item => {
      if (item.field == 'planNoDay') {
        item.componentProps.disabled = cur==='ENABLE'?true:false
        //console.log("item",OrderDayRules)
        OrderDayRules.planNoDay[0].required = cur==='ENABLE'?false:true
        //item.componentProps.required = cur==='ENABLE'?false:true
      }
    })
    
  }
 
}

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

const { tableObject, tableMethods } = useTable({
  getListApi: OrderDayApi.getOrderDayPage // 分页接口

})

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

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultAddBtn({hasPermi:'mes:orderDay:create'}), // 新增
  defaultButtons.defaultImportBtn({hasPermi:'mes:orderDay:import'}), // 导入
  defaultButtons.defaultExportBtn({hasPermi:'mes:orderDay:export'}), // 导出
  defaultButtons.defaultFreshBtn(null), // 刷新
  defaultButtons.defaultFilterBtn(null), // 筛选
  defaultButtons.defaultSetBtn(null), // 设置
]

// 头部按钮事件
const buttonBaseClick = (val, item) => {
  if (val == 'add') { // 新增
    openForm('create')
  } else if (val == 'import') { // 导入
    handleImport()
  } else if (val == 'export') { // 导出
    handleExport()
  } else if (val == 'refresh') { // 刷新
    getList()
  } else if (val == 'filtrate') { // 筛选
  }else{ // 其他按钮
    console.log('其他按钮', item)
  }
}
const publishClosed=()=>{
    console.log('orderday-publishClosed-200')
    nextTick(() => {
      getList()
    })
   
}
// 根据状态返回该按钮是否显示
const isShowMainButton = (row,val) => {
  //console.log('row',row)
  if (val.indexOf(row.status) > -1) {
    return false
  } else {
    return true
  }
}
// 列表-操作按钮
// 列表-操作按钮
//TERMINALE("4", "已终止"),PROCESSING("3", "生产中"),PUBLISHED("2", "待开工"),WAITSECHUDLE("1", "待排产"),CANCELED("-2", "已取消"),WAITREADY("-1", "待齐套");
const butttondata = (row) => {
     //console.log('row2',row)
    return [
    //defaultButtons.mainListEditBtn({ hide: isShowMainButton(row,['1']),hasPermi:'mes:orderDay:update'}), // 编辑
    defaultButtons.mainListDeleteBtn({ hide: isShowMainButton(row,['1']),hasPermi:'mes:orderDay:delete'}), // 删除
    defaultButtons.mainListHandleBtn({label: '排产',
      name: 'publish',
      hide: isShowMainButton(row,['1']),
      type: 'warning',
      icon: '',
      color: '',
      hasPermi: 'mes:orderDay:update'}), // 
    // defaultButtons.mainListHandleBtn({label: '发布',
    //   name: 'publish',
    //   hide: isShowMainButton(row,['2']),
    //   type: 'warning',
    //   icon: '',
    //   color: '',
    //   hasPermi: ''}), // 路由设置
      defaultButtons.mainListHandleBtn({label: '终止',
      name: 'stopPlan',
      hide: isShowMainButton(row,['-1','1','2','3']),
      type: 'warning',
      icon: '',
      color: '',
      hasPermi: 'mes:orderDay:update'}), // 路由设置
    ]
}


// 列表-操作按钮事件
const buttonTableClick =  (val, row) => {
  if (val == 'edit') { // 编辑
    openForm('update', row)
  } else if (val == 'delete') { // 删除
    handleDelete(row.id)
  } else if(val=='publish'){  //发布计划
    openScheduledDetail( '发布计划', row,row.planNoDay)
  }else if(val=='stopPlan'){  //终止计划
    stopPlan(row.id)
  }
   getList()
}

/** 添加/修改操作 */
const basicFormRef = ref()
const openForm = (type: string, row?: any) => {
  basicFormRef.value.open(type, row)
}

// form表单提交
const formsSuccess = async (formType,data) => {
  
  if (formType === 'create') {
    let ret= OrderDayApi.createOrderDay(data)
    if(ret===undefined || ret===null){
      message.error(t('common.networkError'))
    }else{
      message.success(t('common.createSuccess'))
    }
   
  } else {
    let ret= OrderDayApi.updateOrderDay(data)
    if(ret.code==0){
      message.success(t('common.updateSuccess'))
    }else{
      message.error(t('common.networkError'))
    }
    
  }
  
  basicFormRef.value.dialogVisible = false
  await getList()
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (row: any, titleName: any, titleValue: any) => {
  detailRef.value.openDetail(row, titleName, titleValue, 'basicOrderDay')
}
/** 发布操作 */
const scheduleDetailRef = ref()
const openScheduledDetail = (row: any, titleName: any, titleValue: any) => {
  scheduleDetailRef.value.open(row, titleName, titleValue)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderDayApi.deleteOrderDay(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const exportLoading = ref(false) // 导出的加载中
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderDayApi.exportOrderDay(tableObject.params)
    download.excel(data, '生产日计划.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const stopPlan = async (id) => {
   await OrderDayApi.stopPlan(id)
   //getList()
}
/** 导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}
// 导入附件弹窗所需的参数
const importTemplateData = reactive({
  templateUrl: '',
  templateTitle: '生产日计划导入模版.xlsx'
})
// 导入成功之后
const importSuccess = () => {
  getList()
}

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

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

</script>
