<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="state.queryParams.params" :inline="true">
        <el-row :gutter="20">
          <el-col :span="6">
              <el-form-item label="组织" prop="erpFactory">
                <el-select v-model="queryParams.params.erpFactory" placeholder="下拉选择">
                    <el-option v-for="item in state.ERPFactoryList" :key="item.ERPFACTORY" :label="item.DESCRIPTION"
                        :value="item.ERPFACTORY" />
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="仓库编码" prop="params.erpLocation">
              <el-Input v-model="state.queryParams.params.erpLocation" placeholder="仓库编码查询" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货位编码" prop="params.storageName">
              <el-Input v-model="state.queryParams.params.storageName" placeholder="货位编码查询" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货位名称" prop="params.description">
              <el-Input v-model="state.queryParams.params.description" placeholder="货位名称查询" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货位属性" prop="params.storageUseType">
              <el-select
                size="small"
                filterable
                v-model="state.queryParams.params.storageUseType"
                default-first-option
                placeholder="请选择货位属性"
              >
                <el-option
                  v-for="item in state.storageUseTypeList"
                  :key="item.ENUMVALUE"
                  :label="item.ENUMVALUE"
                  :value="item.ENUMVALUE"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="queryInfo" :disabled="state.disableds" v-loadig="state.loadings">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>
    </el-row>

    <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-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            创建
          </el-button>
          <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="materialTableConfig.column" @updateList="updateList" />
          </el-popover>
        </div>
      </div>
      <el-table border :height="tableHeight" v-loading="materialTableConfig.loading" :data="state.wareHouseList" highlight-current-row
        row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <template v-for="(col, index) in materialTableConfig.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>

        <el-table-column width="300" label="操作" align="center" class-name="table-operation" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleUpdate(scope.row)" v-if="!scope.row.status"> 编辑
            </el-button>
            <div class="splitLine" v-if="!scope.row.status"></div>
            <el-button type="danger" link @click.stop="delConfirm(scope.row)" v-if="!scope.row.status"> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-if="total > 0" :total="total" v-model:pageNumTo="queryParams.pageNum"
        v-model:pageSizeTo="queryParams.pageSize" @pagination="handleQuery" />
    </div>
    <!-- 打印机 -->
    <div class="vue-element-page-table">
      <el-row class="page-search" justify="space-between" align="middle">
        <el-form ref="operateFormRef" :model="operateParams" :inline="true">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item label="选择打印机" v-model="state.PRINTNAME">
                <el-select v-model="state.PRINTNAME" placeholder="请选择打印机" style="width: 240px">
                  <el-option v-for="item in state.PRINTLIST" :key="item.VALUE" :label="item.LABEL" :value="item.VALUE" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-button type="primary" @click="print" :disabled="state.button_print" v-loading="state.loadings">打印</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </div>

    <!--  新增或编辑  -->
    <el-drawer :title="dialog.title" v-model="dialog.visible" @close="cancel" @opened="dialogOpend">
      <el-form ref="formDataRef" :model="formData" :rules="rules" label-position="top">
        <!-- <el-form-item label="组织编码" prop="erpFactory" v-if="dialog.type === 'add'">
          <el-input v-model="formData.erpFactory" placeholder="请输入组织编码" disabled/>
        </el-form-item> -->
        <el-form-item label="仓库编码" prop="erpLocation" v-if="dialog.type === 'add'">
          <el-input v-model="formData.erpLocation" placeholder="请输入仓库编码" v-on:keyup.enter="erpLocationEnter"/>
        </el-form-item>
        <el-form-item label="仓库名称" prop="erpLocationName" v-if="dialog.type === 'add'">
          <el-input v-model="formData.erpLocationName" placeholder="请输入仓库名称" disabled/>
        </el-form-item>
        <el-form-item label="货位编码" prop="storageName" v-if="dialog.type === 'add'">
          <el-input v-model="formData.storageName" placeholder="请输入货位编码" />
        </el-form-item>
        <el-form-item label="货位名称" prop="description">
          <el-input v-model="formData.description" placeholder="请输入货位名称" />
        </el-form-item>
        <el-form-item label="货位属性" prop="storageUseType">
          <el-select
            size="small"
            filterable
            v-model="formData.storageUseType"
            default-first-option
            placeholder="请选择货位属性"
          >
            <el-option
              v-for="item in state.storageUseTypeList"
              :key="item.ENUMVALUE"
              :label="item.ENUMVALUE"
              :value="item.ENUMVALUE"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts">
export default {
  name: "wareHouseLocation",
};
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance } from "vue";
import { ElForm, ElMessageBox, ElTable } from "element-plus";
import { BpelEvent, getQueryList } from '@/api/common'
import { bTableHeight } from '@/composables/calcTableHeight';
import { getORG } from '@/api/auth'
import { createStorage, delStorage, editStorage, page, getLocation } from '@/api/wareHouse'
import { localStorage as ls } from "@/utils/storage";
import { printStorage } from '@/api/label'

const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(300);
const queryFormRef = ref(ElForm);
const formDataRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();
const materialTableConfig = ref({
  loading: false,
  column: [] as any,
  data: [],
})

const state = reactive({
  ERPFactoryList: [] as any, // 组织
  storageUseTypeList: [] as any, //货位属性
  disableds : false,
  loadings : false,
  rsa: '',
  DBProcessType: 'save',
  queryParams: {
    params: {
      siteName: 'SDK',
      storageName: '',
      description: '',
      storageUseType: '',
      erpFactory: '',
      erpLocation: '',
    },
    pageNum: 1,
    pageSize: 10
  },
  formData: {
    siteName: 'SDK',
    createUser: localStorage.getItem('userName'),
    storageName: "",
    description: "",
    erpLocation: '',
    erpFactory: '',
    erpLocationName: ''
  } as any,
  dialog: {
    title: "新增货位",
    type: 'add',
    visible: false,
  },
  rules: {
    storageName: [{ required: true, message: "请输入货位编码", trigger: "blur" }],
    description: [{ required: true, message: "请输入货位名称", trigger: "blur" }],
    erpLocation: [{ required: true, message: "请输入仓库编码", trigger: "blur" }],
    erpLocationName: [{ required: true, message: "请输入仓库名称", trigger: "blur" }],
    // storageUseType: [{ required: true, message: "请输入货位属性", trigger: "blur" }],
  },
  // 打印机 start
  operateParams: {
    date: new Date()
  },
  PRINTNAME: '',
  PRINTLIST: [] as any,// 打印机
  button_print:false,
  // 打印机 end
  wareHouseList: [] as any,
  total: 0,
  selectItem: undefined as any,
  multipleSelection: [] as any
})

const {
  // 打印机 start
  operateParams,
  // 打印机 end
  queryParams,
  total,
  dialog,
  formData,
  rules,
  selectItem
} = toRefs(state);

onMounted(() => {
  materialTableConfig.value.column = [
    { header: "组织编码", field: "erpFactory", hide: false },
    { header: "组织名称", field: "orgName", hide: false },
    { header: "仓库编码", field: "erpLocation", hide: false },
    { header: "仓库名称", field: "erpLocationName", hide: false },
    { header: "货位编码", field: "storageName", hide: false },
    { header: "货位名称", field: "description", hide: false },
    { header: "货位属性", field: "storageUseType", hide: false }
  ]
  handleQuery();
  updateTableHeight();
  // 打印机
  getPRINTLIST();
  hangERPFactoryQuery();
  window.addEventListener('resize', handleResize);
  getStorageUseTypeList()
})
// 查询
const queryInfo = () =>  {
  state.queryParams.pageNum = 1
  handleQuery()
}
const handleQuery = () => {
  state.disableds = true;
  state.loadings = true;
  state.wareHouseList = [];
  page(state.queryParams).then((res: any) => {
    state.wareHouseList = res.resultObj.list;
    state.total = res.resultObj.total;
    state.disableds = false;
    state.loadings = false;
  })
}
const resetQuery = () => {
  queryFormRef.value.resetFields();
  state.queryParams.params.storageName = '';
  state.queryParams.params.description = '';
  state.queryParams.params.storageUseType = '';
  queryInfo()
}
const updateList = (col: any) => {
  materialTableConfig.value.column = col
}
/**
 * 新增货位 dialog
 */
function handleAdd() {
  selectItem.value = undefined;
  dialog.value = {
    title: "新增货位",
    visible: true,
    type: 'add'
  };
  getStorageUseTypeList()
}

/**
 * 编辑货位 dialog
 */
function handleUpdate(row: any) {
  state.dialog = {
    title: "编辑货位",
    visible: true,
    type: 'edit'
  };
  state.selectItem = row;
}

// 删除确认
function delConfirm(row: any) {
  ElMessageBox.confirm('确认删除?',
    '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      distinguishCancelAndClose: true,
      type: 'warning',
    }).then(() => {
    handleDelete(row);
  })
    .catch(() => { });
}

function dialogOpend() {
  formDataRef.value.resetFields();
  state.formData.storageName = ''
  state.formData.description = ''
  state.formData.storageUseType = ''
  if (state.selectItem && state.dialog.type === 'edit') {
    state.formData.storageName = state.selectItem.storageName
    state.formData.description = state.selectItem.description
    state.formData.storageUseType = state.selectItem.storageUseType
  }
}
/**
 * 取消关闭弹窗
 */
function cancel() {
  state.dialog.visible = false;
}
/**
 * 保存
 */
function submitForm() {
  formDataRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (state.selectItem) {
        // 编辑
        editStorage(state.formData).then((res: any) => {
          if (res.errorCode === 200) {
            proxy.$ElMessage.success(res.message);
            cancel();
            handleQuery();
          } else {
            proxy.$ElMessage.error(res.message);
          }
        })
      } else {
        createStorage(state.formData).then((res: any) => {
          if (res.errorCode === 200) {
            proxy.$ElMessage.success(res.message);
            cancel();
            handleQuery();
          } else {
            proxy.$ElMessage.error(res.message);
          }
        })
      }
    }
  });
}
/**
 * 删除
 * */
function handleDelete(row: any) {
  const params = {
    storageName: row.storageName,
    siteName: 'SDK',
  };
  delStorage(params).then((res: any) => {
    if (res.errorCode === 200) {
      proxy.$ElMessage.success(res.message);
      handleQuery();
    } else {
      proxy.$ElMessage.error(res.message);
    }
  });
}

/**
 * 打印机
 */
function print() {
  if (state.PRINTNAME == null || state.PRINTNAME == "") {
    ElMessageBox.alert('请选择打印机', {
      confirmButtonText: 'OK',
    })
    return
  }
  if (state.multipleSelection.length == 0) {
    ElMessageBox.alert('打印清单为空', {
      confirmButtonText: 'OK',
    })
    return
  }
  let PRINT = {
    LIST: state.multipleSelection,
    PRINTNAME: state.PRINTNAME,
    USER: ls.get('userId')
  }
  state.button_print = true;
  state.loadings = true;
  printStorage(PRINT).then((res: any) => {
    console.log('PRINT',res)
  }).catch(() => {
    state.button_print = false;
    state.loadings = false;
  });
  state.button_print = false;
  state.loadings = false;
  ElMessageBox.alert('标签打印成功', {
    confirmButtonText: 'OK',
  })
}

function getPRINTLIST() {
  getQueryList({
    queryId: "getPRINTLIST",
    version: "00001",
    params: {
    },
  }).then((res: any) => {
    state.PRINTLIST = res.data
  })
}

const handleSelectionChange = (val: any) => {
  state.multipleSelection = val;
}
function getStorageUseTypeList() {
  getQueryList({
    queryId: "GetEnumdefValueList",
    version: "04281",
    params: {
      ENUMNAME: 'StorageUseType_Bias'
    },
  }).then((res: any) => {
    state.storageUseTypeList = res.data
    state.storageUseTypeList.unshift({
      ENUMVALUE: ''
    })
  })
}

function hangERPFactoryQuery() {
    getORG({ orgNo: null}).then((res: any) => {
        state.ERPFactoryList = res.resultObj
    })

}

function erpLocationEnter() {
  getLocation({erpLocation: state.formData.erpLocation}).then((res: any) => {
    if(res.success && res.resultObj){
      state.formData.erpLocationName = res.resultObj.erpLocationName
      state.formData.erpFactory = res.resultObj.erpFactory
    }
  })
}
</script>
