<template>
  <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-position="left">
        <el-row :gutter="20">
          <el-col :span="6" class="col_height">
            <el-form-item label="组织" prop="params.ERPFACTORY">
              <el-select filterable v-model="queryParams.params.ERPFACTORY" placeholder="下拉选择组织" @change="ERPLocationQuery">
                <el-option v-for="item in ERPFactoryList" :key="item.ERPFACTORY" :label="item.DESCRIPTION" :value="item.ERPFACTORY"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="仓库" prop="params.ERPLOCATION">
              <el-select v-model="state.ChangeERPLocation" multiple clearable collapse-tags placeholder="请选择仓库"
                         popper-class="custom-header" :max-collapse-tags="1"
                         @visible-change="GetLocationListForSomeERPLocation" filterable>
                <template #header>
                </template>
                <el-option v-for="item in state.ERPLocationList" :key="item.ENUMVALUE" :label="item.DESCRIPTION"
                           :value="item.ENUMVALUE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="货位" prop="params.LOCATIONNAME">
              <el-select v-model="state.ChangeLocation" multiple clearable collapse-tags placeholder="请选择货位"
                         popper-class="custom-header" :max-collapse-tags="1"
                         remote :remote-method="handleInput" filterable>
                <template #header>
                </template>
                <el-option v-for="item in state.LocationList" :key="item.storageName" :label="item.storageName"
                           :value="item.storageName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="物料编号" prop="params.MATERIALSPECNAME">
              <el-Input v-model="queryParams.params.MATERIALSPECNAME" placeholder="输入物料编号" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="阶段" prop="params.PHASE">
              <el-select v-model="queryParams.params.PHASE" placeholder="选择阶段" clearable>
                <el-option value="S" label="S"></el-option>
                <el-option value="D" label="D"></el-option>
                <el-option value="C" label="C"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="品名" prop="params.DESC_CN">
              <el-Input v-model="queryParams.params.DESC_CN" placeholder="输入品名" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="批次" prop="params.CHARGE">
              <el-Input v-model="queryParams.params.CHARGE" placeholder="输入批次" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="col_height">
            <el-form-item label="备注" prop="params.REMARK">
              <el-Input v-model="queryParams.params.REMARK" placeholder="输入备注" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="queryInfo">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </el-row>
    <!-- table 区域-->
    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>标签信息</span>
          </div>
        </div>
        <div class="page-table-operateBtns">
          <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px" />
              </el-button>
            </template>
            <ConfigTable :list="tableConfig.column" @updateList="updateList" />
          </el-popover>
        </div>
      </div>
      <el-table :height="tableHeight" border v-loading="loading" :default-sort="{ prop: 'MATERIALSPECNAME', order: 'descending' }"
                :data="state.dataList" highlight-current-row row-key="id" style="width: 100%" @selection-change="handleSelection">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <template v-for="(col, index) in tableConfig.column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" :prop="col.field" show-overflow-tooltip
                :width="col.width" :sort-orders="['descending', 'ascending']" :sortable="true"/>
        </template>
        <el-table-column width="100" label="操作" align="center" class-name="table-operation" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click.stop="refModal.showModal(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <pagination v-if="total > 0" :total="total" v-model:pageNumTo="queryParams.pageNum"
                    v-model:pageSizeTo="queryParams.pageSize" @pagination="handleQuery" />
      </div>
      <div>
        <el-form :model="state.updateParams" ref="formDataRef" label-position="left" :rules="rules">
          <el-row :gutter="22">
            <el-col :span="5">
              <el-form-item label="阶段" prop="PHASE">
                <el-select v-model="state.updateParams.PHASE" placeholder="选择阶段" clearable>
                  <el-option value="S" label="S"></el-option>
                  <el-option value="D" label="D"></el-option>
                  <el-option value="C" label="C"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" @click="updateInfo" v-loading.fullscreen.lock="state.loadings">更新</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <drawer ref="refModal" @refresh="handleQuery"/>
  </div>
</template>
<script lang="ts">
export default {
  name: 'notPosted'
}
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from 'vue'
import { ElForm, ElMessageBox, ElTable } from 'element-plus'
import { getQueryPageList,getQueryList } from '@/api/common'
import { areAllNotEmpty, msToDate } from '@/utils/CommonUtil';
import { localStorage } from '@/utils/storage'
import { updatePacking } from '@/api/material/notPosted'
import { bTableHeight } from '@/composables/calcTableHeight'
import { getORG } from '@/api/auth'
import { search } from '@/api/wareHouse'
import Drawer from './drawer.vue'
// 公共变量
const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(310)
const { proxy }: any = getCurrentInstance()
const tableConfig = ref({
  loading: false,
  column: [] as any,
  data: []
})
const queryFormRef = ref(ElForm)
const formDataRef = ref()
const refModal = ref()
// 变量
const state = reactive({
  dataList: [] as any, // 表格数据
  total: 0, // 总数
  selection: [] as any, // 多选
  loadings: false, // 更新按钮
  loading: true, // 表格
  ChangeERPLocation: [],
  ChangeLocation: [],
  // 组织
  ERPFactoryList: [] as any,
  // 仓库
  ERPLocationList: [] as any,
  // 货位
  LocationList: [] as any,
  // 查询参数
  queryParams: {
    queryId: 'NotPosted',
    version: 'G5001',
    params: {
      SITENAME: localStorage.get('siteName') || 'SDK',
      MATERIALSPECNAME: '', // 物料编号
      ERPFACTORY: '',
      CHARGE: '',
      ERPLOCATION: '',
      LOCATIONNAME: '',
      PHASE: '',
      DESC_CN: '',
      REMARK: '',
    },
    pageNum: 1,
    pageSize: 10
  },
  queryParamsERPLocation: {
    queryId: "GetErpLocationList",
    version: "WEB00001",
    params: {
      SITENAME: localStorage.get("siteName") || 'SDK',
      ERPFACTORYNAME: '',
    },
    pageNum: 1,
    pageSize: 10
  },
  // 更新参数
  updateParams: {
    CHARGE: '',
    EXPIRNGDATE: '',
    MAKEDATE: '',
    PHASE: ''
  },
  // 条件
  rules: {
    // CHARGE: [{required: true, message: '请输入批次号', trigger: 'blur'}],
    // EXPIRNGDATE: [{required: true, message: '请选择保质期', trigger: 'blur'}],
    // MAKEDATE: [{required: true, message: '请选择制造日期', trigger: 'blur'}],
    PHASE: [{required: true, message: '请选择阶段', trigger: 'blur'}],
  }
})
const { queryParams, total, loading, ERPFactoryList, rules } = toRefs(state)

// 加载
onMounted(() => {
  tableConfig.value.column = [
    { header: 'SITENAME', field: 'SITENAME', hide: true },
    { header: '组织', field: 'ERPFACTORY', hide: false },
    { header: '组织(CN)', field: 'ERPFACTORYDESC', hide: false, width: 100 },
    { header: '仓库编码', field: 'ERPLOCATION', hide: false, width: 100 },
    { header: "仓库名称", field: "ERPLOCATIONDESC", hide: false, width: 100 },
    { header: '货位', field: 'LOCATIONNAME', hide: false },
    { header: '货位名称', field: 'LOCATIONNAMEDESC', hide: false, width: 100 },
    { header: '物料编号', field: 'MATERIALSPECNAME', hide: false, width: 140 },
    { header: '品名', field: 'DESC_CN', hide: false, width: 140 },
    { header: '批次号', field: 'CHARGE', hide: false, width: 180 },
    { header: '标签', field: 'MATERIALPACKINGNAME', hide: false, width: 180 },
    { header: '阶段', field: 'PHASE', hide: false },
    { header: '系统规格', field: 'DESCRIPTION', hide: false, width: 100 },
    { header: 'SDK规格', field: 'SPECNAME', hide: false, width: 100 },
    { header: '数量', field: 'MATERIALQUANTITY', hide: false },
    { header: '单位', field: 'UNIT', hide: false },
    { header: '是否良品', field: 'OQARESULT', hide: false, width: 100 },
    { header: '保质期', field: 'EXPIRINGDATE', hide: false, width: 150 },
    { header: '制造日期', field: 'MAKEDATE', hide: false, width: 150 },
    { header: '入库时间', field: 'RECEIVETIME', hide: false, width: 150 },
    { header: '备注', field: 'REMARK', hide: false, width: 150 },
  ]
  handleQuery()
  getErpFactory()
  updateTableHeight()
  window.addEventListener('resize', handleResize)
})
// 搜索
function queryInfo() {
  state.queryParams.pageNum = 1
  handleQuery()
}
// 表格事件
const updateList = (col: any) => {
  tableConfig.value.column = col
}
// 多选
const handleSelection = (val: any) => {
  state.selection = val
}
// 更新
function updateInfo() {
  if (state.selection.length == 0) {
    ElMessageBox.alert('请选择条目', { confirmButtonText: 'OK' })
    return
  }
  formDataRef.value.validate((valid: any) => {
    if (!valid) {
      return
    }
    state.loadings = true;
    updatePacking({
      ...state.updateParams,
      dataList: state.selection,
    }).then((res: any) => {
      if (res.success) {
        ElMessageBox.alert('更新成功', '提醒框', {
          confirmButtonText: 'OK'
        })
        formDataRef.value.resetFields();
        handleQuery()
      } else {
        proxy.$ElMessage.error(res.message)
      }
      state.loadings = false;
    })
  });
}
// 查询
async function handleQuery() {
  state.loading = true
  state.queryParams.params.ERPLOCATION = ''
  if (state.ChangeERPLocation[0] != '')
    for (let i = 0; i < state.ChangeERPLocation.length; i++) {
      state.queryParams.params.ERPLOCATION = state.queryParams.params.ERPLOCATION + state.ChangeERPLocation[i] + ','
    }
  state.queryParams.params.LOCATIONNAME = ''
  if (state.ChangeLocation[0] != '')
    for (let i = 0; i < state.ChangeLocation.length; i++) {
      state.queryParams.params.LOCATIONNAME = state.queryParams.params.LOCATIONNAME + state.ChangeLocation[i] + ','
    }
  await getQueryPageList(state.queryParams).then((res: any) => {
    state.dataList = res.data.list
    state.total = res.data.total
    state.loading = false
  })
}
// 加载组织
function getErpFactory() {
  getORG({ orgNo: null }).then((res: any) => {
    state.ERPFactoryList = res.resultObj
    state.ERPFactoryList.unshift({
      ERPFACTORY: ''
    })
  })
}
// 重置
function resetQuery() {
  queryFormRef.value.resetFields();
  state.ChangeERPLocation = []
  state.ChangeLocation = []
  handleQuery();
}
//ERP库位查询
function ERPLocationQuery() {
  state.queryParamsERPLocation.params.ERPFACTORYNAME = state.queryParams.params.ERPFACTORY
  getQueryList(state.queryParamsERPLocation).then((res: any) => {
    state.ERPLocationList = res.data;
  });
}
function GetLocationListForSomeERPLocation(value: any) {
  if (!areAllNotEmpty(state.queryParams.params.ERPFACTORY)) {
    proxy.$ElMessage.warning('当前还未选择组织');
    state.queryParams.params.ERPLOCATION = ''
    state.ERPLocationList = []
    return
  }
  if (!areAllNotEmpty(state.queryParams.params.ERPLOCATION)) {
    return
  }
}

function handleInput(val: any) {
    let index = [1, 3, 4, 7, 8]
    if (index.indexOf(val.length) > -1) {
      state.LocationList = []
      search({
        storageName: val,
        orgNo: JSON.parse(localStorage.get('orgNo'))
      }).then((res:any) => {
        if (res.resultObj) {
          state.LocationList = res.resultObj
        } else {
          proxy.$ElMessage.warning(res.message);
        }
      })
    }
  }
</script>
<style>
.col_height {
  padding-top: 3.5px;
  padding-bottom: 3.5px;
}
</style>