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

  <!-- 列表头部 -->
  <TableHead
    :HeadButttondata="HeadButttondata"
    @button-base-click="buttonBaseClick"
    :routeName="routeName"
    @updataTableColumns="updataTableColumns"
    @searchFormClick="searchFormClick"
    :allSchemas="CountPlanMain.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 }">
        <ButtonBase
          :Butttondata="butttondata(row, $index)"
          @button-base-click="buttonTableClick($event, row)"
        />
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BasicFormWmsCount
    ref="formRef"
    @success="getList"
    :rules="CountPlanMainRules"
    :formAllSchemas="CountPlanMain.allSchemas"
    :tableAllSchemas="CountPlanDetail.allSchemas"
    :tableFormRules="CountPlanDetailRules"
    :tableData="tableData"
    :apiUpdate="CountPlanMainApi.updateCountPlanMain"
    :apiCreate="CountPlanMainApi.createCountPlanMain"
    :CountPlanMain1FormAllSchemas="CountPlanMain1.allSchemas"
    fromeWhere="countPlan"
    :countScopeType="getStrDictOptions(DICT_TYPE.COUNT_SCOPE_TYPE)"
    @handleAddTable="handleAddTable"
    @handleDeleteTable="handleDeleteTable"
    :isShowReduceButtonSelection="true"
    @tableSelectionDelete="tableSelectionDelete"
    @searchTableSuccess="searchTableSuccess"
    @submitForm="submitForm"
    @formSelectChange="formSelectChange"
    @formSelectvVisibleChange="formSelectvVisibleChange"
    @selectChange="selectChange"
    @tableFormChange="tableFormChange"
    @onChange="onChange"
  />

  <!-- 详情 -->
  <Detail
    ref="detailRef"
    :isBasic="false"
    :allSchemas="CountPlanMain.allSchemas"
    :detailAllSchemas="CountPlanDetail.allSchemas"
    :detailAllSchemasRules="CountPlanDetailRules"
    :searchTableParams="searchTableParams"
    :apiCreate="CountPlanDetailApi.createCountPlanDetail"
    :apiUpdate="CountPlanDetailApi.updateCountPlanDetail"
    :apiPage="CountPlanDetailApi.getCountPlanDetailPage"
    :apiDelete="CountPlanDetailApi.deleteCountPlanDetail"
    :allList="allList"
    :countScopeType="getStrDictOptions(DICT_TYPE.COUNT_SCOPE_TYPE)"
    :Echo="Echo"
    @selectChangeDetail="selectChangeDetail"
    fromeWhere="countPlan"
    :formTypeDetail="formTypeDetail"
    :countPlanAllList="countPlanAllList"
    @searchTableSuccessDetail="searchTableSuccessDetail"
    @detailOpenForm="detailOpenForm"
    :detailButtonIsShowFilter="false"
  />

  <!-- 导入 -->
  <ImportForm
    ref="importFormRef"
    url="/wms/count-plan-main/import"
    :importTemplateData="importTemplateData"
    @success="importSuccess"
  />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import {
  CountPlanDetail,
  CountPlanDetailRules,
  CountPlanMain,
  CountPlanMainRules,
  CountPlanMain1
} from './countPlanMain.data'
import * as CountPlanMainApi from '@/api/wms/countPlanMain'
import * as CountPlanDetailApi from '@/api/wms/countPlanDetail'
import { Owner } from '@/views/wms/basicDataManage/orderManage/owner/owner.data'
import * as OwnerApi from '@/api/wms/owner'

import { Supplier } from '@/views/wms/basicDataManage/supplierManage/supplier/supplier.data'
import * as SupplierApi from '@/api/wms/supplier'

import { Customer } from '@/views/wms/basicDataManage/customerManage/customer/customer.data'
import * as CustomerApi from '@/api/wms/customer'

import { Itembasic } from '@/views/wms/basicDataManage/itemManage/itembasic/itembasic.data'
import * as ItembasicApi from '@/api/wms/itembasic'

import { Warehouse } from '@/views/wms/basicDataManage/factoryModeling/warehouse/warehouse.data'
import * as WarehouseApi from '@/api/wms/warehouse'

import { Area } from '@/views/wms/basicDataManage/factoryModeling/areabasic/areabasic.data'
import * as AreaApi from '@/api/wms/areabasic'

import { Locationgroup } from '@/views/wms/basicDataManage/factoryModeling/locationgroup/locationgroup.data'
import * as LocationgroupApi from '@/api/wms/locationgroup'

import { Location } from '@/views/wms/basicDataManage/factoryModeling/location/location.data'
import * as LocationApi from '@/api/wms/location'
import * as defaultButtons from '@/utils/disposition/defaultButtons'

import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import BasicFormWmsCount from '@/components/BasicForm/src/BasicFormWmsCount.vue'

// 盘点计划主
defineOptions({ name: 'CountPlanMain' })

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

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const tableColumns = ref(CountPlanMain.allSchemas.tableColumns)
const countPlanAllList = ref([]) //盘点详情子表新增的时候判断盘点范围值的下拉列表

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

// 查询列表页面参数设置
const searchTableParams = ref([
  {
    formField: 'productItemCode',
    searchTableTitle: '物料信息',
    searchTableAllSchemas: Itembasic.allSchemas,
    searchTablePage: ItembasicApi.getItembasicPage
  }
])

// 查询页面返回
const searchTableSuccess = (formField, searchField, val, formRef, type, row) => {
  nextTick(() => {
    if (type == 'tableForm') {
      if (formField == 'value') {
        row[formField] = val.map((item) => item.code).join(',')
      }
    } else {
      const setV = {}
      // setV[formField] = val[0][searchField]
      setV[formField] = val.map((item) => item.code).join(',')
      formRef.setValues(setV)
    }
  })
}
const searchTableSuccessDetail = (formField, searchField, val, formRef) => {
  nextTick(async () => {
    const setV = {}

    setV[formField] = val.map((item) => item.code).join(',')
    formRef.setValues(setV)
  })
}
const Echo = []

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

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

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

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

// 列表-操作按钮
const butttondata = (row, $index) => {
  return [
    defaultButtons.mainListPlanOpeBtn({
      hide: isShowMainButton(row, ['5']),
      hasPermi: 'wms:count-plan-main:open'
    }), // 打开
    defaultButtons.mainListPlanCloBtn({
      hide: isShowMainButton(row, ['1', '2', '3', '4']),
      hasPermi: 'wms:count-plan-main:close'
    }), // 关闭
    defaultButtons.mainListPlanSubBtn({
      hide: isShowMainButton(row, ['1']),
      hasPermi: 'wms:count-plan-main:submit'
    }), // 提交审批
    defaultButtons.mainListPlanTurBtn({
      hide: isShowMainButton(row, ['2']),
      hasPermi: 'wms:count-plan-main:reject'
    }), // 驳回
    defaultButtons.mainListPlanAppBtn({
      hide: isShowMainButton(row, ['2']),
      hasPermi: 'wms:count-plan-main:agree'
    }), // 审批通过
    defaultButtons.mainListPlanPubBtn({
      hide: isShowMainButton(row, ['3']),
      hasPermi: 'wms:count-plan-main:publish'
    }), // 发布
    defaultButtons.mainListPlanResBtn({
      hide: isShowMainButton(row, ['4']),
      hasPermi: 'wms:count-plan-main:resetting'
    }), // 重置
    defaultButtons.mainListEditBtn({
      hide: isShowMainButton(row, ['1']),
      hasPermi: 'wms:count-plan-main:update'
    }) // 编辑
  ]
}

// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'mainPlanOpe') {
    // 打开
    tableObject.loading = true
    CountPlanMainApi.open(row.id)
      .then(() => {
        message.success(t('打开成功'))
        tableObject.loading = false
        getList()
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanClo') {
    // 关闭
    await message.confirm('确认要关闭吗？')
    tableObject.loading = true
    CountPlanMainApi.close(row.id)
      .then(() => {
        message.success(t('关闭成功'))
        tableObject.loading = false
        getList()
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanSub') {
    // 提交审批
    await message.confirm(t('common.confirmSubmit'))
    tableObject.loading = true
    await CountPlanMainApi.submit(row.id)
    message.success(t('提交审批成功'))
    tableObject.loading = false
    await getList()
  } else if (val == 'mainPlanTur') {
    // 驳回
    await message.confirm('确认要驳回吗？')
    tableObject.loading = true
    CountPlanMainApi.reject(row.id)
      .then(() => {
        message.success(t('驳回成功'))
        tableObject.loading = false
        getList()
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanApp') {
    // 审批通过
    await message.confirm('确认要审批通过吗？')
    tableObject.loading = true
    CountPlanMainApi.agree(row.id)
      .then(() => {
        message.success(t('审批已通过'))
        tableObject.loading = false
        getList()
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanPub') {
    // 发布
    await message.confirm('确认要发布吗？')
    tableObject.loading = true
    CountPlanMainApi.publish(row.id)
      .then(() => {
        message.success(t('发布成功'))
        tableObject.loading = false
        getList()
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'mainPlanRes') {
    // 重置
    await message.confirm('确认要重置吗？')
    tableObject.loading = true
    CountPlanMainApi.resetting(row.id)
      .then(() => {
        message.success(t('common.updateSuccess'))
        tableObject.loading = false
        getList()
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  } else if (val == 'edit') {
    // 编辑
    openForm('update', row)
  } else if (val == 'delete') {
    // 删除
    handleDelete(row.id)
  }
}
const onChange = (field, value) => {
  console.log(field, value)
}
/** 添加/修改操作 */
const formRef = ref()
const openForm = async (type: string, row?: any) => {
  tableData.value = [
    {
      type: '',
      value: []
    }
  ] // 重置明细数据
  row = row ? row : {}
  // row.dimension = 'BY_INEVNEOTY'
  // CountPlanMain.allSchemas.formSchema.forEach((item) => {
  //   if (item.field == 'crontab') {
  //     item.componentProps.disabled = true
  //   }
  // })
  if (row.type == 'CYCLE') {
      CountPlanMain.allSchemas.formSchema.forEach((item) => {
        if (item.field == 'crontab') {
          item.componentProps.disabled = false
          item.label = '执行周期'
        }
      })
      CountPlanMainRules.crontab[0].required = true
    } else {
      CountPlanMainRules.crontab[0].required = false
      CountPlanMain.allSchemas.formSchema.forEach((item) => {
        if (item.field == 'crontab') {
          item.componentProps.disabled = true
          item.label = ''
        }
      })
    }
  formRef.value.open(type, row)

  // Promise.all([getOwnerAllList(),
  // getSupplierAllList(),
  // getCustomerAllList(),
  // getItembasicAllList(),
  // getWarehouseAllList(),
  // getAreaAllList(),
  // getLocationgroupAllList(),
  // getLocationAllList()])
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (row: any, titleName: any, titleValue: any) => {
  // getOwnerAllList()
  // getSupplierAllList()
  // getCustomerAllList()
  // getItembasicAllList()
  // getWarehouseAllList()
  // getAreaAllList()
  // getLocationgroupAllList()
  // getLocationAllList()
  detailRef.value.openDetail(row, titleName, titleValue,"planCountMain")
}
// 详情打开的编辑的时候设置盘点范围值列表
const detailOpenForm = (type, row) => {
  console.log(row)
  if (type == 'update') {
    if (
      row.type == 'OWNER' ||
      row.type == 'SUPPLIER' ||
      row.type == 'CUSTOMER' ||
      row.type == 'ABC' ||
      row.type == 'ITEMS_TYPE' ||
      row.type == 'ITEMS_GROUP' ||
      row.type == 'ITEM_CODE' ||
      row.type == 'WAREHOUSE_CODE' ||
      row.type == 'AREABASIC_CODE' ||
      row.type == 'LOCATIONGROUP_CODE' ||
      row.type == 'LOCATION_CODE'
    ) {
      formTypeDetail.value = 'Select'
      switch (row.type) {
        case 'OWNER':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '货主信息'
              item.componentProps.searchAllSchemas = Owner.allSchemas
              item.componentProps.searchPage = OwnerApi.getOwnerPage
            }
          })
          break
        case 'SUPPLIER':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '供应商信息'
              item.componentProps.searchAllSchemas = Supplier.allSchemas
              item.componentProps.searchPage = SupplierApi.getSupplierPage
            }
          })
          break
        case 'CUSTOMER':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '客戶信息'
              item.componentProps.searchAllSchemas = Customer.allSchemas
              item.componentProps.searchPage = CustomerApi.getCustomerPage
            }
          })
          break
        case 'ABC':
          countPlanAllList.value = getStrDictOptions(DICT_TYPE.ABC_CLASS)
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.component = 'Select'
              item.componentProps.isSearchList = false
              item.componentProps.options = getStrDictOptions(DICT_TYPE.ABC_CLASS)
            }
          })
          break
        case 'ITEMS_TYPE':
          countPlanAllList.value = getStrDictOptions(DICT_TYPE.ITEM_TYPE)
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.component = 'Select'
              item.componentProps.isSearchList = false
              item.componentProps.options = getStrDictOptions(DICT_TYPE.ITEM_TYPE)
            }
          })
          break
        case 'ITEMS_GROUP':
          countPlanAllList.value = getStrDictOptions(DICT_TYPE.ITEM_GROUP)
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.component = 'Select'
              item.componentProps.isSearchList = false
              item.componentProps.options = getStrDictOptions(DICT_TYPE.ITEM_GROUP)
            }
          })
          break
        case 'ITEM_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isInpuFocusShow = true
              item.componentProps.searchTitle = '物品信息'
              item.componentProps.searchAllSchemas = Itembasic.allSchemas
              item.componentProps.searchPage = ItembasicApi.getItembasicPage
            }
          })
          break
        case 'WAREHOUSE_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isInpuFocusShow = true
              item.componentProps.searchTitle = '仓库信息'
              item.componentProps.searchAllSchemas = Warehouse.allSchemas
              item.componentProps.searchPage = WarehouseApi.getWarehousePage
            }
          })
          break
        case 'AREABASIC_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isInpuFocusShow = true
              item.componentProps.searchTitle = '库区信息'
              item.componentProps.searchAllSchemas = Area.allSchemas
              item.componentProps.searchPage = AreaApi.getAreaPage
            }
          })
          break
        case 'LOCATIONGROUP_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isInpuFocusShow = true
              item.componentProps.searchTitle = '库位组信息'
              item.componentProps.searchAllSchemas = Locationgroup.allSchemas
              item.componentProps.searchPage = LocationgroupApi.getLocationgroupPage
            }
          })
          break
        case 'LOCATION_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isInpuFocusShow = true
              item.componentProps.searchTitle = '库位组信息'
              item.componentProps.searchAllSchemas = Location.allSchemas
              item.componentProps.searchPage = LocationApi.getLocationPage
            }
          })
          break
      }
    } else if (row.type == 'PROJECT') {
      formTypeDetail.value = 'InputString'
    }
  }
}

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

/** 导出按钮操作 */
const exportLoading = ref(false) // 导出的加载中
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CountPlanMainApi.exportCountPlanMain(tableObject.params)
    download.excel(data, '盘点计划主.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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

// 添加明细
const handleAddTable = () => {
  // tableFormKeys.formType=''
  tableFormKeys = {
    type: '',
    value: []
  }
  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, data) => {
  var isHave = CountPlanMain.allSchemas.formSchema.some(function (item) {
    return item.field === 'beginTime' || item.field === 'endTime'
  })
  if (isHave) {
    if (data.beginTime && data.endTime && data.beginTime >= data.endTime) {
      message.error('开始时间大于结束时间')
      return
    }
  }
  data.subList = tableData.value.map((item) => {
    return {
      type: item.type,
      value: item.value
    }
  }) // 拼接子表数据参数
  formRef.value.formLoading = true
  try {
    if (formType === 'create') {
      await CountPlanMainApi.createCountPlanMain(data)
      message.success(t('common.createSuccess'))
    } else {
      await CountPlanMainApi.updateCountPlanMain(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: '盘点计划主导入模版.xlsx'
})

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

// 筛选提交
const searchFormClick = (searchData) => {
  tableObject.params = {
    isSearch: true,
    filters: searchData.filters
  }
  getList() // 刷新当前列表
}
// 选择盘点类型的时候针对限值的操作
const selectChange = (field, val) => {
  console.log(field, val)
  console.log(CountPlanMain.allSchemas.formSchema)
  if (field == 'type') {
    // 循环盘点
    if (val == 'CYCLE') {
      console.log(CountPlanMain.allSchemas.formSchema)
      CountPlanMain.allSchemas.formSchema.forEach((item) => {
        if (item.field == 'crontab') {
          item.componentProps.disabled = false
          item.label = '执行周期'
        }
        if (item.field == 'limitedValue') {
          item.componentProps.disabled = true
        }
      })
      CountPlanMainRules.crontab[0].required = true
    } else {
      CountPlanMainRules.crontab[0].required = false
      CountPlanMain.allSchemas.formSchema.forEach((item) => {
        if (item.field == 'crontab') {
          item.componentProps.disabled = true
          item.label = ''
        }
        if (item.field == 'limitedValue') {
          item.componentProps.disabled = true
        }
      })
    }
    formRef.value.formRef.setValues({
      crontab: ''
    })
    // if (val == 'DYNAMIC') {
    //   CountPlanMain.allSchemas.formSchema.forEach(item=>{
    //     if(item.field == 'limitedValue'){
    //       item.label = '限值（%）'
    //       item.componentProps.min = 0
    //       item.componentProps.max = 100
    //       item.componentProps.disabled = false
    //     }
    //   })
    // } else if (val == 'LOW' || val == 'RANDOM') {
    //   CountPlanMain.allSchemas.formSchema.forEach(item=>{
    //     if(item.field == 'limitedValue'){
    //       item.label = '限值（%）'
    //       item.componentProps.min = 0
    //       item.componentProps.max =Infinity
    //       item.componentProps.disabled = false
    //     }
    //   })
    // } else {
    //   CountPlanMain.allSchemas.formSchema.forEach(item=>{
    //     if(item.field == 'limitedValue'){
    //       item.componentProps.disabled = true
    //     }
    //   })
    // }
  }
}
const formTypeDetail = ref('InputString') //盘点详情子表新增的时候判断盘点范围值显示输入框还是下拉框
// 详情新增的时候选择盘点范围类型的时候针对限值的操作
const selectChangeDetail = (field, val) => {
  console.log(field, val)
  if (field == 'type') {
    // CountPlanDetail.allSchemas.formSchema[1].value = ''
    if (
      val == 'OWNER' ||
      val == 'SUPPLIER' ||
      val == 'CUSTOMER' ||
      val == 'ABC' ||
      val == 'ITEMS_TYPE' ||
      val == 'ITEMS_GROUP' ||
      val == 'ITEM_CODE' ||
      val == 'WAREHOUSE_CODE' ||
      val == 'AREABASIC_CODE' ||
      val == 'LOCATIONGROUP_CODE' ||
      val == 'LOCATION_CODE'
    ) {
      formTypeDetail.value = 'Select'
      switch (val) {
        case 'OWNER':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '货主信息'
              item.componentProps.searchAllSchemas = Owner.allSchemas
              item.componentProps.searchPage = OwnerApi.getOwnerPage
            }
          })
          break
        case 'SUPPLIER':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '供应商信息'
              item.componentProps.searchAllSchemas = Supplier.allSchemas
              item.componentProps.searchPage = SupplierApi.getSupplierPage
            }
          })
          break
        case 'CUSTOMER':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '客戶信息'
              item.componentProps.searchAllSchemas = Customer.allSchemas
              item.componentProps.searchPage = CustomerApi.getCustomerPage
            }
          })
          break
        case 'ABC':
          countPlanAllList.value = getStrDictOptions(DICT_TYPE.ABC_CLASS)
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.component = 'Select'
              item.componentProps.isSearchList = false
              item.componentProps.options = getStrDictOptions(DICT_TYPE.ABC_CLASS)
            }
          })
          break
        case 'ITEMS_TYPE':
          countPlanAllList.value = getStrDictOptions(DICT_TYPE.ITEM_TYPE)
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.component = 'Select'
              item.componentProps.isSearchList = false
              item.componentProps.options = getStrDictOptions(DICT_TYPE.ITEM_TYPE)
            }
          })
          break
        case 'ITEMS_GROUP':
          countPlanAllList.value = getStrDictOptions(DICT_TYPE.ITEM_GROUP)
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.component = 'Select'
              item.componentProps.isSearchList = false
              item.componentProps.options = getStrDictOptions(DICT_TYPE.ITEM_GROUP)
            }
          })
          break
        case 'ITEM_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '物品信息'
              item.componentProps.searchAllSchemas = Itembasic.allSchemas
              item.componentProps.searchPage = ItembasicApi.getItembasicPage
            }
          })
          break
        case 'WAREHOUSE_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '仓库信息'
              item.componentProps.searchAllSchemas = Warehouse.allSchemas
              item.componentProps.searchPage = WarehouseApi.getWarehousePage
            }
          })
          break
        case 'AREABASIC_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '库区信息'
              item.componentProps.searchAllSchemas = Area.allSchemas
              item.componentProps.searchPage = AreaApi.getAreaPage
            }
          })
          break
        case 'LOCATIONGROUP_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '库位组信息'
              item.componentProps.searchAllSchemas = Locationgroup.allSchemas
              item.componentProps.searchPage = LocationgroupApi.getLocationgroupPage
            }
          })
          break
        case 'LOCATION_CODE':
          CountPlanDetail.allSchemas.formSchema.forEach((item) => {
            if (item.field == 'value') {
              item.componentProps.isSearchList = true
              item.componentProps.searchTitle = '库位组信息'
              item.componentProps.searchAllSchemas = Location.allSchemas
              item.componentProps.searchPage = LocationApi.getLocationPage
            }
          })
          break
      }
    } else if (val == 'PROJECT') {
      formTypeDetail.value = 'InputString'
    }
  }
}
// 选择盘点范围类型
const tableFormChange = async (field, val, row) => {
  // debugger
  console.log(field, val, row)
  if (field == 'type') {
    row.value = ''
    if (
      row.type == 'OWNER' ||
      row.type == 'SUPPLIER' ||
      row.type == 'CUSTOMER' ||
      row.type == 'ABC' ||
      row.type == 'ITEMS_TYPE' ||
      row.type == 'ITEMS_GROUP' ||
      row.type == 'ITEM_CODE' ||
      row.type == 'WAREHOUSE_CODE' ||
      row.type == 'AREABASIC_CODE' ||
      row.type == 'LOCATIONGROUP_CODE' ||
      row.type == 'LOCATION_CODE'
    ) {
      row.formType = 'Select'
      switch (val) {
        case 'OWNER':
          row.searchTable = {
            isInpuFocusShow: true,
            searchTitle: '货主信息',
            searchAllSchemas: Owner.allSchemas,
            searchPage: OwnerApi.getOwnerPage
          }
          break
        case 'SUPPLIER':
          row.searchTable = {
            isInpuFocusShow: true,
            searchTitle: '供应商信息',
            searchAllSchemas: Supplier.allSchemas,
            searchPage: SupplierApi.getSupplierPage
          }
          break
        case 'CUSTOMER':
          row.searchTable = {
            isInpuFocusShow: true,
            searchTitle: '客戶信息',
            searchAllSchemas: Customer.allSchemas,
            searchPage: CustomerApi.getCustomerPage
          }
          break
        case 'ABC':
          row.initOptions = getStrDictOptions(DICT_TYPE.ABC_CLASS)
          CountPlanDetail.allSchemas.tableFormColumns.forEach((item) => {
            if (item.field == 'value') {
              item.type = 'Select'
              item.isInpuFocusShow = false
              item.dictClass = 'string'
              item.dictType = 'abc_class'
            }
          })
          break
        case 'ITEMS_TYPE':
          row.initOptions = getStrDictOptions(DICT_TYPE.ITEM_TYPE)
          CountPlanDetail.allSchemas.tableFormColumns.forEach((item) => {
            if (item.field == 'value') {
              item.type = 'Select'
              item.isInpuFocusShow = false
              item.dictClass = 'string'
              item.dictType = 'item_type'
            }
          })
          break
        case 'ITEMS_GROUP':
          row.initOptions = getStrDictOptions(DICT_TYPE.ITEM_GROUP)
          CountPlanDetail.allSchemas.tableFormColumns.forEach((item) => {
            if (item.field == 'value') {
              item.type = 'Select'
              item.isInpuFocusShow = false
              item.dictClass = 'string'
              item.dictType = 'item_group'
            }
          })
          break
        case 'ITEM_CODE':
          row.searchTable = {
            isInpuFocusShow: true,
            searchTitle: '物品信息',
            searchAllSchemas: Itembasic.allSchemas,
            searchPage: ItembasicApi.getItembasicPage
          }

          break
        case 'WAREHOUSE_CODE':
          row.searchTable = {
            isInpuFocusShow: true,
            searchTitle: '仓库信息',
            searchAllSchemas: Warehouse.allSchemas,
            searchPage: WarehouseApi.getWarehousePage
          }
          break
        case 'AREABASIC_CODE':
          row.searchTable = {
            isInpuFocusShow: true,
            searchTitle: '库区信息',
            searchAllSchemas: Area.allSchemas,
            searchPage: AreaApi.getAreaPage
          }
          break
        case 'LOCATIONGROUP_CODE':
          row.searchTable = {
            isInpuFocusShow: true,
            searchTitle: '库位组信息',
            searchAllSchemas: Locationgroup.allSchemas,
            searchPage: LocationgroupApi.getLocationgroupPage
          }
          break
        case 'LOCATION_CODE':
          row.searchTable = {
            isInpuFocusShow: true,
            searchTitle: '库位组信息',
            searchAllSchemas: Location.allSchemas,
            searchPage: LocationApi.getLocationPage
          }
          break
      }
    } else if (row.type == 'PROJECT') {
      row.formType = 'InputString'
    }
  }
}

const allList = ref({
  ownerAllList: [],
  supplierAllList: [],
  customerAllList: [],
  itembasicAllList: [],
  warehouseAllList: [],
  areaAllList: [],
  locationgroupAllList: [],
  locationAllList: [],
  abcList: getStrDictOptions(DICT_TYPE.ABC_CLASS),
  itemTypeList: getStrDictOptions(DICT_TYPE.ITEM_TYPE),
  itemGroupList: getStrDictOptions(DICT_TYPE.ITEM_GROUP)
})
// 获取货主列表
const getOwnerAllList = async (row, update_countPlanAllList = false) => {
  let getLoading = null
  let res = null
  if (!allList.value.ownerAllList || allList.value.ownerAllList.length == 0) {
    try {
      getLoading = ElLoading.service({
        lock: true,
        text: 'loading...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      res = await OwnerApi.getOwnerList()
    } finally {
      getLoading?.close()
    }
  }

  if (res) {
    allList.value.ownerAllList = res.map((element) => {
      return {
        value: element.code,
        label: element.name
      }
    })
  }
  if (row) {
    row.initOptions = allList.value.ownerAllList
  }
  if (update_countPlanAllList) {
    countPlanAllList.value = allList.value.ownerAllList
  }
}
// 获取供应商列表
const getSupplierAllList = async (row, update_countPlanAllList = false) => {
  let getLoading = null
  let res = null
  if (!allList.value.supplierAllList || allList.value.supplierAllList.length == 0) {
    try {
      getLoading = ElLoading.service({
        lock: true,
        text: 'loading...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      res = await SupplierApi.getSupplierList()
    } finally {
      getLoading?.close()
    }
  }
  if (res) {
    allList.value.supplierAllList = res.map((element) => {
      return {
        value: element.code,
        label: element.name
      }
    })
  }
  if (row) {
    row.initOptions = allList.value.supplierAllList
  }
  if (update_countPlanAllList) {
    countPlanAllList.value = allList.value.supplierAllList
  }
}
// 获取供应商列表
const getCustomerAllList = async (row, update_countPlanAllList = false) => {
  let getLoading = null
  let res = null
  if (!allList.value.customerAllList || allList.value.customerAllList.length == 0) {
    try {
      getLoading = ElLoading.service({
        lock: true,
        text: 'loading...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      res = await CustomerApi.getCustomerList()
    } finally {
      getLoading?.close()
    }
  }
  if (res) {
    allList.value.customerAllList = res.map((element) => {
      return {
        value: element.code,
        label: element.name
      }
    })
  }
  if (row) {
    row.initOptions = allList.value.customerAllList
  }
  if (update_countPlanAllList) {
    countPlanAllList.value = allList.value.customerAllList
  }
}
// 获取物料代码列表
const getItembasicAllList = async (row, update_countPlanAllList = false) => {
  let getLoading = null
  let res = null
  if (!allList.value.itembasicAllList || allList.value.itembasicAllList.length == 0) {
    try {
      getLoading = ElLoading.service({
        lock: true,
        text: 'loading...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      res = await ItembasicApi.getItembasicList()
    } finally {
      getLoading?.close()
    }
  }
  if (res) {
    allList.value.itembasicAllList = res.map((element) => {
      return {
        value: element.code,
        label: element.name + '-' + element.code
      }
    })
  }
  if (row) {
    row.initOptions = allList.value.itembasicAllList
  }
  if (update_countPlanAllList) {
    countPlanAllList.value = allList.value.itembasicAllList
  }
}
// 获取仓库列表
const getWarehouseAllList = async (row, update_countPlanAllList = false) => {
  let getLoading = null
  let res = null
  if (!allList.value.warehouseAllList || allList.value.warehouseAllList.length == 0) {
    try {
      getLoading = ElLoading.service({
        lock: true,
        text: 'loading...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      res = await WarehouseApi.getWarehouseList({ available: 'TRUE' })
    } finally {
      getLoading?.close()
    }
  }
  if (res) {
    allList.value.warehouseAllList = res.map((element) => {
      return {
        value: element.code,
        label: element.name
      }
    })
  }
  if (row) {
    row.initOptions = allList.value.warehouseAllList
  }
  if (update_countPlanAllList) {
    countPlanAllList.value = allList.value.warehouseAllList
  }
}
// 获取库区列表
const getAreaAllList = async (row, update_countPlanAllList = false) => {
  let getLoading = null
  let res = null
  if (!allList.value.areaAllList || allList.value.areaAllList.length == 0) {
    try {
      getLoading = ElLoading.service({
        lock: true,
        text: 'loading...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      res = await AreaApi.getAreaList({ available: 'TRUE' })
    } finally {
      getLoading?.close()
    }
  }
  if (res) {
    allList.value.areaAllList = res.map((element) => {
      return {
        value: element.code,
        label: element.name + '-' + element.code
      }
    })
  }
  if (row) {
    row.initOptions = allList.value.areaAllList
  }
  if (update_countPlanAllList) {
    countPlanAllList.value = allList.value.areaAllList
  }
}
// 获取库位组列表
const getLocationgroupAllList = async (row, update_countPlanAllList = false) => {
  let getLoading = null
  let res = null
  if (!allList.value.locationgroupAllList || allList.value.locationgroupAllList.length == 0) {
    try {
      getLoading = ElLoading.service({
        lock: true,
        text: 'loading...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      res = await LocationgroupApi.getLocationgroupList({ available: 'TRUE' })
    } finally {
      getLoading?.close()
    }
  }
  if (res) {
    allList.value.locationgroupAllList = res.map((element) => {
      return {
        value: element.code,
        label: element.name
      }
    })
  }
  if (row) {
    row.initOptions = allList.value.locationgroupAllList
  }
  if (update_countPlanAllList) {
    countPlanAllList.value = allList.value.locationgroupAllList
  }
}
// 获取库位列表
const getLocationAllList = async (row, update_countPlanAllList = false) => {
  let getLoading = null
  let res = null
  if (!allList.value.locationAllList || allList.value.locationAllList.length == 0) {
    getLoading = ElLoading.service({
      lock: true,
      text: 'loading...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    res = await LocationpApi.getLocationList({ available: 'TRUE' })
    console.log('res', res)
  }
  if (res) {
    allList.value.locationAllList = res.map((element) => {
      return {
        value: element.code,
        label: element.name + '-' + element.code
      }
    })
  }
  if (row) {
    row.initOptions = allList.value.locationAllList
  }
  if (update_countPlanAllList) {
    countPlanAllList.value = allList.value.locationAllList
  }
  nextTick(() => {
    getLoading?.close()
  })
}
/** 初始化 **/
onMounted(async () => {
  getList()
})
</script>
