<template>
  <LjDialogNew ref="dialogRef" class="is-selector" width="88%" height="92vh" :closed="handleClosed" ifoverflow>
    <template #header>
      <div class="flx-1">
        <span class="text-h5-b">{{ typeName }}</span>
      </div>
    </template>

    <div class="custom-config-dialog">
      <div class="custom-config-body">
        <div class="custom-config-pane custom-config-pane--mid">
          <LjVxeTable
            ref="midTableRef"
            row-key="__rowKey"
            table-cls="h-full"
            :columns="columnsMid"
            :data="midList"
            dwname="web_configure_codelist"
            :tool-button="[]"
            :table-props="tableProps"
            :table-events="midTableEvents"
            :auto-load-layout="false"
            :request-auto="false"
          >
            <template #tableHeader>
              <el-space wrap>
                <template v-if="isTableEditing('mid')">
                  <el-button type="primary" :loading="tableSaving.mid" @click="saveMidTable">保存</el-button>
                  <el-button @click="appendMidRow">增行</el-button>
                  <el-button @click="removeMidEditRow">删行</el-button>
                  <el-button @click="insertMidRow">插行</el-button>
                  <el-button @click="cancelTableEdit">取消</el-button>
                </template>
                <template v-else>
                  <el-button type="primary" :disabled="hasActiveEdit" @click="enterTableEdit('mid')">编辑</el-button>
                  <el-button type="danger" :disabled="!currentMidRow || hasActiveEdit" @click="deleteMidRow">删除</el-button>
                </template>
              </el-space>
            </template>
          </LjVxeTable>
        </div>

        <div class="custom-config-pane custom-config-pane--right">
          <LjVxeTable
            ref="rightTableRef"
            row-key="__rowKey"
            table-cls="h-full"
            :columns="columnsRight"
            :data="rightList"
            dwname="web_configure_codemxlist"
            :tool-button="[]"
            :table-props="tableProps"
            :auto-load-layout="false"
            :table-events="rightTableEvents"
            :request-auto="false"
          >
            <template #tableHeader>
              <el-space wrap>
                <template v-if="isTableEditing('right')">
                  <el-button type="primary" :loading="tableSaving.right" @click="saveRightTable">保存</el-button>
                  <el-button @click="appendRightRow">增行</el-button>
                  <el-button @click="removeRightEditRow">删行</el-button>
                  <el-button @click="insertRightRow">插行</el-button>
                  <el-button @click="cancelTableEdit">取消</el-button>
                </template>
                <template v-else>
                  <el-button type="primary" :disabled="!currentMidRow || hasActiveEdit" @click="enterTableEdit('right')"
                    >编辑</el-button
                  >
                  <el-button type="danger" :disabled="!currentRightRow || hasActiveEdit" @click="deleteRightRow">删除</el-button>
                </template>
              </el-space>
            </template>
          </LjVxeTable>
        </div>

        <div class="custom-config-pane custom-config-pane--bottom">
          <LjVxeTable
            ref="bottomTableRef"
            row-key="__rowKey"
            table-cls="h-full"
            :columns="columnsBottom"
            :data="bottomList"
            dwname="web_configure_codemxbomlist"
            :tool-button="[]"
            :table-props="tableProps"
            :table-events="bottomTableEvents"
            :auto-load-layout="false"
            :request-auto="false"
          >
            <template #tableHeader>
              <el-space wrap>
                <template v-if="isTableEditing('bottom')">
                  <el-button type="primary" :loading="tableSaving.bottom" @click="saveBottomTable">保存</el-button>
                  <el-button @click="appendBottomRow">增行</el-button>
                  <el-button @click="removeBottomEditRow">删行</el-button>
                  <el-button @click="insertBottomRow">插行</el-button>
                  <el-button @click="cancelTableEdit">取消</el-button>
                </template>
                <template v-else>
                  <el-button type="primary" :disabled="!currentRightRow || hasActiveEdit" @click="enterTableEdit('bottom')"
                    >编辑</el-button
                  >
                  <el-button type="danger" :disabled="!currentBottomRow || hasActiveEdit" @click="deleteBottomRow"
                    >删除</el-button
                  >
                </template>
              </el-space>
            </template>
          </LjVxeTable>
        </div>
      </div>
    </div>
  </LjDialogNew>
  <ErpMtrlPriceDialog ref="ErpMtrlPriceDialogRef" v-bind="ErpMtrlPriceDialogProps" />
</template>

<script setup lang="tsx">
import { computed, nextTick, ref } from "vue";
import { cloneDeep } from "lodash-es";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import LjDialogNew from "@/components/LjDialog/index-new.vue";
import ErpMtrlPriceSelect from "@/views/system/selector/erpMtrlPrice/select.vue";
import ErpMtrlPriceDialog from "@/views/system/selector/erpMtrlPrice/index.vue";
import {
  DeleteConfigureBomList,
  DeleteConfigureCode,
  DeleteConfigureCodeMx,
  SaveConfigureBomList,
  SaveConfigureCode,
  SaveConfigureCodeMx,
  SaveConfigureType,
  getConfigureCodeList,
  getConfigureCodeMxBomList,
  getConfigureCodeMxList,
  getConfigureTypeList
} from "@/api/modules/basicinfo";

type PartType = 1 | 2 | 4;
type TableKey = "mid" | "right" | "bottom";

interface DialogPayload {
  partType: PartType;
  partKey: "headboard" | "nightstand" | "bedframe";
  partLabel: string;
  typeName: string;
}

interface MidRow {
  __rowKey: string;
  pzid: number;
  typeid: number;
  pzcode: string;
  name: string;
  inputtype: number;
  ifnum: number;
  ifcross: number;
  ifcheck: number;
  ifuse: number;
  maxnum: number | string;
  minnum: number | string;
  pricestr: string;
  priceratestr: string;
}

interface RightRow {
  __rowKey: string;
  pzid: number;
  printid: number;
  pzcodemx: string;
  namemx: string;
  ifuse: number;
  ifdft: number;
}

interface BottomRow {
  __rowKey: string;
  pzid: number;
  printid: number;
  pid: number;
  mtrlid: number;
  mtrlname: string;
  mtrlcode: string;
  mtrlmode: string;
  unit: string;
  default_length: number | string;
  default_width: number | string;
  default_qty: number | string;
  sonscale: number | string;
  sonscale_formula: string;
  sonloss: number | string;
}

const dialogRef = ref();
const midTableRef = ref();
const rightTableRef = ref();
const bottomTableRef = ref();
const ErpMtrlPriceDialogRef = ref();
const ErpMtrlPriceDialogProps = ref({});

const typeName = ref("");
const typeId = ref(0);
const midList = ref<MidRow[]>([]);
const rightList = ref<RightRow[]>([]);
const bottomList = ref<BottomRow[]>([]);
const currentMidKey = ref("");
const currentRightKey = ref("");
const currentBottomKey = ref("");
const editTable = ref<TableKey | "">("");
const editSnapshot = ref<any[]>([]);
const editSelectedKey = ref("");
const tableSaving = ref({ mid: false, right: false, bottom: false });

let seed = 1;
const nextKey = (prefix: string) => `${prefix}_${Date.now()}_${seed++}`;

const tableProps = {
  height: "auto",
  minHeight: "180px",
  mouseConfig: { selected: true }
};

const currentMidRow = computed(() => midList.value.find(item => item.__rowKey === currentMidKey.value) || null);
const currentRightRow = computed(() => rightList.value.find(item => item.__rowKey === currentRightKey.value) || null);
const currentBottomRow = computed(() => bottomList.value.find(item => item.__rowKey === currentBottomKey.value) || null);
const hasActiveEdit = computed(() => Boolean(editTable.value));

const getTableRefByKey = (table: TableKey) => {
  if (table === "mid") return midTableRef;
  if (table === "right") return rightTableRef;
  return bottomTableRef;
};

function getTableRows<T>(table: TableKey) {
  const tableData = getTableRefByKey(table).value?.element?.getTableData?.();
  return (tableData?.fullData || []) as T[];
}

const isTableEditing = (table: TableKey) => editTable.value === table;

const getCurrentKeyByTable = (table: TableKey) => {
  if (table === "mid") return currentMidKey.value;
  if (table === "right") return currentRightKey.value;
  return currentBottomKey.value;
};

const setCurrentKeyByTable = (table: TableKey, key: string) => {
  if (table === "mid") currentMidKey.value = key;
  if (table === "right") currentRightKey.value = key;
  if (table === "bottom") currentBottomKey.value = key;
};

const getRowKey = (row?: any) => row?.__rowKey || "";

const dataCallback = (data: any) => data.datatable || [];

const markMidRow = (row: any): MidRow => ({
  __rowKey: row.__rowKey || nextKey("mid"),
  pzid: Number(row.pzid || 0),
  typeid: Number(row.typeid || 0),
  pzcode: row.pzcode || "",
  name: row.name || "",
  inputtype: Number(row.inputtype || 0),
  ifnum: Number(row.ifnum || 0),
  ifcross: Number(row.ifcross || 0),
  ifcheck: Number(row.ifcheck || 0),
  ifuse: row.ifuse == null ? 1 : Number(row.ifuse),
  maxnum: row.maxnum ?? "",
  minnum: row.minnum ?? "",
  pricestr: row.pricestr || "",
  priceratestr: row.priceratestr || ""
});

const markRightRow = (row: any): RightRow => ({
  __rowKey: row.__rowKey || nextKey("right"),
  pzid: Number(row.pzid || 0),
  printid: Number(row.printid || 0),
  pzcodemx: row.pzcodemx || "",
  namemx: row.namemx || "",
  ifuse: row.ifuse == null ? 1 : Number(row.ifuse),
  ifdft: Number(row.ifdft || 0)
});

const markBottomRow = (row: any): BottomRow => ({
  __rowKey: row.__rowKey || nextKey("bottom"),
  pzid: Number(row.pzid || 0),
  printid: Number(row.printid || 0),
  pid: Number(row.pid || 0),
  mtrlid: Number(row.mtrlid || 0),
  mtrlname: row.mtrlname || "",
  mtrlcode: row.mtrlcode || "",
  mtrlmode: row.mtrlmode || "",
  unit: row.unit || "",
  default_length: row.default_length ?? row.cutting_length ?? "",
  default_width: row.default_width ?? row.cutting_width ?? "",
  default_qty: row.default_qty ?? row.cutting_qty ?? "",
  sonscale: row.sonscale ?? row.useqty ?? "",
  sonscale_formula: row.sonscale_formula ?? row.use_formula ?? "",
  sonloss: row.sonloss ?? row.loss_rate ?? ""
});

const createMidRow = (): MidRow =>
  markMidRow({
    pzid: 0,
    typeid: typeId.value,
    ifuse: 1
  });

const createRightRow = (): RightRow =>
  markRightRow({
    pzid: Number(currentMidRow.value?.pzid || 0),
    printid: 0,
    ifuse: 1,
    ifdft: 0
  });

const createBottomRow = (): BottomRow =>
  markBottomRow({
    pzid: Number(currentRightRow.value?.pzid || 0),
    printid: Number(currentRightRow.value?.printid || 0),
    pid: 0,
    mtrlid: 0,
    mtrlname: "",
    mtrlcode: "",
    mtrlmode: "",
    unit: "",
    default_length: "",
    default_width: "",
    default_qty: "",
    sonscale: "",
    sonscale_formula: "",
    sonloss: ""
  });

const setCurrentTableRow = (table: TableKey, row?: any) => {
  nextTick(() => {
    if (row) getTableRefByKey(table).value?.element?.setCurrentRow?.(row);
  });
};

const ensureType = async () => {
  if (typeId.value) return typeId.value;

  await SaveConfigureType({
    configure: {
      contfigtypeid: 0,
      contfigtypename: typeName.value
    }
  });

  const result = await getConfigureTypeList({ arg_search: typeName.value, pageSize: 500, pageNum: 1 });
  const typeRow = (result.datatable || []).find((item: any) => item.contfigtypename === typeName.value);
  typeId.value = Number(typeRow?.contfigtypeid || 0);
  if (!typeId.value) throw new Error("无法获取配置类型主键。");
  return typeId.value;
};

const loadBottomList = async (preferredPid = 0) => {
  if (!currentRightRow.value?.pzid || !currentRightRow.value?.printid) {
    bottomList.value = [];
    currentBottomKey.value = "";
    return;
  }

  const result = await getConfigureCodeMxBomList({
    pzid: currentRightRow.value.pzid,
    printid: currentRightRow.value.printid,
    pageSize: 500,
    pageNum: 1
  });
  const list = dataCallback(result).map((item: any) => markBottomRow(item));
  bottomList.value = list;
  const row = list.find((item: BottomRow) => item.pid > 0 && item.pid === preferredPid) || list[0];
  currentBottomKey.value = row?.__rowKey || "";
  setCurrentTableRow("bottom", row);
};

const loadRightList = async (preferredPrintid = 0) => {
  if (!currentMidRow.value?.pzid) {
    rightList.value = [];
    bottomList.value = [];
    currentRightKey.value = "";
    currentBottomKey.value = "";
    return;
  }

  const result = await getConfigureCodeMxList({
    pzid: currentMidRow.value.pzid,
    typeid: currentMidRow.value.typeid || typeId.value
  });
  const list = dataCallback(result).map((item: any) => markRightRow(item));
  rightList.value = list;
  const row = list.find((item: RightRow) => item.printid > 0 && item.printid === preferredPrintid) || list[0];
  currentRightKey.value = row?.__rowKey || "";
  setCurrentTableRow("right", row);
  await loadBottomList();
};

const loadMidList = async (preferredPzid = 0) => {
  if (!typeId.value) {
    midList.value = [];
    rightList.value = [];
    bottomList.value = [];
    currentMidKey.value = "";
    currentRightKey.value = "";
    currentBottomKey.value = "";
    return;
  }

  const result = await getConfigureCodeList({ typeid: typeId.value });
  const list = dataCallback(result).map((item: any) => markMidRow(item));
  midList.value = list;
  const row = list.find((item: MidRow) => item.pzid > 0 && item.pzid === preferredPzid) || list[0];
  currentMidKey.value = row?.__rowKey || "";
  setCurrentTableRow("mid", row);
  await loadRightList();
};

const loadAllData = async () => {
  const typeResult = await getConfigureTypeList({ arg_search: typeName.value });
  const typeRow = (typeResult.datatable || []).find((item: any) => item.contfigtypename === typeName.value);
  typeId.value = Number(typeRow?.contfigtypeid || 0);
  await loadMidList();
};

const enterTableEdit = (table: TableKey) => {
  if (hasActiveEdit.value) {
    ElMessage.warning("请先保存或取消当前编辑");
    return;
  }
  if (table === "right" && !currentMidRow.value) {
    ElMessage.warning("请先选择配置项");
    return;
  }
  if (table === "bottom" && !currentRightRow.value) {
    ElMessage.warning("请先选择配置项明细");
    return;
  }
  editTable.value = table;
  editSnapshot.value = cloneDeep(getTableRows(table));
  editSelectedKey.value = getCurrentKeyByTable(table);
};

const restoreCurrentRowAfterCancel = async (table: TableKey, rows: any[]) => {
  const row = rows.find(item => getRowKey(item) === editSelectedKey.value) || rows[0] || null;
  setCurrentKeyByTable(table, getRowKey(row));
  setCurrentTableRow(table, row);

  if (table === "mid") {
    await loadRightList();
    return;
  }
  if (table === "right") {
    await loadBottomList();
  }
};

const cancelTableEdit = async () => {
  if (!editTable.value) return;
  const table = editTable.value;
  const rows = cloneDeep(editSnapshot.value);
  if (table === "mid") midList.value = rows;
  if (table === "right") rightList.value = rows;
  if (table === "bottom") bottomList.value = rows;
  editTable.value = "";
  editSnapshot.value = [];
  await restoreCurrentRowAfterCancel(table, rows);
  editSelectedKey.value = "";
};

const insertRow = async (table: TableKey, append = true) => {
  if (!isTableEditing(table)) {
    ElMessage.warning("请先进入编辑状态");
    return;
  }
  if (table === "right" && !currentMidRow.value) {
    ElMessage.warning("请先选择配置项");
    return;
  }
  if (table === "bottom" && !currentRightRow.value) {
    ElMessage.warning("请先选择配置项明细");
    return;
  }

  if (table === "mid") {
    const row = createMidRow();
    const targetRow = append ? -1 : currentMidRow.value || -1;
    const result = await midTableRef.value?.element?.insertAt?.(row, targetRow);
    const newRow = result?.row || row;
    currentMidKey.value = newRow.__rowKey;
    setCurrentTableRow("mid", newRow);
    return;
  }

  if (table === "right") {
    const row = createRightRow();
    const targetRow = append ? -1 : currentRightRow.value || -1;
    const result = await rightTableRef.value?.element?.insertAt?.(row, targetRow);
    const newRow = result?.row || row;
    currentRightKey.value = newRow.__rowKey;
    setCurrentTableRow("right", newRow);
    return;
  }

  const row = createBottomRow();
  const targetRow = append ? -1 : currentBottomRow.value || -1;
  const result = await bottomTableRef.value?.element?.insertAt?.(row, targetRow);
  const newRow = result?.row || row;
  currentBottomKey.value = newRow.__rowKey;
  setCurrentTableRow("bottom", newRow);
};

const removeEditRow = async (table: TableKey) => {
  if (!isTableEditing(table)) {
    ElMessage.warning("请先进入编辑状态");
    return;
  }

  if (table === "mid") {
    if (!currentMidKey.value) return ElMessage.warning("请先选择一行数据");
    const currentRow = currentMidRow.value;
    if (!currentRow) return;
    const currentKey = currentMidKey.value;
    const prevRows = getTableRows<MidRow>("mid");
    const prevIndex = prevRows.findIndex(item => item.__rowKey === currentKey);
    await midTableRef.value?.element?.remove?.(currentRow);
    const rows = getTableRows<MidRow>("mid");
    const nextRow = rows[Math.max(prevIndex - 1, 0)] || rows[0] || null;
    currentMidKey.value = nextRow?.__rowKey || "";
    setCurrentTableRow("mid", nextRow);
    return;
  }

  if (table === "right") {
    if (!currentRightKey.value) return ElMessage.warning("请先选择一行数据");
    const currentRow = currentRightRow.value;
    if (!currentRow) return;
    const currentKey = currentRightKey.value;
    const prevRows = getTableRows<RightRow>("right");
    const prevIndex = prevRows.findIndex(item => item.__rowKey === currentKey);
    await rightTableRef.value?.element?.remove?.(currentRow);
    const rows = getTableRows<RightRow>("right");
    const nextRow = rows[Math.max(prevIndex - 1, 0)] || rows[0] || null;
    currentRightKey.value = nextRow?.__rowKey || "";
    setCurrentTableRow("right", nextRow);
    return;
  }

  if (!currentBottomKey.value) return ElMessage.warning("请先选择一行数据");
  const currentRow = currentBottomRow.value;
  if (!currentRow) return;
  const currentKey = currentBottomKey.value;
  const prevRows = getTableRows<BottomRow>("bottom");
  const prevIndex = prevRows.findIndex(item => item.__rowKey === currentKey);
  await bottomTableRef.value?.element?.remove?.(currentRow);
  const rows = getTableRows<BottomRow>("bottom");
  const nextRow = rows[Math.max(prevIndex - 1, 0)] || rows[0] || null;
  currentBottomKey.value = nextRow?.__rowKey || "";
  setCurrentTableRow("bottom", nextRow);
};

const appendMidRow = () => insertRow("mid", true);
const insertMidRow = () => insertRow("mid", false);
const removeMidEditRow = () => removeEditRow("mid");
const appendRightRow = () => insertRow("right", true);
const insertRightRow = () => insertRow("right", false);
const removeRightEditRow = () => removeEditRow("right");
const appendBottomRow = () => insertRow("bottom", true);
const insertBottomRow = () => insertRow("bottom", false);
const removeBottomEditRow = () => removeEditRow("bottom");

const setMtrl = (row: BottomRow, item: any) => {
  row.mtrlid = Number(item.mtrlid || 0);
  row.mtrlname = item.mtrlname || "";
  row.mtrlcode = item.mtrlcode || "";
  row.mtrlmode = item.mtrlmode || "";
  row.unit = item.unit || "";
};

const clearMtrl = (row: BottomRow) => {
  row.mtrlid = 0;
  row.mtrlname = "";
  row.mtrlcode = "";
  row.mtrlmode = "";
  row.unit = "";
};

const openMtrlDialog = (row: BottomRow, params: any) => {
  ErpMtrlPriceDialogProps.value = {
    onSubmit: (res: any) => {
      setMtrl(row, res.value[0]);
    }
  };
  ErpMtrlPriceDialogRef.value?.show?.(params);
};

const deleteMidRow = async () => {
  if (!currentMidRow.value) return ElMessage.warning("请先选择一行数据");
  await ElMessageBox.confirm("确认删除当前配置项吗？", "询问", { type: "warning" });
  if (currentMidRow.value.pzid > 0) {
    await DeleteConfigureCode({ list: [{ pzid: currentMidRow.value.pzid, typeid: currentMidRow.value.typeid }] });
  }
  await loadMidList();
};

const deleteRightRow = async () => {
  if (!currentRightRow.value) return ElMessage.warning("请先选择一行数据");
  await ElMessageBox.confirm("确认删除当前配置项明细吗？", "询问", { type: "warning" });
  if (currentRightRow.value.printid > 0) {
    await DeleteConfigureCodeMx({ list: [{ pzid: currentRightRow.value.pzid, printid: currentRightRow.value.printid }] });
  }
  await loadRightList();
};

const deleteBottomRow = async () => {
  if (!currentBottomRow.value) return ElMessage.warning("请先选择一行数据");
  await ElMessageBox.confirm("确认删除当前用料明细吗？", "询问", { type: "warning" });
  if (currentBottomRow.value.pid > 0) {
    await DeleteConfigureBomList({
      list: [{ pzid: currentBottomRow.value.pzid, printid: currentBottomRow.value.printid, pid: currentBottomRow.value.pid }]
    });
  }
  await loadBottomList();
};

const saveMidTable = async () => {
  if (!isTableEditing("mid")) return;
  try {
    tableSaving.value.mid = true;
    const savedTypeId = await ensureType();
    const rows = getTableRows<MidRow>("mid");
    for (const row of rows) {
      await SaveConfigureCode({
        configure: {
          pzid: row.pzid,
          typeid: savedTypeId,
          pzcode: row.pzcode,
          name: row.name,
          inputtype: row.inputtype,
          ifnum: row.ifnum,
          ifcross: row.ifcross,
          ifcheck: row.ifcheck,
          ifuse: row.ifuse,
          maxnum: row.maxnum,
          minnum: row.minnum,
          pricestr: row.pricestr,
          priceratestr: row.priceratestr
        }
      });
    }
    const preferredPzid = currentMidRow.value?.pzid || 0;
    editTable.value = "";
    editSnapshot.value = [];
    editSelectedKey.value = "";
    await loadMidList(preferredPzid);
    ElNotification({ title: "保存成功", type: "success" });
  } catch (error: any) {
    ElMessage.error(error?.message || "保存失败");
  } finally {
    tableSaving.value.mid = false;
  }
};

const saveRightTable = async () => {
  if (!isTableEditing("right")) return;
  if (!currentMidRow.value?.pzid) {
    ElMessage.warning("请先保存配置项");
    return;
  }
  try {
    tableSaving.value.right = true;
    const rows = getTableRows<RightRow>("right");
    for (const row of rows) {
      await SaveConfigureCodeMx({
        configure: {
          pzid: currentMidRow.value.pzid,
          printid: row.printid,
          pzcodemx: row.pzcodemx,
          namemx: row.namemx,
          ifuse: row.ifuse,
          ifdft: row.ifdft
        }
      });
    }
    const preferredPrintid = currentRightRow.value?.printid || 0;
    editTable.value = "";
    editSnapshot.value = [];
    editSelectedKey.value = "";
    await loadRightList(preferredPrintid);
    ElNotification({ title: "保存成功", type: "success" });
  } catch (error: any) {
    ElMessage.error(error?.message || "保存失败");
  } finally {
    tableSaving.value.right = false;
  }
};

const saveBottomTable = async () => {
  if (!isTableEditing("bottom")) return;
  if (!currentRightRow.value?.pzid || !currentRightRow.value?.printid) {
    ElMessage.warning("请先保存配置项明细");
    return;
  }
  try {
    tableSaving.value.bottom = true;
    const rows = getTableRows<BottomRow>("bottom");
    await SaveConfigureBomList({
      bomList: rows.map(row => ({
        pid: row.pid,
        pzid: currentRightRow.value!.pzid,
        printid: currentRightRow.value!.printid,
        mtrlid: row.mtrlid,
        mtrlname: row.mtrlname,
        mtrlcode: row.mtrlcode,
        mtrlmode: row.mtrlmode,
        unit: row.unit,
        default_length: row.default_length ?? 0,
        default_width: row.default_width ?? 0,
        default_qty: row.default_qty ?? 0,
        sonscale: row.sonscale ?? 0,
        sonscale_formula: row.sonscale_formula || "",
        sonloss: row.sonloss ?? 0,
        sondecloss: 0,
        sonloss_formula: "",
        sondecloss_formula: "",
        mng_cost_rate: 0,
        profit_rate: 0
      }))
    });
    const preferredPid = currentBottomRow.value?.pid || 0;
    editTable.value = "";
    editSnapshot.value = [];
    editSelectedKey.value = "";
    await loadBottomList(preferredPid);
    ElNotification({ title: "保存成功", type: "success" });
  } catch (error: any) {
    ElMessage.error(error?.message || "保存失败");
  } finally {
    tableSaving.value.bottom = false;
  }
};

const renderInput = (table: TableKey, getter: (scope: any) => any, editor: (scope: any) => any) => (scope: any) =>
  isTableEditing(table) ? editor(scope) : getter(scope);

const renderTextInput = (table: TableKey, field: string) =>
  renderInput(
    table,
    (scope: any) => scope.row[field] ?? "",
    (scope: any) => <el-input v-model={scope.row[field]} />
  );

const renderCheckbox = (table: TableKey, field: string) =>
  renderInput(
    table,
    (scope: any) => <el-checkbox modelValue={Number(scope.row[field]) === 1} disabled />,
    (scope: any) => (
      <el-checkbox
        modelValue={Number(scope.row[field]) === 1}
        onChange={(val: boolean) => {
          scope.row[field] = val ? 1 : 0;
        }}
      />
    )
  );

const setDefaultRight = (row: RightRow, value: boolean) => {
  if (!value) {
    row.ifdft = 0;
    return;
  }
  rightList.value = rightList.value.map(item => ({
    ...item,
    ifdft: item.__rowKey === row.__rowKey ? 1 : 0
  }));
};

const columnsMid = [
  { field: "pzcode", title: "配置项编号", width: 120, render: renderTextInput("mid", "pzcode") },
  { field: "name", title: "配置项名称", minWidth: 140, render: renderTextInput("mid", "name") },
  {
    field: "inputtype",
    title: "录入类型",
    width: 100,
    render: renderInput(
      "mid",
      (scope: any) => (Number(scope.row.inputtype) === 1 ? "数值" : "文本"),
      (scope: any) => (
        <el-select v-model={scope.row.inputtype}>
          <el-option label="文本" value={0} />
          <el-option label="数值" value={1} />
        </el-select>
      )
    )
  },
  { field: "ifnum", title: "数量", width: 80, render: renderCheckbox("mid", "ifnum") },
  { field: "ifcross", title: "混搭", width: 80, render: renderCheckbox("mid", "ifcross") },
  { field: "ifcheck", title: "必填", width: 80, render: renderCheckbox("mid", "ifcheck") },
  { field: "ifuse", title: "有效", width: 80, render: renderCheckbox("mid", "ifuse") },
  { field: "maxnum", title: "最大数", width: 100, render: renderTextInput("mid", "maxnum") },
  { field: "minnum", title: "最小数", width: 100, render: renderTextInput("mid", "minnum") }
];

const columnsRight = [
  { field: "pzcodemx", title: "明细编号", width: 120, render: renderTextInput("right", "pzcodemx") },
  { field: "namemx", title: "配置项明细名", minWidth: 160, render: renderTextInput("right", "namemx") },
  {
    field: "ifdft",
    title: "标准项",
    width: 90,
    render: renderInput(
      "right",
      (scope: any) => <el-checkbox modelValue={Number(scope.row.ifdft) === 1} disabled />,
      (scope: any) => (
        <el-checkbox modelValue={Number(scope.row.ifdft) === 1} onChange={(val: boolean) => setDefaultRight(scope.row, val)} />
      )
    )
  },
  { field: "ifuse", title: "有效", width: 80, render: renderCheckbox("right", "ifuse") }
];

const columnsBottom = [
  {
    field: "mtrlname",
    title: "物料名称",
    minWidth: 220,
    render: renderInput(
      "bottom",
      (scope: any) => `${scope.row.mtrlname || ""}${scope.row.mtrlmode ? ` ${scope.row.mtrlmode}` : ""}`,
      (scope: any) => {
        const row = scope.row as BottomRow;
        const params = { keyword: row.mtrlcode || row.mtrlname || "" };
        return (
          <ErpMtrlPriceSelect
            value={row.mtrlid}
            {...params}
            clearable
            placeholder={row.mtrlname}
            onOpenModal={() => openMtrlDialog(row, params)}
            onSelect={(val: any) => setMtrl(row, val)}
            onClear={() => clearMtrl(row)}
          >
            {{
              label: () => `${row.mtrlname} ${row.mtrlmode || ""}`
            }}
          </ErpMtrlPriceSelect>
        );
      }
    )
  },
  { field: "unit", title: "单位", width: 70 },
  { field: "default_length", title: "默认长", width: 100, render: renderTextInput("bottom", "default_length") },
  { field: "default_width", title: "默认宽", width: 100, render: renderTextInput("bottom", "default_width") },
  { field: "default_qty", title: "默认数量", width: 100, render: renderTextInput("bottom", "default_qty") },
  { field: "sonscale", title: "用料量", width: 100, render: renderTextInput("bottom", "sonscale") },
  { field: "sonscale_formula", title: "用料量公式", minWidth: 180, render: renderTextInput("bottom", "sonscale_formula") },
  { field: "sonloss", title: "损耗率", width: 100, render: renderTextInput("bottom", "sonloss") }
];

const midTableEvents = {
  "cell-click": async ({ row }: any) => {
    if (editTable.value && editTable.value !== "mid") {
      ElMessage.warning("请先保存或取消当前编辑");
      return;
    }
    currentMidKey.value = row.__rowKey;
    setCurrentTableRow("mid", row);
    if (isTableEditing("mid")) return;
    await loadRightList();
  }
};

const rightTableEvents = {
  "cell-click": async ({ row }: any) => {
    if (editTable.value && editTable.value !== "right") {
      ElMessage.warning("请先保存或取消当前编辑");
      return;
    }
    currentRightKey.value = row.__rowKey;
    setCurrentTableRow("right", row);
    if (isTableEditing("right")) return;
    await loadBottomList();
  }
};

const bottomTableEvents = {
  "cell-click": ({ row }: any) => {
    if (editTable.value && editTable.value !== "bottom") {
      ElMessage.warning("请先保存或取消当前编辑");
      return;
    }
    currentBottomKey.value = row.__rowKey;
    setCurrentTableRow("bottom", row);
  }
};

const closeDialog = () => {
  if (hasActiveEdit.value) {
    ElMessage.warning("请先保存或取消当前编辑");
    return;
  }
  dialogRef.value?.hide?.();
};

const handleClosed = () => {
  editTable.value = "";
  editSnapshot.value = [];
  editSelectedKey.value = "";
  tableSaving.value = { mid: false, right: false, bottom: false };
};

const open = async (payload: DialogPayload) => {
  typeName.value = payload.typeName;
  typeId.value = 0;
  midList.value = [];
  rightList.value = [];
  bottomList.value = [];
  currentMidKey.value = "";
  currentRightKey.value = "";
  currentBottomKey.value = "";
  editTable.value = "";
  editSnapshot.value = [];
  editSelectedKey.value = "";
  dialogRef.value?.show?.();
  await loadAllData();
};

defineExpose({ open });
</script>

<style scoped lang="scss">
.custom-config-dialog {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0px 8px;
  box-sizing: border-box;
}

.dialog-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.dialog-toolbar__meta {
  display: flex;
  align-items: center;
  gap: 6px;
}

.dialog-toolbar__type {
  font-weight: 600;
}

.custom-config-body {
  flex: 1;
  min-height: 0;
  display: grid;
  grid-template-columns: 28% 28% 1fr;
  gap: 12px;
  overflow: hidden;
}

.custom-config-pane {
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}
</style>
<style lang="scss">
.el-dialog {
  padding: 0;
}
.el-dialog__footer {
  padding: 8px;
}
</style>
