<!--
  功能：功能描述 盘点流程创建
  作者：Libra
  邮箱：mingxichen@163.com
  时间：2024年04月12日 11:11:48
  版本：v2.0
  修改记录：
  修改内容：
  修改人员：陶庆峰
  修改时间：2024-05-10
-->
<template>
  <div class="page-horizontal-wrap" ref="tableContainer">
    <div class="page-left-container">
      <div class="left-form-container" style="min-height:150px">
        <el-form ref="formDataRef" label-position="left" label-width="120px" :model="formData" :rules="rules">
          <el-form-item label="日期" prop="PLANDATE">
            <el-date-picker v-model="formData.PLANDATE" type="date" placeholder="请选择日期" />
          </el-form-item>
          <el-form-item label="任务名称" prop="CHECKPLANNAME">
            <el-input v-model="state.formData.CHECKPLANNAME" :disabled="true" placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item label="盘点方式" prop="MOVEFLAG">
            <el-radio-group v-model="formData.MOVEFLAG">
              <el-radio :label="'Y'">动态盘点</el-radio>
              <el-radio :label="'N'">静态盘点</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="page-left-container-head">
        <div class="page-form-button">
          <!-- <el-button type="primary" class="el-button-center" v-loading="state.loading2" @click="CreateNumber"
            :disabled="state.button_state">生成入库单号</el-button> -->

          <el-button type="primary" class="el-button-center" v-loading="state.loading2" @click="handleCreate"
            :disabled="state.button_state">创建盘点单</el-button>
        </div>
      </div>
    </div>
    <div class="vue-element-page-wrap" ref="tableContainer">
      <el-row class="page-search" justify="space-between" align="bottom">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="40px" label-position="left">
          <el-row :gutter="24">
            <el-col :span="5">
              <el-form-item label="盘点方式" label-width="80px">
                <el-select clearable filterable remote v-model="queryParams.checkType" placeholder="请选择盘点方式"
                  class="product-input" @change="changeCheckType">
                  <el-option v-for="dict in state.checkTypeOption" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- v-if="queryParams.checkType == '全盘'" -->
            <el-col :span="5">
              <el-form-item label="组织" prop="MATERIALSPECNAME">
                <el-select clearable filterable v-model="queryParams.ERPFACTORY" placeholder="请选择组织"
                  class="product-input" @change="changeFac">
                  <el-option v-for="dict in state.erpFactoryList" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="queryParams.checkType != '全盘'">
              <el-form-item label="ERP库位" prop="erpLocation" label-width="65px">
                <!-- <el-select clearable multiple filterable remote v-model="queryParams.erpLocation" placeholder="请选择仓库编码"
                  allow-create class="product-input" @visible-change="GetLocationListForSomeERPLocation">
                  <el-option v-for="dict in state.ERPLocationList" :key="dict.ERPLOCATIONNAME" :label="dict.DESCRIPTION"
                    :value="dict.ERPLOCATIONNAME" />
                </el-select> -->
                <el-select clearable multiple collapse-tags filterable v-model="queryParams.erpLocation" placeholder="请选择仓库编码"
                  class="product-input" :filter-method="filterMethod" @change="GetLocationListForSomeERPLocation">
                  <template #header>
                    <el-checkbox
                      v-model="checkAll"
                      :indeterminate="state.indeterminate"
                      @change="handleCheckAll"
                    >
                      全部
                    </el-checkbox>
                  </template>
                  <el-option v-for="dict in state.ERPLocationList" :key="dict.ENUMVALUE" :label="dict.DESCRIPTION"
                    :value="dict.ENUMVALUE" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6" v-if="queryParams.checkType != '全盘'">
              <el-form-item label="货位" prop="ReservoirArea">
                <el-select clearable multiple collapse-tags filterable remote v-model="queryParams.LOCATIONNAME" placeholder="请选择货位"
                  allow-create class="product-input"  :filter-method="filterMethodhw" @change="GetLocationListForSomeERPhw">
                  <template #header>
                    <el-checkbox
                      v-model="checkAllhw"
                      :indeterminate="state.indeterminatehw"
                      @change="handleCheckAllhw"
                    >
                      全部
                    </el-checkbox>
                  </template>
                  <el-option v-for="dict in state.LOCATIONLIST" :key="dict.STORAGENAME" :label="dict.DESCRIPTION"
                    :value="dict.STORAGENAME" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" v-if="queryParams.checkType != '全盘'">
              <el-form-item label="料号" prop="MATERIALSPECNAME">
                <!-- <el-select clearable multiple filterable remote v-model="queryParams.MATERIALSPECNAME"
                  placeholder="请输入料号" collapse-tags class="product-input" :remote-method="getMateOption">
                  <el-option v-for="dict in state.MaterialPackingList" :key="dict.valueLabe" :label="dict.valueLabe"
                    :value="dict.valueLabe" />
                </el-select> -->
                <el-input v-model="queryParams.MATERIALSPECNAME" placeholder="请输入料号" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="page-search-btns">
          <el-button type="primary" style="width: 60px;" @click="handleQuery">查看</el-button>
          <el-button type="primary" style="width: 60px;" @click="resetForm">置空</el-button>
          <el-button type="primary" style="width: 60px;" @click="exportExcel" :disabled="state.disableds" v-loading="state.loadings">导出</el-button>
        </div>
      </el-row>
      <div class="vue-element-page-table">
        <div class="page-table-operate">
          <span>Box信息列表</span>
        </div>
        <el-table :height="tableHeight" border v-loading="loading" :data="list" height="600" highlight-current-row row-key="id">
          <template v-for="(col, index) in column" :key="index">
            <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ scope.row[col.field] }}</span>
              </template>
            </el-table-column>
          </template>
          <template v-slot:empty>
            <svg-icon icon-class="noData" width="160px" height="160px" />
          </template>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: 'buildSheet'
}
</script>
<script lang="ts" setup>
import { reactive, ref, nextTick, onMounted, toRefs, getCurrentInstance } from "vue";
import { ElForm, ElMessageBox } from "element-plus";
import { BpelEvent, getQueryList } from "@/api/common";
import dayjs from 'dayjs';
import exportDataToExcel from '@/utils/export-excel';
import { IFTRUE, areAllNotEmpty, msToDate } from "@/utils/CommonUtil"
import { bTableHeight } from "../../../composables/calcTableHeight";
import { getORG } from '@/api/auth';

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(120);
const { proxy }: any = getCurrentInstance();
const queryFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const state = reactive({
  queryParamsERPLocation: {
    queryId: "GetErpLocationList",
    version: "WEB00001",
    params: {
      SITENAME: localStorage.getItem("siteName") || 'SDK',
      ERPFACTORYNAME: '',
    },
    pageNum: 1,
    pageSize: 10
  },
  filList: [],
  filListhw: [],
  allfilterListhw: [] as any,
  checkAll: false,
  checkAllhw: false,
  indeterminate: false,
  indeterminatehw: false,
  loading2: false,
  disableds : false,
  loadings : false,
  LOCATIONLIST: [] as any,
  button_state: false,
  MaterialPackingList: [] as any,//料号下拉选项
  ReservoirAreaList: [] as any,//库区下拉选项
  erpLocationList: [] as any,//erp库位下拉选项
  ERPLocationList: [] as any,
  checkTypeOption: [
    {
      label: "全盘",
      value: "全盘",
    },
    {
      label: "其它盘",
      value: "其它盘",
    }
  ],
  erpFactoryList: [] as { label: '', value: '' }[],
    
  queryParams: {
    checkType: '全盘',
    ERPFACTORY: '',
    MATERIALSPECNAME: '',
    AREANAME: '',
    erpLocation: '',
    LOCATIONNAME: [],
  },
  filterLocation: '',
  formData: {
    PLANDATE: '',
    CHECKPLANNAME: '',
    MOVEFLAG: '',
  },
  rules: {
    PLANDATE: [{ required: true, message: "请输入日期", trigger: "change" }],
    MOVEFLAG: [{ required: true, message: "请选择盘点方式", trigger: "change" }],
  },
  list: [] as any,
  loading: false,
  column: [] as any,

});
const { queryParamsERPLocation, allfilterListhw,filList, ERPLocationList, formData, column, list, loading, rules, queryParams,checkAll,indeterminate,checkAllhw,indeterminatehw } = toRefs(state);

onMounted(() => {
  state.column = [
    {
      header: "条码",
      field: "MATERIALPACKINGNAME",
      width: "100px",
      hide: false,
    }, {
      header: "批次",
      field: "CHARGE",
      width: "100px",
      hide: false,
    },
    {
      header: "料号",
      field: "MATERIALSPECNAME",
      width: "100px",
      hide: false,
    },{
      header: "品名",
      field: "DESC_CN",
      width: "100px",
      hide: false,
    },{
      header: "仓库",
      field: "ERPLOCATIONDESC",
      width: "100px",
      hide: false,
    } ,{
      header: "仓库",
      field: "ERPLOCATION",
      width: "100px",
      hide: true,
    },{
      header: "货位",
      field: "LOCATIONNAME",
      width: "100px",
      hide: true,
    },{
      header: "货位",
      field: "LOCATIONNAMEDESC",
      width: "100px",
      hide: false,
    },
    {
      header: "阶段",
      field: "PHASE",
      width: "100px",
      hide: false,
    },{
      header: "物料规格",
      field: "DESCRIPTION",
      width: "100px",
      hide: false,
    },{
      header: "SDK规格",
      field: "SPECNAME",
      width: "100px",
      hide: false,
    }, {
      header: "数量",
      field: "MATERIALQUANTITY",
      width: "100px",
      hide: false,
    }, {
      header: "单位",
      field: "UNIT",
      width: "100px",
      hide: false,
    },{
      header: "入库日期",
      field: "RECEIVETIME",
      width: "100px",
      hide: false,
    }, {
      header: "生产日期",
      field: "MAKEDATE",
      width: "100px",
      hide: false,
    }, {
      header: "到期日",
      field: "EXPIRINGDATE",
      width: "100px",
      hide: false,
    }]
    
  let pwd: any = localStorage.getItem('remeberPwd');
  // state.queryParams.ERPFACTORY = JSON.parse(pwd).orgNo;
    
  getFactoryList()
  updateTableHeight();
  window.addEventListener('resize', handleResize);
});
function changeFac() {
  if(state.queryParams.checkType != '全盘') {
    ERPLocationQuery()
  }
}
function changeCheckType(val: any) {
  if (val === '全盘') {
    getFactoryList()
    state.queryParams.LOCATIONNAME = []
    state.queryParams.MATERIALSPECNAME = ''
    state.queryParams.erpLocation = ''
  } else {
    // ERPLocationQuery()
    // state.queryParams.ERPFACTORY = ''
  }

}

const handleCheckAll = (val: any) => {
  console.log(val)
  state.indeterminate = false;
  if (val) {
    state.queryParams.erpLocation = state.ERPLocationList.map((_: any) => _.ENUMVALUE)
  } else {
    state.queryParams.erpLocation = ''
  }
}
const handleCheckAllhw = (val: any) => {
  console.log(val)
  state.indeterminatehw = false;
  if (val) {
    // state.queryParams.LOCATIONNAME = state.LOCATIONLIST.map((_: any) => _.STORAGENAME)
    state.queryParams.LOCATIONNAME = state.allfilterListhw.map((_: any) => _.STORAGENAME)
    
  } else {
    state.queryParams.LOCATIONNAME = []
  }
}
function filterMethod (e: any) {
  // console.log('filterMethod',e)
  if(e) {
    state.filterLocation = e
    let filterList = state.filList.filter((item: any) => {
      if (item.DESCRIPTION !== undefined && typeof item.DESCRIPTION === 'string') {
        let des = item.DESCRIPTION
        return (des.toLowerCase().includes(state.filterLocation.toLowerCase()) || des.toLowerCase() == state.filterLocation.toLowerCase())
      }
    })
    // console.log('filterList',filterList)
    state.ERPLocationList = filterList
  }else {
    state.checkAll = false;
    state.ERPLocationList = state.filList
    // console.log('222222222',state.ERPLocationList)
  }
}
function filterMethodhw (e: any) {
  console.log('filterMethod',e)
  if(e) {
    let filterLocation = e
    let filterList = state.filListhw.filter((item: any) => {
      if (item.DESCRIPTION !== undefined && typeof item.DESCRIPTION === 'string') {
        let des = item.DESCRIPTION
        console.log(des.includes(filterLocation.toLowerCase()))
        console.log(des.toLowerCase(),filterLocation.toLowerCase())
        return (des.toLowerCase().includes(filterLocation.toLowerCase()) || des.toLowerCase() == filterLocation.toLowerCase())
        // return (des.indexOf(filterLocation.toLowerCase()) > 0 || des.toLowerCase() == filterLocation.toLowerCase())
      }
    })
    // console.log('filterList',filterList)
    // state.LOCATIONLIST = filterList
    state.allfilterListhw = filterList;
    if(filterList.length > 100){
        state.LOCATIONLIST = filterList.slice(0,100);
       
      } else {
        state.LOCATIONLIST = filterList;
      }
  }else {
    state.checkAllhw = false;
    // state.LOCATIONLIST = state.filListhw

    if(state.filListhw.length > 100){
        state.LOCATIONLIST = state.filListhw.slice(0,100);
       
      } else {
        state.LOCATIONLIST = state.filListhw;
      }
    // console.log('222222222',state.ERPLocationList)
  }
}
/**
 * 查询
 * */
// function ERPLocationQuery() {
//   getQueryList({
//     queryId: "GetErpLocationList",
//     version: "WEB00002",
//     params: {

//     },
//   })
//     .then((res: any) => {
//       state.ERPLocationList = res.data;
//       state.ERPLocationList.unshift({
//         ERPLOCATIONNAME: ''
//       });
//       state.filList = JSON.parse(JSON.stringify(state.ERPLocationList))
//     })
//     .catch(() => { });
// }
function ERPLocationQuery() {
  state.queryParamsERPLocation.params.ERPFACTORYNAME = state.queryParams.ERPFACTORY
  getQueryList(state.queryParamsERPLocation)
    .then((res: any) => {
      state.ERPLocationList = res.data;
      state.ERPLocationList.unshift({
        ENUMVALUE: ''
      });
      state.filList = JSON.parse(JSON.stringify(state.ERPLocationList))
    })
    .catch(() => { });
}
function GetLocationListForSomeERPLocation(value: any) {
  // console.log(1111,state.queryParams.erpLocation)
  // if(!state.queryParams.erpLocation.length) {
    state.ERPLocationList = []
    nextTick(() => {
      state.checkAll = false;
      state.ERPLocationList = state.filList
    })

    // console.log(state.queryParams.erpLocation)
    if(state.queryParams.erpLocation.length > 1) {
      state.LOCATIONLIST = []
      state.filListhw = []
      return
    }
  getQueryList({
    queryId: "GetErpLocationList",
    version: "WEB00003",
    params: {
      ERPLOCATION: state.queryParams.erpLocation
    },
  })
    .then((res: any) => {
      console.log(111)
      // state.LOCATIONLIST = res.data;
        // state.filListhw = JSON.parse(JSON.stringify(state.LOCATIONLIST))
      if(res.data.length > 100){
        state.LOCATIONLIST = res.data.slice(0,100);
        
      } else {
        state.LOCATIONLIST = res.data;
      }
      state.filListhw = JSON.parse(JSON.stringify(res.data))
      state.LOCATIONLIST.unshift({
          STORAGENAME: ''
        });
    })
    .catch(() => { });

}
function GetLocationListForSomeERPhw(value: any) {
  // console.log(1111,state.queryParams.erpLocation)
  // if(!state.queryParams.erpLocation.length) {
    state.LOCATIONLIST = []
    nextTick(() => {
      state.checkAllhw = false;
      // state.LOCATIONLIST = state.filListhw
      if(state.filListhw.length > 100){
        state.LOCATIONLIST = state.filListhw.slice(0,100);
        
      } else {
        state.LOCATIONLIST = state.filListhw;
      }
      
    })
}
function getFactoryList() {
  getORG({ orgNo: null}).then((res: any) => {
    state.erpFactoryList = res.resultObj.map((item: any) => {
      return {
        label: item.DESCRIPTION,
        value: item.ERPFACTORY
      }
    })
  });
}
/**
 * 列表查询
 * */
function handleQuery() {
  // 数组为空时，转为字符串
  Object.keys(state.queryParams).forEach((key) => {
    if (state.queryParams[key] && state.queryParams[key].length === 0) {
      state.queryParams[key] = ''
    }
  });
  let loactionString = ''
  for (let i = 0; i < state.queryParams.LOCATIONNAME.length; i++) {
    loactionString = loactionString + state.queryParams.LOCATIONNAME[i] + ','
  }
  let loactionString1 = ''
  for (let i = 0; i < state.queryParams.erpLocation.length; i++) {
    loactionString1 = loactionString1 + state.queryParams.erpLocation[i] + ','
  }
  let param = {}
  if (state.queryParams.checkType === '全盘') {
    if (!state.queryParams.ERPFACTORY) {
      proxy.$ElMessage.warning("请选择组织进行盘点")
      return
    }
    param = {
      ERPFACTORY: state.queryParams.ERPFACTORY,
      MATERIALSPECNAME: '',
      LOCATIONNAME: loactionString,
      erpLocation: ''
    }
  } else {
    param = {
      ERPFACTORY: state.queryParams.ERPFACTORY,
      MATERIALSPECNAME: state.queryParams.MATERIALSPECNAME,
      LOCATIONNAME: loactionString,
      erpLocation: loactionString1,
    }
  }
  queryFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      getQueryList({
        queryId: "GetBoxListBy_4",
        version: "00003",
        params: {
          userId: localStorage.getItem('userId'),
          ...param
        },
      }).then((res: any) => {
        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].RECEIVETIME != '' && res.data[i].RECEIVETIME != null)
            res.data[i].RECEIVETIME = msToDate(res.data[i].RECEIVETIME).withoutTime;
        }
        state.list = res.data
      });
    }
  });
}
async function handleCreate() {
  // debugger
  // CreateNumber()  //写入到DOM元素
  if (!areAllNotEmpty(state.queryParams.checkType)) {
    ElMessageBox.alert("盘点方式不能为空", "提示框", {
      confirmButtonText: 'OK',
    })
    return
  }
  if (state.list.length === 0) {
    proxy.$ElMessage.warning("批次信息为空")
    return
  }
  
  if (state.formData.PLANDATE == null || state.formData.PLANDATE == undefined ||   state.formData.PLANDATE == '') {
    ElMessageBox.alert("请选择日期", "提示框", {
      confirmButtonText: 'OK',
    })
    return
  }
  if (!areAllNotEmpty(state.formData.MOVEFLAG)) {
    ElMessageBox.alert("请选择盘点方式", "提示框", {
      confirmButtonText: 'OK',
    })
    return
  }
  let time = formatDate(msToDate(formData.value.PLANDATE).withoutTime)
  await getQueryList({
    queryId: "GeCheckPlanNumber",
    version: "00002",
    params: {
      SITENAME: 'SDK',
      PLANTYPE: state.queryParams.checkType, //盘点类型
      PLANDATE: time
    }
  }).then(async (res: any) => {
    if (res.data.length == 0) {
      state.formData.CHECKPLANNAME = time + '0001'
    } else {
      let WaterNumber = parseInt(res.data[0].CHECKPLANNAME.substring(8))//后四位流水号
      WaterNumber += 1; // 将数字加1
      let formattedNum = ''
      formattedNum = WaterNumber.toString().padStart(4, '0'); // 将数字转换为4位字符串，不足的部分用0填充
      state.formData.CHECKPLANNAME = time + formattedNum

    }
  })
  state.loading2 = true
  state.button_state = true
  formDataRef.value.validate(async (isValid: boolean) => {

    let PLANCONDITION = `ERPFACTORY:${state.queryParams.ERPFACTORY || '空'},MATERIALSPECNAME:${state.queryParams.MATERIALSPECNAME || '空'},AREANAME:${state.queryParams.AREANAME || '空'},erpLocation:${state.queryParams.erpLocation || '空'}`

    let list = state.list.map((item: any) => {
      return {
        CHECKMATERIALTYPE: '1',
        CHECKPACKINGTYPE: '1',
        CHECKPLANSTATE: 'Created',
        PLANTYPE: state.queryParams.checkType,
        PLANTYPENAME: state.queryParams.checkType,
        SYSLOCATION: item.LOCATIONNAME,
        BOXSTATE: item.STOCKSTATE,
        LASTACTION: item.LASTEVENTNAME,
        PLANCONDITION,
        ...item
      }
    })
    let query = {
      header: {
        MESSAGENAME: "OICCreateCheckPlan",
        LANGUAGE: "Chinese"
      },
      body: {
        BOXLIST: list,
        SITENAME: "SDK",
        PLANDATE: dayjs(state.formData.PLANDATE).format('YYYYMMDD'),
        CHECKPLANNAME: state.formData.CHECKPLANNAME,
        MOVEFLAG: state.formData.MOVEFLAG
      }
    }

    if (isValid) {
      await BpelEvent(query).then((res: any) => {
        if (IFTRUE(res)) {
          ElMessageBox.alert('盘点任务创建成功', '提醒框', {
            confirmButtonText: 'OK',
          })
        } else {
          ElMessageBox.alert(res.data.RETURNCODE + '->' + res.data.RETURNMESSAGE, '', {
            confirmButtonText: 'OK',
          })
        }

      });
    }
  });
  state.loading2 = false
  state.button_state = false
}

/**
 * 获取选项
 * */
function getMateOption(e: any) {
  if (!e) return
  let query = {
    queryId: "GetMaterialSpec_MeanTime",
    version: "00001",
    params: {
      SITENAME: 'SDK',
      MATERIALSPECNAME: e, //料号
    },
  }
  getQueryList(query).then((res: any) => {
    state.MaterialPackingList = res.data.map((item: any) => {
      return {
        valueLabe: item.MATERIALSPECNAME
      }
    })

  })


}
function getAreaOption(e: any) {
  if (!e) return
  let query = {
    queryId: "GetAreaName_check",
    version: "00001",
    params: {
      SITENAME: 'SDK',
      AREANAME: e, //库区
    },
  }
  getQueryList(query).then((res: any) => {
    state.ReservoirAreaList = res.data.map((item: any) => {
      return {
        valueLabe: item.AREANAME
      }
    })
  })


}
function getErpOption(e: any) {
  if (!e) return
  let query = {
    queryId: "GetERPLocationName",
    version: "00001",
    params: {
      SITENAME: 'SDK',
      ERPLOCATIONNAME: e, //库位
    },
  }
  getQueryList(query).then((res: any) => {
    state.erpLocationList = res.data.map((item: any) => {
      return {
        valueLabe: item.ERPLOCATIONNAME
      }
    })
  })
}
/**
 * 重置
 * */
function resetForm() {
  queryFormRef.value.resetFields();
  state.queryParams.checkType = "全盘"
}
/**
 * 导出
 * */
function exportExcel() {
  state.disableds = true;
  state.loadings = true;
  exportDataToExcel(state.list, '批次信息')
  state.disableds = false;
  state.loadings = false;
}

function getCurrentDate() {
  let date = new Date;
  let year = date.getFullYear();
  let month = ''; // 月份从0开始，所以需要加1
  let day = '';

  if ((date.getMonth() + 1) < 10) {
    month = '0' + (date.getMonth() + 1); // 如果月份小于10，前面补0
  }
  if ((date.getDate()) < 10) {
    day = '0' + date.getDate(); // 如果日期小于10，前面补0
  }

  return year + '' + month + '' + day;
}

async function CreateNumber() {
  if (!areAllNotEmpty(state.queryParams.checkType)) {
    ElMessageBox.alert("盘点方式不能为空", "提示框", {
      confirmButtonText: 'OK',
    })
    return
  }
  if (state.list.length === 0) {
    proxy.$ElMessage.warning("批次信息为空")
    return
  }
  let time = formatDate(msToDate(formData.value.PLANDATE).withoutTime)
  await getQueryList({
    queryId: "GeCheckPlanNumber",
    version: "00002",
    params: {
      SITENAME: 'SDK',
      PLANTYPE: state.queryParams.checkType, //盘点类型
      PLANDATE: time
    }
  }).then(async (res: any) => {
    if (res.data.length == 0) {
      state.formData.CHECKPLANNAME = time + '0001'
    } else {
      let WaterNumber = parseInt(res.data[0].CHECKPLANNAME.substring(8))//后四位流水号
      WaterNumber += 1; // 将数字加1
      let formattedNum = ''
      formattedNum = WaterNumber.toString().padStart(4, '0'); // 将数字转换为4位字符串，不足的部分用0填充
      state.formData.CHECKPLANNAME = time + formattedNum

    }
  })
}

function formatDate(dateString: any) {
  // 验证输入是否为有效的日期字符串  
  const date = new Date(dateString);
  if (isNaN(date.getTime())) {
    throw new Error('Invalid date string');
  }

  // 使用padStart方法来确保月份和日期都是两位数  
  const year = date.getFullYear().toString();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); // getMonth() 返回的是0-11  
  const day = date.getDate().toString().padStart(2, '0');

  // 拼接结果  
  return `${year}${month}${day}`;
} 
</script>

<style scoped>
.page-horizontal-wrap {
  display: flex;
  width: 100%;
  height: 100%;

  .page-left-container {
    width: 360px;
    height: 100%;
    background: #FFFFFF;
    border: 1px solid #DBDEE3;
    box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.10);
    border-radius: 4px;
    margin-right: 6px;
    padding: 10px;
    display: flex;
    flex-direction: column;

    :deep(.el-form-item) {
      margin-bottom: 20px;
    }

    .page-left-container-head {
      display: flex;
      justify-content: space-between;

      .page-form-title {
        font-size: 14px;
        color: #000000;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: bold;
        margin-bottom: 10px;

        .el-icon {
          cursor: pointer;
        }

        .el-button-center {
          align-items: center;
          width: 60px;
        }
      }
    }

  }

  .vue-element-page-wrap {
    flex: 1;
  }
}
</style>
