﻿<template>
  <div class="mesMaterial-container">
    <el-row :gutter="10" style="height: 100%;">
      <el-col :span="4" style="height: 100%;">
        <treeFilter @node-click="typeClick"></treeFilter>
      </el-col>
      <el-col :span="20" style="display: flex;flex-direction: column;height: 100%;">
        <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
          <el-form :model="queryParams" ref="queryForm" labelWidth="90">
            <el-row style="height: 100%;">
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="MES编码">
                  <el-input v-model="queryParams.materialCode" clearable="" placeholder="请输入MES编码" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="MES名称">
                  <el-input v-model="queryParams.materialName" clearable="" placeholder="请输入MES名称" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="存货代码">
                  <el-input v-model="queryParams.materialNo" clearable="" placeholder="请输入存货代码" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="规格">
                  <el-input v-model="queryParams.specs" clearable="" placeholder="请输入规格" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10 ml10">
                <el-button-group>
                  <el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'mesMaterial/page'"> 查询
                  </el-button>
                  <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>
                </el-button-group>
                <el-button-group style="margin-left:20px">
                  <el-button type="primary" icon="ele-Plus" @click="openAddMesMaterial" v-auth="'mesMaterial/add'"> 新增
                  </el-button>
                  <el-button type="primary" icon="ele-Download" @click="isShowImportDg= true"  :loading="importLoading"> 导入 </el-button>
                </el-button-group>
                <el-button-group style="margin-left:20px">
                  <el-button type="primary" icon="ele-RefreshRight" v-auth="'u8/getMaterial'" @click="syncClick"> 同 步
                  </el-button>
                  <el-button type="primary" icon="ele-Histogram" @click="historySync">
                  </el-button>
                </el-button-group>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card class="full-table" shadow="hover" style="margin-top: 8px;">
          <el-table :data="tableData" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id"
            border="">
            <el-table-column type="index" label="序号" width="55" align="center" />
            <el-table-column prop="materialCode" label="MES编码" width="140" show-overflow-tooltip="" />
            <el-table-column prop="materialName" label="MES名称" width="140" show-overflow-tooltip="" />
            <el-table-column prop="materialTypeCode" label="存货分类编码" width="100" />
            <el-table-column prop="materialTypeCode" label="存货分类" width="90">
              <template #default="scope">
                <span>{{ scope.row.materialTypeCodeMaterialTypeName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="materialTypeCode" label="存货类型" width="90">
              <template #default="scope">
                <span v-if="scope.row.productType==0">原材料</span>
                <span v-if="scope.row.productType==1">半成品</span>
                <span v-if="scope.row.productType==2">产成品</span>
              </template>
            </el-table-column>
            <el-table-column prop="specs" label="规格型号" width="140" show-overflow-tooltip="" />
            <el-table-column prop="materialNo" label="存货代码" width="140" show-overflow-tooltip="" />
            <el-table-column prop="unitGroupName" label="计量单位组名称" width="105" show-overflow-tooltip="" />
            <el-table-column prop="unitName" label="计量单位名称" width="90" show-overflow-tooltip="" />
            <el-table-column prop="unitWeightLength" label="产品单重长度" width="90" show-overflow-tooltip="" />
            <el-table-column prop="workHour" label="工时(小时)" width="90" show-overflow-tooltip="" />
            <el-table-column prop="inOutRecord" label="出库跟踪入库" width="90" show-overflow-tooltip="" />
            <el-table-column prop="aBCType" label="ABC分类" width="140" show-overflow-tooltip="" />
            <el-table-column prop="featureSelection" label="特征选配" width="140" show-overflow-tooltip="" />
            <el-table-column prop="activeDate" label="启用日期" width="140" show-overflow-tooltip="" />
            <el-table-column prop="disabledDate" label="停用日期" width="140" show-overflow-tooltip="" />
            <el-table-column prop="price" label="单价" width="140" show-overflow-tooltip="" />
            <el-table-column label="操作" width="200" align="center" fixed="right" 
              >
              <template #default="scope">
                <!-- <el-button icon="ele-MessageBox" size="small" text="" type="primary" @click="getKuCun(scope.row)"
                  v-auth="'u8/currentstock'"> 查看库存 </el-button> -->
                <el-button icon="ele-Edit" size="small" text="" type="primary" @click="openEditMesMaterial(scope.row)"
                  v-auth="'mesMaterial/update'"> 编辑 </el-button>
                <el-button icon="ele-Delete" size="small" text="" type="primary" @click="delMesMaterial(scope.row)"
                  v-auth="'mesMaterial/delete'"> 删除 </el-button>
                <!-- <el-button icon="ele-RefreshRight" size="small" text="" v-auth="'u8/syncBom'" type="primary" @click="syncMesBom(scope.row)"> 同步Bom </el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize"
            :total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" small="" background=""
            @size-change="handleSizeChange" @current-change="handleCurrentChange"
            layout="total, sizes, prev, pager, next, jumper" />

            <el-dialog v-model="isShowImportDg" :width="800" draggable="" destroy-on-close>
              <template #header>
              <div style="color: #fff">
                <el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
                  <ele-Download />
                </el-icon>
                <span> 导入 </span>
              </div>
            </template>
            <el-row>
              <el-col>
                <el-upload :show-file-list="false" drag :http-request="onImport" accept=".xlsx">
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    拖拽文件到这里上传 或者<em>点击上传</em>
                  </div>
                  <template #tip>
                    <el-button type="primary" style="margin-top:10px" link @click="downloadTemplate">点击下载模板</el-button>
                  </template>
                </el-upload>
              </el-col>
            </el-row>
          </el-dialog>
          <printDialog ref="printDialogRef" :title="printMesMaterialTitle" @reloadTable="handleQuery" />
          <editDialog ref="editDialogRef" :title="editMesMaterialTitle" @reloadTable="handleQuery" />
          <syncProcess ref="syncProcessRef" />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog v-model="isShowDialog" :width="750" draggable="">
      <template #header>
        <div style="color: #fff">
          <!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
          <span>库存信息</span>
        </div>
      </template>
      <div>
        <div>
          只显示有库存记录<el-switch v-model="onlyShow" @change="onOnlyShow"></el-switch>
        </div>
        <el-table :data="storeData" style="width: 100%" v-loading="storeLoading" tooltip-effect="light" row-key="id" border="">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column prop="whcode" label="仓库编码" width="90" show-overflow-tooltip="" />
          <el-table-column prop="whname" label="仓库名称" width="90" show-overflow-tooltip="" />
          <el-table-column prop="invcode" label="MES编码" width="90" show-overflow-tooltip="" />
          <el-table-column prop="invname" label="MES名称" show-overflow-tooltip="" />
          <el-table-column prop="qty" label="现存数量" width="90" show-overflow-tooltip="" />
          <el-table-column prop="availqty" label="可用数量" width="90" show-overflow-tooltip="" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup="" name="mesMaterial">
import { ref } from "vue";
import { ElMessageBox, ElMessage ,UploadRequestOptions} from "element-plus";
import { auth } from '/@/utils/authFunction';
import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import { formatDate } from '/@/utils/formatTime';
import {  importExcel,excelTemplate} from '/@/api/simple/mesVirtualPackLog';
import editDialog from '/@/views/mes/mesMaterial/component/editDialog.vue'
import {pageMesMaterial, deleteMesMaterial, getMaterials, currentstock, SyncBom} from '/@/api/mes/mesMaterial';
import { downloadByData, getFileName} from '/@/utils/download';
import treeFilter from '/@/views/mes/mesMaterialType/component/treeFilter.vue'
import syncProcess from '/@/views/mes/components/syncProcess/index.vue'
const syncProcessRef = ref();
const historySync = () => {
  syncProcessRef.value.openDialog();
}
const isShowImportDg = ref<Boolean>(false);
  const importLoading = ref(false);
const isShowDialog = ref(false);
const showAdvanceQueryUI = ref(true);
const printDialogRef = ref();
const editDialogRef = ref();
const loading = ref(false);
const tableData = ref<any>([]);
const queryParams = ref<any>({materialTypeCode:''});
const tableParams = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});

const printMesMaterialTitle = ref("");
const editMesMaterialTitle = ref("");

// 改变高级查询的控件显示状态
const changeAdvanceQueryUI = () => {
  showAdvanceQueryUI.value = !showAdvanceQueryUI.value;
}
const syncClick = () => {
  ElMessageBox.confirm(`确定要同步数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success',
  })
    .then(async () => {
      await getMaterials(queryParams.value.materialTypeCode);
      ElMessage.success('开始同步');
    })
    .catch(() => { });
}

const storeData = ref<any>([]);
const orgStoreData = ref<any>([]);
const storeLoading = ref<boolean>(false);
const onlyShow = ref<boolean>(false);
const getKuCun = async (row: any) => {
  isShowDialog.value = true;
  storeLoading.value = true;
  var res = await currentstock(row.materialName,row.materialCode).finally(()=>{ storeLoading.value = false; });
  orgStoreData.value = res.data.result;
  onOnlyShow();
}
const onOnlyShow = ()=>{
  storeData.value = onlyShow.value?orgStoreData.value.filter((u:any)=>{ return u.availqty>0||u.qty>0 }) : orgStoreData.value;

}

// 查询操作
const handleQuery = async () => {
  loading.value = true;
  var res = await pageMesMaterial(Object.assign(queryParams.value, tableParams.value));
  tableData.value = res.data.result?.items ?? [];
  tableParams.value.total = res.data.result?.total;
  loading.value = false;
};

// 打开新增页面
const openAddMesMaterial = () => {
  editMesMaterialTitle.value = '添加存货档案';
  editDialogRef.value.openDialog({});
};

// 打开编辑页面
const openEditMesMaterial = (row: any) => {
  editMesMaterialTitle.value = '编辑存货档案';
  editDialogRef.value.openDialog(row);
};

// 删除
const delMesMaterial = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteMesMaterial(row);
      handleQuery();
      ElMessage.success("删除成功");
    })
    .catch(() => { });
};

const syncMesBom = (row: any) => {
  ElMessageBox.confirm(`确定要同步bom信息吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await SyncBom(row.materialCode);
      handleQuery();
      ElMessage.success("操作成功");
    })
    .catch(() => { });
};

// 改变页面容量
const handleSizeChange = (val: number) => {
  tableParams.value.pageSize = val;
  handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
  tableParams.value.page = val;
  handleQuery();
};
// 点击树形筛选
const typeClick = (item: any) => {
  queryParams.value.materialTypeCode = item.materialTypeCode;
  handleQuery();
}

//下载模板
const downloadTemplate = async () => {
  var res = await excelTemplate({});
  var fileName = getFileName(res.headers);
  downloadByData(res.data as any, fileName);
}

//导入
const onImport = async (options: UploadRequestOptions) => {
  importLoading.value = true;
  const res = await importExcel(options);
  importLoading.value = false;
  var fileName = getFileName(res.headers);
  isShowImportDg.value = false; 
  if (fileName) {
    ElMessageBox.confirm(fileName.indexOf('异常')==-1? '导入成功，是否下载导入结果？' : '数据验证失败，是否下载查看原因？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async (res1: any) => {
        if (res1 == 'confirm') {
          downloadByData(res.data as any, fileName);
        }
      })
      .catch(() => {});
  }
  handleQuery();
};

handleQuery();
</script>
<style scoped>
:deep(.el-ipnut),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}
</style>

