<template>
  <div class="container">
    <el-card style="margin-bottom:10px;">
      <el-form :model="queryParams" ref="queryForm" labelWidth="90">
        <el-row style="height: 80;">
          <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10">
            <el-form-item label="产品编码">
              <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">
            <el-form-item label="产品名称">
              <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">
            <el-form-item label="规格">
              <el-input v-model="queryParams.specs" clearable="" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10">
            <el-form-item label="存货代码">
              <el-input v-model="queryParams.materialNo" clearable="" placeholder="请输入存货代码" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb10 ml10">
            <el-button-group>
              <el-button type="primary" icon="ele-Search" @click="handleQuery"> 查询
              </el-button>
              <el-button icon="ele-Refresh" @click="resetClick"> 重置 </el-button>
              <el-button type="primary" icon="ele-Download" @click="isShowImportDg = true" v-auth="'mesBarcodeMapMaterial/import'" :loading="importLoading"> 导入 </el-button>
            </el-button-group>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-row :gutter="12" class="height100">
      <el-col :span="8" class="height100">
        <el-card class="full-table">
          <div class="table_left">
            <el-table :data="tableData" size="small" style="width: 100%" height="100%" v-loading="loading" tooltip-effect="light" row-key="id" border :row-style="tableRowClassName" @row-click="cellClick">
              <el-table-column prop="materialCode" label="产品编码" width="150" show-overflow-tooltip="" />
              <el-table-column prop="materialName" label="产品名称" width="110" show-overflow-tooltip="" />
              <el-table-column prop="specs" label="规格型号" width="145" show-overflow-tooltip="" />
              <el-table-column prop="materialTypeCode" label="产品分类" show-overflow-tooltip="">
                <template #default="scope">
                  <span>{{ scope.row.materialTypeCodeMaterialTypeName }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <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" :pager-count="5" @current-change="handleCurrentChange" layout="total, prev, pager, next" />
        </el-card>
      </el-col>

      <el-col :span="16" class="height100">
        <el-card  v-if="currentRow.materialName">
          <div class="right_top">
            <span style="font-size:14px;font-weight:600;">{{ `【${currentRow.materialCode}：
           ${currentRow.materialName}】信息管理` }}</span>
            <span>
              <el-button type="success" size="small" icon="ele-Edit" :disabled="currentRow.isLock" @click="saveDataPar" > 保存
              </el-button>
              <el-button icon="ele-Edit" size="small" @click="quxiaoClick"> 取消
              </el-button>
            </span>
          </div>
          <div class="center_form">
            <el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" disabled>
              <el-row :gutter="12">
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb20">
                  <el-form-item label="MES编码" prop="materialCode">
                    <el-input v-model="ruleForm.materialCode" placeholder="请输入MES编码" maxlength="100" show-word-limit clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb20">
                  <el-form-item label="MES名称" prop="materialName">
                    <el-input v-model="ruleForm.materialName" placeholder="请输入MES名称" maxlength="100" show-word-limit clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb20">
                  <el-form-item label="规格型号" prop="specs">
                    <el-input v-model="ruleForm.specs" placeholder="请输入规格型号" maxlength="200" show-word-limit clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb20">
                  <el-form-item label="存货代码" prop="materialNo">
                    <el-input v-model="ruleForm.materialNo" placeholder="请输入存货代码" maxlength="100" show-word-limit clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb20">
                  <el-form-item label="计量单位组名称" prop="unitGroupName">
                    <el-input v-model="ruleForm.unitGroupName" placeholder="请输入计量单位组名称" maxlength="100" show-word-limit clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb20">
                  <el-form-item label="计量单位名称" prop="unitName">
                    <el-input v-model="ruleForm.unitName" placeholder="请输入计量单位名称" maxlength="100" show-word-limit clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb20">
                  <el-form-item label="产品单重长度" prop="unitWeightLength">
                    <el-input v-model="ruleForm.unitWeightLength" placeholder="请输入产品单重长度" maxlength="100" show-word-limit clearable />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <el-tabs v-model="activeName" :before-leave="tabBeforeLeve" style="margin-top: -16px">
            <el-tab-pane label="Bom清单" name="bom"> </el-tab-pane>
            <el-tab-pane label="工艺路线配置" name="craftline"></el-tab-pane>
          </el-tabs>
          <div class="right_bom_class" style="width: 100%">
            <Bom :material="currentRow" ref="bom" v-if="activeName == 'bom'" @submitAduitAfter="submitAduitAfter" > </Bom>
            <CraftLine :material="currentRow" ref="craftline" @submitAduitAfter="submitAduitAfter" v-if="activeName == 'craftline'" ></CraftLine>
          </div>
        </el-card>
        <el-card class="height100" v-else> </el-card>
      </el-col>
    </el-row>
    <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>
    <!-- <el-dialog v-model="versionShow" :width="600" destroy-on-close>
      <template #header>
        <div style="color: #fff">
          <span>版本更新</span>
        </div>
      </template>
      <div>
        <el-form-item label="版本号">
          <el-input v-model="versionStr" placeholder="请输入版本号" maxlength="100" show-word-limit clearable />
        </el-form-item>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="versionShow = false">取 消</el-button>
          <el-button type="primary" @click="versionSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog> -->
  </div>
</template>
<script setup lang="ts" name="mesproduct">
// import { deepClone } from '/@/utils/other.ts';
import { importExcel,excelTemplate  } from '/@/api/mes/mesProduct';
import { pageMesMaterial, detailMesMaterial } from '/@/api/mes/mesMaterial';
import { ElMessageBox, ElMessage } from 'element-plus';
import { onBeforeRouteLeave } from 'vue-router';
import Bom from './components/Bom.vue';
import CraftLine from './components/CraftLine.vue';
import { downloadByData, getFileName} from '/@/utils/download';
import { ref, onMounted } from 'vue';
import { version } from 'os';
const loading = ref(false);
const versionShow = ref(false);
const versionStr = ref('');
const tableData = ref<any>([]);
const queryParams = ref<any>({});
const ruleForm = ref({});
const activeName = ref('bom');
const tools = ref();
const zhidao = ref();
const bom = ref();
// const tuzhi = ref();
// const files = ref();
const craftline = ref();
const craftfile = ref();
const currentRow = ref({});
const tableParams = ref({
  page: 1,
  pageSize: 20,
  total: 0,
});
let versionRemark = {};
const leaveVaild = async (activeName: string) => {
  if (!currentRow.value.materialCode) {
    return true;
  }
  let ischange = false;
  if (activeName == 'bom') {
    ischange = bom.value.vaildChange();
  } else if (activeName == 'craftline') {
    ischange = craftline.value.vaildChange();
  }
  // else if (activeName == 'craft') {
  //   ischange = craftfile.value.vaildChange();
  // } else if (activeName == 'pfmea' || activeName == 'control' || activeName == 'qingdan') {
  //   ischange = files.value.vaildChange();
  // } else if (activeName == 'tuzhi') {
  //   ischange = tuzhi.value.vaildChange();
  // } else if (activeName == 'tools') {
  //   ischange = tools.value.vaildChange();
  // } else if (activeName == 'zhidao') {
  //   ischange = zhidao.value.vaildChange();
  // }

  if (ischange) {
    const res = await ElMessageBox.confirm(`数据未保存，确定离开?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
  } else {
    return true;
  }
};
onBeforeRouteLeave(async () => {
  return await leaveVaild(activeName.value);
});

const getdetail = (id: any) => {
  detailMesMaterial(id).then((res) => {
    currentRow.value = res.data.result;
    handleQuery();
  });
};

let callback: () => {};
const quxiaoClick = () => {
  currentRow.value = {};
};
// const suoding = (num: number) => {
//   if (num == 1) {
//     ElMessageBox.confirm(`确定锁定数据?`, '提示', {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'success',
//     }).then((res) => {
//       lock({
//         productCode: currentRow.value.materialCode,
//         lock: num,
//       }).then((res) => {
//         getdetail(currentRow.value.id);
//         ElMessage({
//           type: 'success',
//           message: '锁定完成',
//         });
//       });
//     });
//   } else {
//     lock({
//       productCode: currentRow.value.materialCode,
//       lock: num,
//     }).then((res) => {
//       getdetail(currentRow.value.id);
//       ElMessage({
//         type: 'success',
//         message: '解锁完成',
//       });
//     });
//   }
// };
// const versionClick = (data: any, done: () => {}) => {
//   versionRemark = deepClone(data);
//   versionStr.value = '';
//   callback = done;
//   versionShow.value = true;
// };
const submitAduitAfter = () => {
  getdetail(currentRow.value.id);
};
// const versionSubmit = () => {
//   if (!versionStr.value) {
//     ElMessage({
//       type: 'warning',
//       message: '请输入版本号',
//     });
//     return;
//   }
//   updateVer({
//     ...versionRemark,
//     verNo: versionStr.value,
//   }).then((res) => {
//     getdetail(currentRow.value.id);
//     //   versionStr.value
//     versionShow.value = false;
//     if (callback) {
//       callback();
//     }
//     ElMessage({
//       type: 'success',
//       message: '更新完成',
//     });
//   });
// };

const tabBeforeLeve = async (activeName, oldActiveName) => {
  return await leaveVaild(oldActiveName);
};
const getFileType = () => {
  if (activeName.value == 'pfmea') {
    return 2;
  } else if (activeName.value == 'control') {
    return 3;
  } else if (activeName.value == 'qingdan') {
    return 4;
  }
};

const cellClick = (row, column, event) => {
  leaveVaild(activeName.value).then((res) => {
    console.log(row);
    currentRow.value = row;
    ruleForm.value = row;
  });
};
const resetClick = () => {
  queryParams.value = {};
  currentRow.value = {};
  handleQuery();
};
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.id == currentRow.value.id) {
    return 'background-color:#e2ef9c;';
  }
  return '';
};

const saveDataPar = () => {
  if (activeName.value == 'bom') {
    bom.value.saveData();
  } else if (activeName.value == 'craftline') {
    craftline.value.saveData();
  }
  // else if (activeName.value == 'craft') {
  //   craftfile.value.saveData();
  // } else if (activeName.value == 'pfmea' || activeName.value == 'control' || activeName.value == 'qingdan') {
  //   files.value.saveData();
  // } else if (activeName.value == 'tuzhi') {
  //   tuzhi.value.saveData();
  // } else if (activeName.value == 'tools') {
  //   tools.value.saveData();
  // } else if (activeName.value == 'zhidao') {
  //   zhidao.value.saveData();
  // }
};

// 查询操作
const handleQuery = async () => {
  loading.value = true;
  var res = await pageMesMaterial(Object.assign({ ...queryParams.value,productType:2  }, tableParams.value));
  tableData.value = res.data.result?.items ?? [];
  tableParams.value.total = res.data.result?.total;
  loading.value = false;
};
// 改变页面容量
const handleSizeChange = (val: number) => {
  tableParams.value.pageSize = val;
  handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
  tableParams.value.page = val;
  handleQuery();
};
// onMounted(() => {
handleQuery();
// });

const exportLoading = ref(false);
const importLoading = ref(false);
//导出
const exportClick = async () => {
  exportLoading.value = true;
//   var res = await exportExcel(Object.assign(queryParams.value, tableParams.value));
//   exportLoading.value = false;
//   var fileName = getFileName(res.headers);
//   downloadByData(res.data as any, fileName);
};
const isShowImportDg = ref<Boolean>(false);
//下载模板
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();
};
</script>

<style lang="scss" scoped>
.center_form {
  padding: 8px 0px;
}

.container {
  width: 100%;
  height: 100%;
}

.right_bom_class {
  height: 520px;
  overflow: auto;
}

.right_top {
  height: 36px;
  border-bottom: 1px solid #3d3d3d;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

::v-deep.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: rgba(0, 0, 0, 0) !important;
}

.table_left {
  height: calc(100% - 60px);
}

::v-deep .table_left.success-row {
}

.height100 {
  height: 90%;
}

</style>
