<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 生产bom树 -->
      <el-col :lg="6" :xs="24" style="" v-loading="treeLoading">
        <el-card shadow="hover" style="height: calc(100vh - 120px);overflow:auto;">
          <el-input v-model="materialName" placeholder="请输入物料名称" prefix-icon="Search" clearable />
          <el-tree
            ref="materialBomTreeRef"
            class="mt-2"
            node-key="treeKey"
            :data="materialBomOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div style="width: 100%">
                <el-tooltip :content="`${data.label}`" style="width: 100%">
                  <div class="custom-tree-node"
                       style="display: inline-block;vertical-align: top;max-width: 80%;overflow: hidden;">
                    <span
                      :style="{backgroundColor:getColor(data)?.[0],color:getColor(data)?.[1],verticalAlign: 'center'}">{{ node.label
                      }}</span>
                  </div>
                </el-tooltip>
                <el-button type="success" v-has-permi="['mes:materialBom:publish']" link @click="publishMaterialBom(data)" style=" vertical-align: top; "
                v-if="data.activeFlag && data.activeFlag!==MATERIAL_BOM_ACTIVE_FLAG.ACTIVE && data.children">
                  发布
                </el-button>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <el-col :lg="18" :xs="24" v-loading="loading">
        <el-divider content-position="left">父级物料</el-divider>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button v-has-permi="['mes:materialBom:add']" type="primary" plain icon="Plus"
                           @click="addNewMaterialBomVersion()" :loading="btnLoading"
                           :disabled="addNewMaterialBomVersionBtnDisabled">{{ addNewMaterialBomVersionBtnText }}
                </el-button>
              </el-col>
            </el-row>
          </template>

          <el-form ref="parentMaterialBomFormRef" label-width="120px" :model="parentForm" :rules="parentRules">
            <el-row :gutter="20">
              <el-form-item label='父物料ID' prop='parentId' v-if="false">
                <el-input v-model='parentForm.parentId' placeholder='' style="width:360px" />
              </el-form-item>
              <el-form-item label='父物料类型ID' prop='parentMaterialTypeId' v-if="false">
                <el-input v-model='parentForm.parentMaterialTypeId' placeholder='' style="width:360px" />
              </el-form-item>

              <el-form-item label='状态' prop='activeFlag' style="width:260px">
                <el-select v-model='parentForm.activeFlag' disabled>
                  <el-option v-for='dict in material_bom_active_flag' :key='dict.value' :label='dict.label'
                             :value='dict.value' />
                </el-select>
              </el-form-item>

              <el-form-item label="BOM版本" prop='materialBomVersion'>
                <el-input v-model='parentForm.materialBomVersion' placeholder='' style="width:260px" disabled />
              </el-form-item>

              <el-form-item label='父物料名称' prop='parentMaterialName'>
                <el-input v-model='parentForm.parentMaterialName' placeholder='请点击检索物料'
                          @click='handleMaterialSelect(parentForm,SELECT_MATERIAL_MODEL.PARENT_SELECT)'
                          style="width:260px" @change="getList" suffix-icon="Search" readonly
                          :disabled="parentMaterialDisabled" />
              </el-form-item>
              <el-form-item label="父物料类型名称" prop='parentMaterialTypeName'>
                <el-input v-model='parentForm.parentMaterialTypeName' placeholder='' style="width:260px" readonly />
              </el-form-item>


              <!--              <el-form-item label="BOM版本" prop='materialBomVersion' :model="parentForm">-->
              <!--                <el-select v-model="parentForm.materialBomVersion"-->
              <!--                           placeholder="请选择" style="width:200px">-->
              <!--                  <el-option-->
              <!--                    v-for="item in materialBomVersionOptions"-->
              <!--                    :key="item.materialBomVersion"-->
              <!--                    :label="item.materialBomVersion"-->
              <!--                    :value="item.materialBomVersion"-->
              <!--                  ></el-option>-->
              <!--                </el-select>-->
              <!--              </el-form-item>-->

              <el-form-item label='父物料数量' prop='parentStandardAmount'>
                <el-input-number v-model='parentForm.parentStandardAmount' :precision="2" :step="1"
                                 placeholder='请输入父物料数量'
                                 style="width:200px" :disabled="parentForm.activeFlag !== MATERIAL_BOM_ACTIVE_FLAG.DESIGN"/>
              </el-form-item>

              <el-form-item label='单位' prop='parentUnitId'>
                <el-select v-model="parentForm.parentUnitId" placeholder="请选择" style="width:200px" :disabled="parentForm.activeFlag !== MATERIAL_BOM_ACTIVE_FLAG.DESIGN">
                  <el-option
                    v-for="item in unitInfoOptions"
                    :key="item.unitId"
                    :label="item.unitName"
                    :value="item.unitId"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="BOM说明" prop='materialBomDesc'>
                <el-input v-model='parentForm.materialBomDesc' placeholder='' style="width:360px" type="textarea" :disabled="parentForm.activeFlag !== MATERIAL_BOM_ACTIVE_FLAG.DESIGN"/>
              </el-form-item>

            </el-row>
          </el-form>
        </el-card>


        <el-divider content-position="left">子级物料</el-divider>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button v-has-permi="['mes:materialBom:add']" type="primary" plain icon="Plus"
                           @click="handleAdd()" :loading="btnLoading" v-if="parentForm.activeFlag === MATERIAL_BOM_ACTIVE_FLAG.DESIGN">新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-has-permi="['mes:materialBom:remove']" type="danger" plain :disabled="multiple"
                           icon="Delete" @click="handleDelete()" :loading="btnLoading" v-if="parentForm.activeFlag === MATERIAL_BOM_ACTIVE_FLAG.DESIGN">
                  删除
                </el-button>
              </el-col>
            </el-row>
          </template>

          <el-table :data="materialBomList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column type="index" width="50" align="center" label="序号" />
            <el-table-column v-if="columns[0].visible" key="materialBomId" label="生产BOM_ID" align="center"
                             prop="materialBomId" />
            <el-table-column v-if="columns[1].visible" key="materialTypeCode" label="子物料类型编号" align="center"
                             prop="materialTypeCode" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[2].visible" key="materialTypeName" label="子物料类型名称" align="center"
                             prop="materialTypeName" :show-overflow-tooltip="true" w />
            <el-table-column v-if="columns[4].visible" key="materialId" label="子物料ID" align="center"
                             prop="materialId" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[5].visible" key="materialName" label="子物料名称" align="center"
                             prop="materialName" :show-overflow-tooltip="true">
              <template #default='scope'>
                <el-input v-model='scope.row.materialName' placeholder='请点击检索物料'
                          @click='handleMaterialSelect(scope.row,SELECT_MATERIAL_MODEL.CHILD_SELECT)'
                          suffix-icon="Search" readonly />
              </template>
            </el-table-column>
            <el-table-column v-if="columns[6].visible" key="standardAmount" label="子物料数量" align="center"
                             prop="standardAmount" :show-overflow-tooltip="true" width="220px">
              <template #default='scope'>
                <el-input-number v-model='scope.row.standardAmount' :precision="2" :step="1"
                                 placeholder='请输入数量' style="width:180px" />
              </template>
            </el-table-column>

            <el-table-column v-if="columns[7].visible" key="unitId" label="子物料单位" align="center"
                             prop="unitId" :show-overflow-tooltip="true">

              <template #default='scope'>
                <el-select v-model="scope.row.unitId" placeholder="请选择">
                  <el-option
                    v-for="item in unitInfoOptions"
                    :key="item.unitId"
                    :label="item.unitName"
                    :value="item.unitId"
                  ></el-option>
                </el-select>
              </template>

            </el-table-column>

          </el-table>


          <template #footer>
            <div class="dialog-footer">
              <el-button v-has-permi="['mes:materialBom:add']" type="success" plain icon="CircleCheck"
                         @click="submitBatchSaveMaterialBoms()" :loading="btnLoading" v-if="parentForm.activeFlag === MATERIAL_BOM_ACTIVE_FLAG.DESIGN">保存
              </el-button>
            </div>
          </template>

          <!--          <pagination-->
          <!--            v-show="total > 0"-->
          <!--            v-model:page="queryParams.pageNum"-->
          <!--            v-model:limit="queryParams.pageSize"-->
          <!--            :total="total"-->
          <!--            @pagination="getList"-->
          <!--          />-->
        </el-card>

      </el-col>
    </el-row>

    <!-- 添加或修改生产bom配置对话框 -->
    <el-dialog ref="formDialogRef" v-model="dialog.visible" :title="dialog.title" width="600px" append-to-body
               @close="closeDialog">
      <el-form ref="materialBomFormRef" :model="form" :rules="rules" label-width="98px">
        <el-form-item label="子物料类型" prop='materialTypeId'>
          <el-select v-model="form.materialTypeId" placeholder="请选择" style="width:360px">
            <el-option
              v-for="item in materialTypeOptions"
              :key="item.materialTypeId"
              :label="item.materialTypeName"
              :value="item.materialTypeId"
            ></el-option>
          </el-select>
        </el-form-item>

        <!--        <el-form-item label='BOM版本' prop='materialBomVersion'>-->
        <!--          <el-input v-model='form.materialBomVersion' placeholder='请输入BOM版本' style="width:360px"/>-->
        <!--        </el-form-item>-->

        <el-form-item label='子物料ID' prop='materialId' v-if="false">
          <el-input v-model='form.materialId' placeholder='' style="width:360px" />
        </el-form-item>

        <el-form-item label='子物料名称' prop='materialName'>
          <el-input v-model='form.materialName' placeholder='请点击检索物料'
                    @click='handleMaterialSelect(form,SELECT_MATERIAL_MODEL.DIALOG_CHILD_SELECT)'
                    style="width:360px" />
        </el-form-item>

        <el-form-item label='子物料数量' prop='standardAmount'>
          <el-input-number v-model='form.standardAmount' :precision="2" :step="1" placeholder='请输入子物料数量'
                           style="width:360px" />
        </el-form-item>

        <el-form-item label='子物料单位' prop='unitId'>
          <el-select v-model="form.unitId" placeholder="请选择单位" style="width:360px">
            <el-option
              v-for="item in unitInfoOptions"
              :key="item.unitId"
              :label="item.unitName"
              :value="item.unitId"
            ></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加物料信息对话框 -->
    <el-dialog title="选择物料信息" v-model='materialOpen' append-to-body>
      <MaterialSelect @selection="handleSelection" ref="materialSelectRef"
                      :materialTypeId="materialTypeId"
                      v-if="materialOpen"></MaterialSelect>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
        <el-button @click="materialOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup name="ProdMaterialBom" lang="ts">
import {
  materialBomTreeSelect,
  listMaterialBomJoinStructure,
  addBatchMaterialBom,
  getUnitInfoList, getMaterialBomVersionList, getParentMaterialBom, deleteMaterialBoms,
  selectNextMaterialBomVersion,publish
} from '@/api/mes/materialBom';

import { MaterialBomVO, MaterialBomForm, MaterialBomQuery } from '@/api/mes/materialBom/types';
import { BaseMaterialTypeVO } from '@/api/mes/baseMaterialType/types';
import MaterialSelect from '@/views/mes/baseMaterialInfo/addMaterial.vue';

import { to } from 'await-to-js';
import { nextTick } from 'vue';
import { MaterialBomVersionVO } from '@/api/mes/materialBomVersion/types';
import { BaseMeasurementUnitInfoVO } from '@/api/mes/baseMeasurementUnitInfo/types';
import { BaseStructureBomTreeVO } from '@/api/mes/baseStructureBom/types';

const materialTypeId = ref(0);//此值是传给选择物料信息弹框使用

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { material_bom_active_flag } = toRefs<any>(proxy?.useDict('material_bom_active_flag'));


const materialBomList = ref<MaterialBomVO[]>();
const saveMaterialBomList = ref<MaterialBomVO[]>([]);
const treeLoading = ref(false);
const loading = ref(false);
const materialSelectRef = ref();
const materialOpen = ref(false);
const editedRow = ref();
const submitLoading = ref(false);
const btnLoading = ref(false);
const showSearch = ref(true);
const selectedMaterialBoms = ref<MaterialBomVO[]>([]);
const toDeleteMaterialBoms = ref<MaterialBomVO[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const parentFormDisplay = ref(false);
const childTableTitle = ref('');
const materialName = ref('');
const materialBomOptions = ref<MaterialBomVO[]>([]);
const materialTypeOptions = ref<BaseMaterialTypeVO[]>([]);
const materialBomVersionOptions = ref<MaterialBomVersionVO[]>([]);
const unitInfoOptions = ref<BaseMeasurementUnitInfoVO[]>([]);

const focusKeyNode = ref<MaterialBomVO>;

const parentMaterialDisabled = ref(true);

const globalSelectMode = ref('');
const SELECT_MATERIAL_MODEL = ref({
  PARENT_SELECT: '1',//父级物料选择
  CHILD_SELECT: '2',//子级物料选择
  DIALOG_CHILD_SELECT: '3'//弹窗子级选择
});

const MATERIAL_BOM_ACTIVE_FLAG = ref({
  ACTIVE: '1',//启用
  HISTORY: '2',//历史
  DESIGN: '3'//设计中
});

const addNewMaterialBomVersionBtnText = ref('新增中');
const addNewMaterialBomVersionBtnDisabled = ref(true);

const publishBtnDisplay = ref(false);

const initialMaterialBomVersion = ref('01');

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `生产BOM_ID`, visible: false, children: [] },
  { key: 1, label: `子物料类型编号`, visible: true, children: [] },
  { key: 2, label: `子物料类型名称`, visible: true, children: [] },
  { key: 3, label: `BOM版本`, visible: false, children: [] },
  { key: 4, label: `子物料ID`, visible: false, children: [] },
  { key: 5, label: `子物料名称`, visible: true, children: [] },
  { key: 6, label: `子物料数量`, visible: true, children: [] },
  { key: 7, label: `子物料单位`, visible: true, children: [] }
]);

const materialBomTreeRef = ref<ElTreeInstance>();
const parentMaterialBomFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const materialBomFormRef = ref<ElFormInstance>();
const formDialogRef = ref<ElDialogInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initParentFormData: MaterialBomForm = {
  materialBomId: undefined,
  parentId: undefined,
  parentStandardAmount: 1,
  unitId: undefined,
  parentUnitId: undefined,
  materialId: undefined,
  materialName: undefined,
  materialTypeId: undefined,
  parentMaterialTypeId: undefined,
  materialBomDesc: undefined,
  materialBomVersion: undefined,
  ancestors: undefined,
  standardAmount: undefined,
  topFlag: undefined,
  checkType: '1',
  projectId: undefined,
  assembleTime: undefined,
  materialClassfication: undefined,
  attachId: undefined,
  activeFlag: undefined,
  remark: undefined,
  materialTypeName: undefined
};

const initFormData: MaterialBomForm = {
  materialBomId: undefined,
  parentId: undefined,
  parentStandardAmount: undefined,
  unitId: undefined,
  parentUnitId: undefined,
  materialId: undefined,
  materialName: undefined,
  materialTypeId: undefined,
  materialBomDesc: undefined,
  materialBomVersion: undefined,
  ancestors: undefined,
  standardAmount: undefined,
  topFlag: undefined,
  checkType: '1',
  projectId: undefined,
  assembleTime: undefined,
  materialClassfication: undefined,
  attachId: undefined,
  activeFlag: undefined,
  remark: undefined,
  materialTypeName: undefined
};

const data = reactive<PageData<MaterialBomForm, MaterialBomQuery>>({
  form: { ...initFormData },
  parentForm: { ...initParentFormData },
  queryParams: {
    materialBomId: undefined,
    parentId: undefined,
    materialTypeCode: undefined,
    materialTypeName: undefined,
    materialName: undefined,
    materialBomVersion: undefined,
    parentMaterialTypeId: undefined,
    params: {}
  },
  rules: {
    materialTypeId: [
      { required: true, message: '物料类型不能为空', trigger: 'blur' }
    ],
    materialBomVersion: [
      { required: true, message: 'BOM版本不能为空', trigger: 'blur' }
    ],
    materialName: [
      { required: true, message: '物料名称不能为空', trigger: 'blur' }
    ],
    standardAmount: [
      { required: true, message: '子物料数量不能为空', trigger: 'blur' }
    ]
  },

  parentRules: {
    parentMaterialName: [
      { required: true, message: '父物料名称不能为空', trigger: 'blur' }
    ],
    materialBomVersion: [
      { required: true, message: 'BOM版本不能为空', trigger: 'blur' }
    ],
    parentStandardAmount: [
      { required: true, message: '父物料数量不能为空', trigger: 'blur' }
    ],
    parentUnitId: [
      { required: true, message: '父物料单位不能为空', trigger: 'blur' }
    ]
  }

});


const parentQueryParams = ref({
  materialBomId: undefined,
  parentId: undefined,
  materialTypeCode: undefined,
  materialTypeName: undefined,
  materialName: undefined,
  materialBomVersion: undefined,
  params: {}
});

const { queryParams, form, rules, parentForm, parentRules } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label?.toLowerCase().includes(value.toLowerCase());
};
/** 根据名称筛选部门树 */
watchEffect(
  () => {
    materialBomTreeRef.value?.filter(materialName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询物料类型bom结构树下拉树结构 */
const getTreeSelect = async () => {
  treeLoading.value = true;
  loading.value = true;
  const res = await materialBomTreeSelect();
  materialBomOptions.value = [];
  const virtualTopNodeId = -1;
  const initialTree: BaseStructureBomTreeVO = {
    treeKey: virtualTopNodeId,
    id: virtualTopNodeId,//materialBomId
    parentId: -1,
    materialId: 0,
    label: '生产BOM',
    children: res.data
  };
  materialBomOptions.value.push(initialTree);
  console.log(materialBomOptions);

  // materialBomOptions.value = res.data;
  if (!focusKeyNode.value) {//如果之前没有focus
    focusKeyNode.value = { treeKey: virtualTopNodeId };
  } else {
    const clickNode = findObjectByTreeKey(materialBomOptions.value, focusKeyNode.value.treeKey);

    if (!clickNode) {
      focusKeyNode.value = undefined;
      focusKeyNode.value = { treeKey: virtualTopNodeId };
    }
    // if (!allTreeKeys || allTreeKeys.length <= 0) {
    //   focusKeyNode.value = {
    //     treeKey: virtualTopNodeId,
    //     id: virtualTopNodeId
    //   };
    // }

    // const focusKeyNodeIndex = JSON.stringify(materialBomOptions.value).indexOf(focusKeyNode.value.treeKey);
    // if (focusKeyNodeIndex < 0) {
    //   focusKeyNode.value = {treeKey: virtualTopNodeId};
    // }
    // const focusKeyNodeIndex = materialBomOptions.value.findIndex((optionItem) => focusKeyNode.value.treeKey === optionItem.treeKey);//有嵌套children的，有可能找不到
  }

  nextTick(function() {
    materialBomTreeRef.value?.setCurrentKey(focusKeyNode.value.treeKey, true);
  });

  loading.value = false;
  treeLoading.value = false;
  handleNodeClick(focusKeyNode.value);


  // const dd = {"id":"1","parentId":-1,"label":"dd"};
  // materialTypeOptions.value[0].children.push(dd);
};

/** 查询生产bom列表 */
const getNextMaterialBomVersion = async () => {
  //顶级节点，如果是重新修改父级物料则重新获取最新版本
  // loading.value = true;
  const res = await selectNextMaterialBomVersion(parentForm.value.parentId);
  parentForm.value.materialBomVersion = res.data;
  // materialBomList.value = res.data;
  // loading.value = false;
};

/** 查询生产bom列表 */
const getList = async () => {
  //如果是有节点的则加载数据，如果是顶级节点生产BOM则不加载数据
  loading.value = true;
  const res = await listMaterialBomJoinStructure(queryParams.value);
  materialBomList.value = res.data;
  loading.value = false;
};

const resetParentQueryParams = () => {
  parentQueryParams.value.parentId = undefined;//是当前节点的materialId
  parentQueryParams.value.materialBomVersion = undefined;
};

const resetQueryParams = () => {
  queryParams.value.parentId = undefined;//materialid
  queryParams.value.parentMaterialTypeId = undefined;
};

/** 节点单击事件 */
const handleNodeClick = (data: MaterialBomVO) => {
  materialBomList.value = [];
  parentMaterialDisabled.value = true;
  publishBtnDisplay.value = false;
  addNewMaterialBomVersionBtnDisabled.value = true;
  btnLoading.value = true;

  resetParentForm();
  resetQueryParams();
  resetParentQueryParams();
  focusKeyNode.value = data;
  if (data.materialId && data.materialId != 0) {
    parentQueryParams.value.parentId = data.materialId;//是当前节点的materialId
    parentQueryParams.value.materialBomVersion = data.materialBomVersion;
    getParentMaterialBomInfo();

  } else {
    parentForm.value.activeFlag = MATERIAL_BOM_ACTIVE_FLAG.value.DESIGN;
    handleBtnStatus();
    btnLoading.value = false;
    // if (materialBomVersionOptions.value.length > 0) {
    //   parentForm.value.materialBomVersion = materialBomVersionOptions.value[0].materialBomVersion;
    //   queryParams.value.materialBomVersion = materialBomVersionOptions.value[0].materialBomVersion;
    // }
  }
  parentMaterialDisabled.value = focusKeyNode.value.treeKey != -1;
};

const handleBtnStatus = () => {
  if (parentForm.value.materialBomVersion && parentForm.value.materialBomVersion !== '') {
    addNewMaterialBomVersionBtnDisabled.value = false;
    addNewMaterialBomVersionBtnText.value = '新增版本';
    publishBtnDisplay.value = parentForm.value.activeFlag !== MATERIAL_BOM_ACTIVE_FLAG.value.ACTIVE;
  } else {
    addNewMaterialBomVersionBtnDisabled.value = true;
    addNewMaterialBomVersionBtnText.value = '新增中';
    publishBtnDisplay.value = false;
  }

};

const clickDisplay = () => {
  if (queryParams.value.parentId === 0) {
    parentFormDisplay.value = false;
    childTableTitle.value = '顶级物料';
  } else {
    parentFormDisplay.value = true;
    childTableTitle.value = '子级物料';
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  // queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  // dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  // queryParams.value.pageNum = 1;
  // queryParams.value.parentId = undefined;
  // structureBomTreeRef.value?.setCurrentKey(undefined);
  handleQuery();
};

/** 删除按钮操作 */
const handleDelete = async (row?: MaterialBomVO) => {
  btnLoading.value = true;
  const toDeleteIndexes = [];
  selectedMaterialBoms.value.forEach(item => {
    // const index = materialBomList.value.findIndex((optionItem) => item.materialBomId === optionItem.materialBomId);
    const index = materialBomList.value.indexOf(item);
    toDeleteIndexes.push(parseInt(index + 1));
  });

  if (toDeleteIndexes.length > 0) {
    try {
      const [err] = await to(proxy?.$modal.confirm('是否确认删除序号为"' + toDeleteIndexes + '"的数据项？') as any);
      if (!err) {
        selectedMaterialBoms.value.forEach(item => {
          if (item.materialBomId && item.materialBomId !== '') {
            toDeleteMaterialBoms.value.push(item);
          } else {
            deleteReset(item);
          }
        });
        // alert(JSON.stringify(toDeleteMaterialBoms.value))
        if (toDeleteMaterialBoms.value.length > 0) {
          await deleteMaterialBoms(toDeleteMaterialBoms.value);
          await getTreeSelect();
        }

        proxy?.$modal.msgSuccess('删除成功');
      }
    } catch {
      btnLoading.value = false;
    }
  }
  btnLoading.value = false;
};

const deleteReset = (item) => {
  item.materialId = undefined;
  item.materialName = undefined;
  item.materialBomVersion = undefined;
  item.standardAmount = undefined;
  item.unitId = undefined;
};

/** 选择条数  */
const handleSelectionChange = (selection: MaterialBomVO[]) => {
  selectedMaterialBoms.value = selection.map((item) => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};


/** 重置操作表单 */
const reset = () => {
  form.value = { ...initFormData };
  materialBomFormRef.value?.resetFields();
};
/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  materialTypeOptions.value = [];
  if (!parentForm.value.parentId) {
    proxy?.$modal.msgWarning('请先选择父级物料');
    return;
  }
  materialTypeOptions.value = Array.from(
    new Map(materialBomList.value.map(item => [item['materialTypeId'], item]))
  ).map(([_, item]) => item);

  dialog.visible = true;
  dialog.title = '新增';
  form.value.parentId = parentForm.value.parentId;
};


/** 提交按钮 */
const submitForm = () => {
  materialBomFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true;
      const selectedMaterialType = materialTypeOptions.value
        .find(materialType => materialType.materialTypeId === form.value.materialTypeId);
      const childMaterialBom = {
        materialTypeId: form.value.materialTypeId,
        materialTypeCode: selectedMaterialType.materialTypeCode,
        materialTypeName: selectedMaterialType.materialTypeName,
        materialId: form.value.materialId,
        materialName: form.value.materialName,
        standardAmount: form.value.standardAmount,
        unitId: form.value.unitId
      };

      materialBomList.value.push(childMaterialBom);
      submitLoading.value = false;
      dialog.visible = false;
      // try {
      //   form.value.materialBomId ? await updateMaterialBom(form.value) : await addMaterialBom(form.value);
      //   proxy?.$modal.msgSuccess('操作成功');
      //   await getTreeSelect();
      //   dialog.visible = false;
      //   submitLoading.value = false;
      // } catch {
      //   submitLoading.value = false;
      // }

      // const child = {"id":"1","parentId":-1,"label":"dd"};
      // alert(materialTypeOptions.value[0])
      // materialTypeOptions.value[0].children.push(dd);
    }
  });
};

/**
 * 关闭用户弹窗
 */
const closeDialog = () => {
  dialog.visible = false;
  resetForm();
};

/**
 * 重置表单
 */
const resetForm = () => {
  materialBomFormRef.value?.resetFields();
  materialBomFormRef.value?.clearValidate();

  form.value.materialBomId = undefined;
  form.value.activeFlag = '1';
};
/**
 * 重置父级表单
 */
const resetParentForm = () => {
  parentMaterialBomFormRef.value?.resetFields();
  parentMaterialBomFormRef.value?.clearValidate();

};

onMounted(() => {
  getTreeSelect(); // 初始化物料类型结构bom数据
  initUnitInfoData();
  initMaterialBomVersionData();
});

const handleSelection = () => {
  // this.ids = selection.map(item => item.materialBomId)
  // this.single = selection.length !== 1
  // this.multiple = !selection.length
};

const handleMaterialSelect = (row, selectMode) => {
  editedRow.value = row;
  globalSelectMode.value = selectMode;
  if (selectMode === SELECT_MATERIAL_MODEL.value.DIALOG_CHILD_SELECT) {//弹窗新增子级时需要先选择子物料类型
    if (!row.materialTypeId) {
      proxy?.$modal.msgWarning('请先选择父级物料');
      return;
    }
    materialTypeId.value = row.materialTypeId;//弹窗子级选择物料需要传值materialTypeId
  } else if (selectMode === SELECT_MATERIAL_MODEL.value.CHILD_SELECT) {//子级选择物料需要传值materialTypeId
    materialTypeId.value = row.materialTypeId;
  } else {
    materialTypeId.value = undefined;
  }
  materialOpen.value = true;
};

/** 提交物料信息按钮 */
const submitMaterialForm = () => {
  let selectedRow = materialSelectRef.value.tableRef.store.states.currentRow.value;


  //此处只有是父级物料时赋值
  if (globalSelectMode.value === SELECT_MATERIAL_MODEL.value.PARENT_SELECT) {
    editedRow.value.materialBomVersion = undefined;
    editedRow.value.parentId = selectedRow.materialId;
    editedRow.value.parentMaterialName = selectedRow.materialName;
    editedRow.value.parentMaterialTypeId = selectedRow.materialTypeId;
    editedRow.value.parentMaterialTypeName = selectedRow.matrialTypeName;
    queryParams.value.parentId = selectedRow.materialId;
    queryParams.value.parentMaterialTypeId = selectedRow.materialTypeId;

    getNextMaterialBomVersion();
    // alert(JSON.stringify(queryParams.value))
    getList();
  } else {
    editedRow.value.materialId = selectedRow.materialId;
    editedRow.value.materialName = selectedRow.materialName;
  }
  materialOpen.value = false;
};


const submitBatchSaveMaterialBoms = async () => {
  parentMaterialBomFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        btnLoading.value = true;
        saveMaterialBomList.value = [];
        for (let i = 0; i < materialBomList.value.length; i++) {
          let item = materialBomList.value[i];
          if (item.materialId) {

            if (!item.standardAmount) {
              proxy?.$modal.msgWarning('序号为[' + (parseInt(i) + 1) + ']，请填写子物料数量');
              btnLoading.value = false;
              return;
            }
            if (!item.unitId) {
              proxy?.$modal.msgWarning('序号为[' + (parseInt(i) + 1) + ']，请选择单位');
              btnLoading.value = false;
              return;
            }

            item.parentId = parentForm.value.parentId;
            item.parentUnitId = parentForm.value.parentUnitId;
            item.parentStandardAmount = parentForm.value.parentStandardAmount;
            item.parentMaterialTypeId = parentForm.value.parentMaterialTypeId;

            item.materialBomDesc = parentForm.value.materialBomDesc;
            item.materialBomVersion = parentForm.value.materialBomVersion;
            item.activeFlag = parentForm.value.activeFlag;
            saveMaterialBomList.value.push(item);
          }
        }
        if (saveMaterialBomList.value.length <= 0) {
          proxy?.$modal.msgWarning('无可保存子级物料');
          btnLoading.value = false;
          return;
        }
        await addBatchMaterialBom(saveMaterialBomList.value);
        proxy?.$modal.msgSuccess('操作成功');

        focusKeyNode.value.treeKey = parentForm.value.parentId + '-' + parentForm.value.materialBomVersion;
        focusKeyNode.value.materialId = parentForm.value.parentId;
        focusKeyNode.value.materialTypeId = parentForm.value.parentMaterialTypeId;
        focusKeyNode.value.materialBomVersion = parentForm.value.materialBomVersion;
        focusKeyNode.value.parentUnitId = parentForm.value.parentUnitId;
        focusKeyNode.value.parentStandardAmount = parentForm.value.parentStandardAmount;

        resetParentQueryParams();
        resetQueryParams();
        resetParentForm();
        await getTreeSelect();
        btnLoading.value = false;
      } catch (e) {
        proxy?.$modal.msgWarning(e);
        btnLoading.value = false;
      }
    }
  });
};


/** 初始化单位数据 */
const initUnitInfoData = async () => {
  if (unitInfoOptions.value === undefined || unitInfoOptions.value.length <= 0) {
    const { data } = await getUnitInfoList();
    // alert(JSON.stringify(data))
    unitInfoOptions.value = data;
  }
};

/** 初始化物料bom版本数据 */
const initMaterialBomVersionData = async () => {
  // alert(JSON.stringify(getMaterialBomVersionList))
  if (materialBomVersionOptions.value === undefined || materialBomVersionOptions.value.length <= 0) {
    const { data } = await getMaterialBomVersionList();
    materialBomVersionOptions.value = data;

    if (materialBomVersionOptions.value.length > 0) {
      parentForm.value.materialBomVersion = materialBomVersionOptions.value[0].materialBomVersion;
      queryParams.value.materialBomVersion = materialBomVersionOptions.value[0].materialBomVersion;
    }

  }
};


/** 查询父级生产bom */
const getParentMaterialBomInfo = async () => {
  const res = await getParentMaterialBom(parentQueryParams.value);
  parentForm.value = res.data;
  handleBtnStatus();

  if (!parentForm.value.materialBomVersion || parentForm.value.materialBomVersion === '') {
    parentForm.value.materialBomVersion = initialMaterialBomVersion.value;
    parentForm.value.activeFlag = MATERIAL_BOM_ACTIVE_FLAG.value.DESIGN;
  }

  queryParams.value.parentId = parentForm.value.parentId;
  queryParams.value.parentMaterialTypeId = parentForm.value.parentMaterialTypeId;
  queryParams.value.materialBomVersion = parentForm.value.materialBomVersion;
  handleQuery();
  btnLoading.value = false;
};


const findObjectByTreeKey = (list, targetTreeKey) => {
  for (const item of list) {
    if (item.treeKey === targetTreeKey) return item;
    if (item.children) {
      const found = findObjectByTreeKey(item.children, targetTreeKey);
      if (found) return found;
    }
  }
  return null;
};

/** 基于当前父级物料和版本，新增物料bom版本 */
const addNewMaterialBomVersion = async () => {
  loading.value = true;
  parentForm.value.activeFlag = MATERIAL_BOM_ACTIVE_FLAG.value.DESIGN;
  await getNextMaterialBomVersion();
  materialBomList.value.forEach(childMaterialBom => {
    childMaterialBom.materialBomId = undefined;
  });
  loading.value = false;
  console.log(materialBomList);
};

/** 基于当前父级物料和版本,发布 */
const publishMaterialBom = async (data) => {
  try{
    loading.value = true;
    treeLoading.value = true;
    const toPublishMaterialBom = {
      parentId:data.materialId,
      materialBomVersion:data.materialBomVersion
    };

    await publish(toPublishMaterialBom);
    proxy?.$modal.msgSuccess('操作成功');
    await getTreeSelect();
    loading.value = false;
  }catch (e) {
    proxy?.$modal.msgWarning(e);
    loading.value = false;
    treeLoading.value = false;
  }

};

// const getClickNode = (obj) => {
//   // 如果当前对象有 id,并且与之前focus的id相同，则收集
//   // console.log(JSON.stringify(obj))
//   if (obj.treeKey !== undefined && obj.treeKey === focusKeyNode.value.treeKey) {
//     return obj;
//   }
//
//   // 如果有 children，递归遍历
//   if (obj.children && Array.isArray(obj.children)) {
//     obj.children.forEach(child => {
//       getClickNode(child); // 递归获取
//     });
//   }
//
// }
const getColor = (e) => {
  if (e.activeFlag === MATERIAL_BOM_ACTIVE_FLAG.value.ACTIVE) {
    return ['#00ff00', '#000'];
  }
  if (e.activeFlag === MATERIAL_BOM_ACTIVE_FLAG.value.HISTORY) {
    return ['#ff0000', '#fff'];
  }
  if (e.activeFlag === MATERIAL_BOM_ACTIVE_FLAG.value.DESIGN) {
    return ['#0000ff', '#fff'];
  }
};
</script>

<style lang="less" scoped>

:deep(.el-tree-node__content) {
  width: 100%;
}
</style>
