<template>
  <div ref="tableContainer">
    <div class="vue-element-page-wrap">
    <el-row class="page-search" justify="space-between" align="bottom">
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        :inline="true"
        label-width="80px"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="入库时间" prop="queryForm.params.DateValue">
              <el-date-picker
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="queryForm.params.DateValue"
                type="datetimerange"
                unlink-panels
                range-separator="To"
                v-model:start-placeholder="queryForm.params.FROMDATE"
                v-model:end-placeholder="queryForm.params.TODATE"
                :shortcuts="shortcuts2"
                :size="size"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="是否收货" prop="IS_CHECK">
              <el-select v-model="queryForm.params.IS_SURE" placeholder="是否确认" style="width: 240px"
                default-first-option>
                <el-option v-for="item in state.TEMPList" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button type="primary" @click="handleAdd">新建</el-button>
      </div>
    </el-row>
    <div class="vue-element-page-table">
      <el-table
        :height="500"
        border
        v-loading="undistributed_loading"
        :data="undistributed_list"
        highlight-current-row
        row-key="id"
      > 
        <template v-for="(col, index) in undistributed_column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="col.field === 'IS_SURE'">
                <span v-if="scope.row[col.field] == 'Y'">是</span>
                <span v-else >否</span>
              </span>
              <span v-else>{{ 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-column label="操作" align="center" fixed="right">
          <template #default="scope">
            <el-popconfirm v-if="scope.row.IS_SURE =='N'" title="需要确认收货吗?" @confirm="handleSure(scope.row)">
              <template #reference>
                <el-button type="primary" link> 收货 </el-button>
              </template>
            </el-popconfirm>
        </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-if="total > 0" :total="total" v-model:pageNumTo="queryForm.pageNum"
      v-model:pageSizeTo="queryForm.pageSize" @pagination="handleQuery" />
  </div>
  <div style="width: 300px">
    <el-drawer v-model="boxDrawer" title="创建物料" size="300px">
      <el-form ref="formDataRef"  label-position="top" :model="queryParam">
        <el-form-item label="组织" prop="ERPFACTORY">
            <el-select filterable v-model="queryParam.ERPFACTORY" placeholder="下拉选择组织">
<!--                       @change="GetERPLocationForList">-->
              <el-option v-for="item in ERPFactoryList" :key="item.ENUMVALUE" :label="item.DESCRIPTION"
                         :value="item.ENUMVALUE" />
            </el-select>
          </el-form-item>
          <el-form-item label="选择阶段" prop="PHASE">
            <el-select v-model="queryParam.PHASE" placeholder="选择阶段">
              <el-option label="" value="" />
              <el-option label="C" value="C" />
              <el-option label="D" value="D" />
              <el-option label="S" value="S" />
            </el-select>
          </el-form-item>
        <el-form-item label="料号" prop="MATERIALSPECNAME">
            <el-input v-model="queryParam.MATERIALSPECNAME" placeholder="请输入料号" @change="getSdkInfo"/>
          </el-form-item>
          <el-form-item label="选择SDK规格" prop="sdkid" >
            <el-select filterable v-model="queryParam.sdkid" placeholder="选择SDK规格" @click="getMATERIALSPECNAME"  :filter-method="locatioNFilter"
                       style="width: 300px">
              <!--                       @change="GetERPLocationForList">-->
              <el-option v-for="item in state.sdkList" :key="item.text" :label="item.text" lwhlslsk
                         :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="实际规格">
            <el-input v-model="queryParam.TRUEGG" placeholder="填写实际规格" />
          </el-form-item>
          <el-form-item label="总数量">
            <el-input v-model="queryParam.MATERIALQUANTITY" placeholder="填写总数量" />
          </el-form-item>
          <el-form-item label="选择单位" prop="UNIT">
            <el-select filterable v-model="queryParam.UNIT" placeholder="选择单位">
              <el-option v-for="item in state.unitList" :key="item.FNAME" :label="item.FNAME"
                         :value="item.FNUMBER" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="选择生产日期">
            <el-col :span="24">
              <el-date-picker
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="queryParam.MAKEDATE"
                type="datetime"
                placeholder="选择生产日期"
                style="width: 100%"
              />
            </el-col>
          </el-form-item> -->
          <el-form-item label="备注">
          <el-input v-model="queryParam.REMARK" placeholder="填写备注" />
        </el-form-item>
          <el-button type="primary" @click="getpows">新建</el-button>
        </el-form>
    </el-drawer>
  </div>
  </div>
  
</template>

<script lang="ts">
import { ref } from 'vue'
export default {
  name: "NChargeStockIn"
}
</script>

<script lang="ts" setup>
import { ElForm, ElMessageBox } from 'element-plus'
import { onMounted, reactive, toRefs, getCurrentInstance } from 'vue'
import { getSdkList, getUnitList } from '@/api/label'
import { addNChargeNOrder, checkNChargeNOrder } from '@/api/StockIn'
import { getQueryList,getQueryPageList } from '@/api/common'
import { localStorage } from '@/utils/storage'
import { msToDate } from '@/utils/CommonUtil'
import { bTableHeight } from "../../../composables/calcTableHeight";

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(0);
const { proxy }: any = getCurrentInstance();

const formDataRef = ref(ElForm)
const state = reactive({
  boxDrawer: false,
  loadings: false,
  button_print: false,
  TEMPList: [{ label: '是', value: 'Y' }, { label: '否', value: 'N' }] as any,
  queryForm: {
    queryId: "getCacheWareList",
    version: "00001",
    params: {
      DateValue: '',
      FROMDATE: '',
      TODATE: '',
      IS_SURE: ''
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParam: {
      SITENAME:'SDK',
      USERID: '',
      MATERIALSPECNAME: '',
      sdkid: '',
      PHASE: '',
      // MAKEDATE: '',
      MATERIALQUANTITY: '',
      ERPFACTORY: '',
      UNIT: '',
      TRUEGG: '',
      REMARK: '',
      IS_SURE: 'N'
  },
  queryParamsERPFactory: {
    queryId: 'GetErpFactoryList',
    version: 'WEB00001',
    params: {
      SITENAME: localStorage.get('siteName') || 'SDK'
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParamsSDK: {
    materialSpecName: ''
  },
  unit: '',
  PRINTLIST: [] as any, //打印机
  multipleSelection: [] as any,
  undistributed_column: [] as any,
  undistributed_list: [] as any,
  ERPFactoryList: [] as any,
  unitList: [] as any,
  sdkList: [] as any,
  sdkListAll: [] as any,
  undistributed_loading: false,
  total: 0
})

const {
  queryForm,
  queryParam,
  undistributed_column,
  undistributed_loading,
  undistributed_list,
  ERPFactoryList,
  boxDrawer,
  total,
  TEMPList
} = toRefs(state)

const size = ref<'default' | 'large' | 'small'>('default');
const shortcuts2 = [
  {
    text: '',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
onMounted(() => {
  state.undistributed_column = [
    {
      header: '料号',
      field: 'MATERIALSPECNAME',
      // width: '100px',
      hide: false
    },
    {
      header: '规格',
      field: 'SDK_ID',
      width: '100px',
      hide: false
    },
    {
      header: '阶段',
      field: 'PHASE',
      // width: '100px',
      hide: false
    },
    {
      header: '数量',
      field: 'MATERIALQUANTITY',
      width: '100px',
      hide: false
    },
    {
      header: '单位',
      field: 'UNIT',
      // width: '100px',
      hide: false
    },
    {
      header: '实际规格',
      field: 'TRUEGG',
      width: '100px',
      hide: false
    },
    {
      header: '是否收货',
      field: 'IS_SURE',
      // width: '100px',
      hide: false
    },
    {
      header: '日期时间',
      field: 'MAKEDATE',
      // width: '150px',
      hide: false
    },
    {
      header: '备注',
      field: 'REMARK',
      // width: '100px',
      hide: false
    },
    {
      header: '创建人',
      field: 'USERID',
      width: '50px',
      hide: false
    }
  ]
  handleQuery()
  ERPFactoryQuery()
  getUnitInfo()
  updateTableHeight();
  window.addEventListener('resize', handleResize);
})
function handleAdd() {
  state.boxDrawer = true;
}
async function handleQuery() {
  if (state.queryForm.params.DateValue.length > 0) {
    state.queryForm.params.FROMDATE = state.queryForm.params.DateValue[0]
    state.queryForm.params.TODATE = state.queryForm.params.DateValue[1]
  }
  await getQueryPageList(state.queryForm)
    .then((res: any) => {
      if (res.data.list.length > 0) {
        state.undistributed_list = res.data.list
        state.total = res.data.total
      } else {
        state.undistributed_list = res.data.list
        proxy.$ElMessage.success('查询结果为空');
      }

    })
}


function getpows() {
  // let time = formatDate(msToDate(state.queryParam.MAKEDATE).hasTime)
  state.queryParam.USERID = localStorage.get('userId')
  // state.queryParam.MAKEDATE = time
  if ('' == state.queryParam.MATERIALSPECNAME) {
    ElMessageBox.alert('请输入料号', {
      confirmButtonText: 'OK'
    })
    return
  }
  // if('1' != state.queryParam.materialreceiveAct.MATERIALSPECNAME.slice(0,1) || '2' != state.queryParam.materialreceiveAct.MATERIALSPECNAME.slice(0,1)){
  if ('6' == state.queryParam.MATERIALSPECNAME.slice(0, 1)) {
    if ('' == state.queryParam.PHASE) {
      ElMessageBox.alert('请输入阶段', {
        confirmButtonText: 'OK'
      })
      return
    }
  } else if (
    '3' == state.queryParam.MATERIALSPECNAME.slice(0, 1) ||
    '4' == state.queryParam.MATERIALSPECNAME.slice(0, 1)
  ) {
    if ('' == state.queryParam.sdkid) {
      ElMessageBox.alert('请输入规格', {
        confirmButtonText: 'OK'
      })
      return
    }
    if ('' == state.queryParam.PHASE) {
      ElMessageBox.alert('请输入阶段', {
        confirmButtonText: 'OK'
      })
      return
    }
  }
  // if ('NaN-NaN-NaN' == state.queryParam.MAKEDATE) {
  //   ElMessageBox.alert('请输入生产日期', {
  //     confirmButtonText: 'OK'
  //   })
  //   return
  // }
  if ('' == state.queryParam.MATERIALQUANTITY) {
    ElMessageBox.alert('请输入总数量', {
      confirmButtonText: 'OK'
    })
    return
  }
  if ('' == state.queryParam.ERPFACTORY) {
    ElMessageBox.alert('请输入组织', {
      confirmButtonText: 'OK'
    })
    return
  }
  if ('' == state.queryParam.UNIT) {
    ElMessageBox.alert('请输入单位', {
      confirmButtonText: 'OK'
    })
    return
  }
  addNChargeNOrder(state.queryParam)
    .then((res: any) => {
      if (res.code == 0) {
        state.undistributed_list = res.resultObj
        ElMessageBox.alert("新建成功", {
          confirmButtonText: 'OK'
        })
        state.boxDrawer = false;
        handleQuery()
      } else {
        ElMessageBox.alert(res.message, {
          confirmButtonText: 'OK'
        })
      }
    })
    .catch(() => {})
}

function getUnitInfo() {
  getUnitList(state.unit)
    .then((res: any) => {
      state.unitList = res.resultObj
    })
    .catch(() => {})
}

function handleSure(row: any) {
  let params = {...row};
  params.IS_SURE = "Y"
  checkNChargeNOrder({...params, USERID: localStorage.get('userId')})
      .then((res: any) => {
        handleQuery();
        proxy.$ElMessage.success('确认成功')
      }).catch(() => { })
}

function getMATERIALSPECNAME() {
  if (
    queryParam.value.MATERIALSPECNAME == null ||
    queryParam.value.MATERIALSPECNAME == ''
  ) {
    ElMessageBox.alert('请输入料号', {
      confirmButtonText: 'OK'
    })
    return
  }
}

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}`
}

function getSdkInfo() {
  state.sdkList = []
  state.queryParamsSDK.materialSpecName = queryParam.value.MATERIALSPECNAME
  getSdkList(state.queryParamsSDK)
    .then((res: any) => {
      state.sdkListAll = res.resultObj
      locatioNFilter('1')
    })
    .catch(() => {})
}

function locatioNFilter(query: any) {
  console.log(query)
  let arr = state.sdkListAll.filter((item: any) => {
    return item.text.includes(query) || item.value.includes(query)
  })
  if (arr.length > 50) {
    state.sdkList = arr.slice(0, 50)
  } else {
    state.sdkList = arr
  }
}

function ERPFactoryQuery() {
  getQueryList(state.queryParamsERPFactory)
    .then((res: any) => {
      state.ERPFactoryList = res.data
      state.ERPFactoryList.unshift({
        ENUMVALUE: ''
      })
    })
    .catch(() => {})
}

</script>

<style scoped>
.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: stretch;
}

.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.1);
    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;
        }
      }
    }
  }

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