<template>
  <div class="mainContentBox">
    <!--{{dataDetail}}-->
    <!--{{dicts}}-->
    <div class="detail-title">物料信息</div>
    <div class="detail">
      <div class="title-detail">物料编码 : {{ dataDetail.materialCode }}</div>
      <div class="title-detail">物料名称 : {{ dataDetail.materialName }}</div>
      <div class="title-detail">
        物料属性 : {{ dataDetail.attributeDictValue }}
      </div>

      <div class="title-detail">单位 : {{ dataDetail.unitDictValue }}</div>
      <div class="title-detail">物料级别 : {{ dataDetail.levelDictValue }}</div>
      <div class="title-detail">产品阶段 : {{ dataDetail.stageDictValue }}</div>
      <div class="title-detail">生产厂家 : {{ dataDetail.manufacturer }}</div>
      <div class="title-detail">创建时间 : {{ dataDetail.created }}</div>
      <div class="title-text">物料规格 : {{ dataDetail.spec }}</div>
      <div class="title-text">备注 : {{ dataDetail.remark }}</div>
    </div>
    <avue-crud
      ref="crudRef"
      v-model:search="search"
      v-model="form"
      :data="data"
      :option="option"
      @row-update="updateRow"
      @row-del="deleteRow"
      @search-change="searchChange"
      @search-reset="resetChange"
      @selection-change="selectionChange"
    >
      <template #menu-left="{ size }">
        <div style="display: flex">
          <el-button type="primary" icon="el-icon-plus" @click="openMaterial"
            >新增</el-button
          >
          <el-select
            v-model="version"
            placeholder="请选择BOM版本"
            ref="selectBom"
            style="width: 150px; margin-left: 15px"
            @click="openBomVersion"
            @focus="openBomVersion"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </template>

      <!--<CommonTable
        ref="ctableRef"
        tableTitle="物料选择"
        tableType="BOM"
        @selected-sure="onSelectedFinish"
      />-->
      <template #footer>
        <div class="detail-footer">
          <el-button type="primary" @click="onSelected"> 保存 </el-button>
          <el-button @click="routeBack">取消</el-button>
        </div>
      </template>

      <template #menu-right="{}">
        <el-dropdown split-button
          >导入
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="downloadTemplate('/api/v1/base/materialBom/template')"
              >
                <i-ep-download />下载模板
              </el-dropdown-item>
              <el-dropdown-item @click="importExcelData">
                <i-ep-top />导入数据
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <ExcelUpload ref="uploadRef" @finished="uploadFinished" />
      </template>
    </avue-crud>
    <CommonTable
      ref="ctableRef"
      tableTitle="BOM添加"
      :multipleRow="multipleRow"
      tableType="MARTERIAL"
      @selected-sure="onSelectedFinish"
    />
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="900px"
      @close="dialog.visible = false"
    >
      <version-page
        :materialCode="route.params.materialCode"
        :dialog="dialog"
        @selected-sure="selectedFinish"
      />
    </el-dialog>

  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "../../../hooks/userCrud";
import ButtonPermKeys from "../../../common/configs/buttonPermission";
import { useCommonStoreHook, useDictionaryStore } from "../../../store/index";

import { getMaterialDetails, getBomVersion } from "@/api/material";

import { batchAddBom } from "@/api/bom";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
// 数据字典相关
const { dicts } = useDictionaryStore();
const router = useRouter();
const route = useRoute();
const selectBom = ref({});
const dataDetail = ref({});
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};
const multipleRow = ref(true);
const openMaterial = () => {
  if (
    version.value.value === 0 ||
    version.value.value === null ||
    version.value.value == "0"
  ) {
    ElMessage({
      message: "没有选择BOM版本",
      type: "error",
    });
    return;
  }
  if (ctableRef.value) {
    startCreat();
    ctableRef.value.startSelect();
  }
};
const openBomVersion = () => {
  selectBom.value.blur();
  dialog.visible = true;
};
const version = ref({
  value: "0",
  label: "请选择BOM版本",
});
const options = ref([]);
const dataDict = dicts.value;
const dataBomLists = () => {
  search.value.materialCode = route.params.materialCode;
  dataNoPageList();
};

const ctableRef = ref({});
const dialog = reactive({
  title: "BOM版本",
  visible: false,
});
//defineExpose({ startCreat });
const material = ref(null);
const binding = (row) => {
  if (ctableRef.value) {
    ctableRef.value.startSelect();
  }
};
const startCreat = () =>{
  ctableRef.value?.mergeOption({
    selection: true,
    reserveSelection : true,
  });
}
const onSelected = () => {
  for (var i = 0; i < data.value.length; i++) {
    if (data.value[i].bomMaterialNumber <= 0) {
      ElMessage({
        message: data.value[i].bomMaterialName + "数量不能为0",
        type: "error",
      });
      return;
    }
  }
  if (data.value.length === 0) {
    ElMessage({
      message: "物料记录不能为空!",
      type: "error",
    });
    return;
  }
  batchAddBom(data.value).then((data) => {
    if (data.code === "200") {
      ElMessage({
        message: data.msg,
        type: "success",
      });
      router.back();
    } else {
      ElMessage({
        message: data.msg,
        type: "error",
      });
    }
  });
};
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/base/materialBom",
  });
const {
  dataNoPageList,
  createRow,
  updateRow,
  deleteRow,
  searchChange,
  resetChange,
} = Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
// checkBtnPerm(ButtonPermKeys.PLAN.BTNS.order_add) :permission="permission"
// const permission = reactive({
//   delBtn: checkPerm(buttonPermission.PLAN.BTNS.order_del),
//   addBtn: checkPerm(buttonPermission.PLAN.BTNS.order_add),
//   editBtn: checkPerm(buttonPermission.PLAN.BTNS.order_edit),
//   menu: true,
// });

const crudRef = ref(null); //crudRef.value 获取avue-crud对象

onMounted(() => {
  getBomVersion(route.params.materialCode).then((data) => {
    version.value.value = data.data;
    search.value.bomVersion = data.data;
    version.value.value = data.data;
    if (data.data != "0") {
      version.value.label = data.data;
    }
    search.value.materialCode = route.params.materialCode;
    queryMaterialDetail();
    dataNoPageList();
  });
});

/**
 * 上传excel相关
 */
const uploadRef = ref(null);
const uploadFinished = () => {
  // 上传完成后的刷新操作
  dataNoPageList();
};
const importExcelData = () => {
  if (uploadRef.value) {
    uploadRef.value.show(
      "/api/v1/base/materialBom/import?materialCode=" +
        route.params.materialCode
    );
  }
};

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  selection: false,
  addBtn: false,
  viewBtn: false,
  editBtn: false,
  saveBtn: false,
  cellBtn: true,
  column: [
    {
      label: "物料编码",
      prop: "materialCode",
      hide: true,
    },

    {
      label: "物料名称",
      prop: "materialName",
      overHidden: true,
      hide: true,
    },

    {
      label: "物料编码",
      prop: "bomMaterialCode",
    },
    {
      label: "物料名称",
      prop: "bomMaterialName",
      overHidden: true,
    },
    {
      label: "物料属性",
      prop: "bomMaterialAttribute",
      type: "select",
      dicData: dicts.material_properties,
      props: { label: "dictLabel", value: "dictValue" },
    },
    {
      label: "物料数量",
      prop: "bomMaterialNumber",
      min: 0,
      slot: true,
      cell: true,
      type: "number",
      precision: 2,
    },
    {
      label: "版本号",
      prop: "bomVersion",
      type: "number",
      precision: 1,
    },
  ],
});
const routeBack = () => {
  router.back();
};
const onSelectedFinish = (selectedValueList) => {
  if (Object.keys(selectedValueList).length === 0 || selectedValueList == undefined || selectedValueList == null || selectedValueList.length <= 0) {
    ElMessage({
      message: "没有选择任何物料",
      type: "error",
    });
    return false;
  }
  const flag = ref(true);
  selectedValueList?.forEach((selectedValue, index) => {
      if (selectedValue.materialCode == dataDetail.value.materialCode) {
        ElMessage({
          message: selectedValue.materialCode + "自己不能添加自己为BOM",
          type: "error",
        });
        flag.value=false;
        return;
      }
      for (var i = 0; i < data.value.length; i++) {
        if (data.value[i].bomMaterialCode === selectedValue.materialCode) {
          ElMessage({
            message: selectedValue.materialCode + "的" + data.value[i].bomMaterialName + "已经添加过了",
            type: "error",
          });
          flag.value=false;
          return;
        }
      }
      if (version.value.value === 0 || version.value.value === null) {
        ElMessage({
          message: "没有选择BOM版本",
          type: "error",
        });
        flag.value=false;
        return;
      }

    }
  );
  if(!flag.value){
    return;
  }
  selectedValueList?.forEach((selectedValue, index) => {
    const bom = ref({
      materialCode: route.params.materialCode,
      bomMaterialCode: selectedValue.materialCode,
      bomMaterialName: selectedValue.materialName,
      bomVersion: version.value.value,
      bomMaterialAttribute: selectedValue.attributeDictValue,
      bomMaterialNumber: 0,
      $cellEdit: true,
    });
    data.value.push(bom.value);
  });

};
const queryMaterialDetail = () => {
  getMaterialDetails(route.params.materialCode).then(({ data }) => {
    dataDetail.value = data;

    if (
      null != dicts.material_properties &&
      undefined != dicts.material_properties &&
      dicts.material_properties.length > 0
    ) {
      for (var i = 0; i < dicts.material_properties.length; i++) {
        if (
          data.attributeDictValue === dicts.material_properties[i].dictValue
        ) {
          dataDetail.value.attributeDictValue =
            dicts.material_properties[i].dictLabel;
        }
      }
    }

    if (
      null != dicts.danwei_type &&
      undefined != dicts.danwei_type &&
      dicts.danwei_type.length > 0
    ) {
      for (var i = 0; i < dicts.danwei_type.length; i++) {
        if (data.unitDictValue === dicts.danwei_type[i].dictValue) {
          dataDetail.value.unitDictValue = dicts.danwei_type[i].dictLabel;
        }
      }
    }
    if (
      null != dicts.material_level &&
      undefined != dicts.material_level &&
      dicts.material_level.length > 0
    ) {
      for (var i = 0; i < dicts.material_level.length; i++) {
        if (data.levelDictValue === dicts.material_level[i].dictValue) {
          dataDetail.value.levelDictValue = dicts.material_level[i].dictLabel;
        }
      }
    }
    if (
      null != dicts.stage &&
      undefined != dicts.stage &&
      dicts.stage.length > 0
    ) {
      for (var i = 0; i < dicts.stage.length; i++) {
        if (data.stageDictValue === dicts.stage[i].dictValue) {
          dataDetail.value.stageDictValue = dicts.stage[i].dictLabel;
        }
      }
    }
  });
};

const selectedFinish = (selectedValue) => {
  console.info(selectedValue.bomVersion);
  if (
    selectedValue.bomVersion != undefined &&
    selectedValue.bomVersion != null
  ) {
    version.value.value = selectedValue.bomVersion;
    version.value.label = selectedValue.bomVersion;
  }
  search.value.bomVersion = version.value.value;
  dataNoPageList();
};
</script>
<style type="text/css">
.title-detail {
  width: 30%;
  height: 30px;
  line-height: 50px;
  margin: 5px 20px 5px 0;
  float: left;
}
.title-text{
  width: 100%;
  height: 30px;
  line-height: 50px;
  margin: 5px 20px 5px 0;
  float: left;
}
.detail {
  margin: 0 auto 30px;
  width: 100%;
  padding-left: 15px;
  overflow: hidden;
}
.avue-crud {
  float: left;
}
.detail-footer {
  float: right;
  margin-top: 15px;
}
.detail-title {
  width: 100%;
  padding-left: 5px;
  font-weight: 700;
}
</style>
