<template>
  <div class="recipe-detail-page p-2">
    <div class="page-header">
      <span class="page-title">配方明细信息</span>
      <div class="header-actions">
        <el-button type="primary" :icon="isEdit ? 'Select' : 'Edit'" @click="toggleEdit">
          {{ isEdit ? '取消编辑' : '编辑' }}
        </el-button>
        <el-button type="success" icon="Select" :loading="saveLoading" :disabled="!isEdit" @click="handleSave">
          保存
        </el-button>
      </div>
    </div>

    <el-tabs v-model="activeTab" type="border-card">
      <el-tab-pane label="基本信息" name="basic">
        <el-card shadow="never" class="mb-4">
          <template #header>配方基本信息</template>
          <el-form ref="basicFormRef" :model="recipeInfo" :disabled="!isEdit" label-width="140px" class="form-grid">
            <el-row :gutter="16">
              <el-col :span="8">
                <el-form-item label="配方代码" prop="recipeCode">
                  <el-input v-model="recipeInfo.recipeCode" placeholder="配方代码" />
                </el-form-item>
                <el-form-item label="超时时间(秒)" prop="overtimeTime">
                  <el-input-number v-model="recipeInfo.overtimeTime" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
                <el-form-item label="超温最短时间(秒)" prop="overtempMintime">
                  <el-input-number v-model="recipeInfo.overtempMintime" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
                <el-form-item label="最小间隔时间(秒)" prop="miniTime">
                  <el-input-number v-model="recipeInfo.miniTime" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
                <el-form-item label="每架车数(车)" prop="shelfNum">
                  <el-input-number v-model="recipeInfo.shelfNum" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物料名称" prop="recipeCode">
                  <el-input v-model="recipeInfo.recipeCode" placeholder="物料名称" />
                </el-form-item>
                <el-form-item label="超温温度(℃)" prop="overtempTemp">
                  <el-input-number v-model="recipeInfo.overtempTemp" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
                <el-form-item label="最低进胶温度(℃)" prop="minInpolytemp">
                  <el-input-number v-model="recipeInfo.minInpolytemp" controls-position="right" style="width: 100%" />
                </el-form-item>
                <el-form-item label="配方总重(千克)" prop="totalWeight">
                  <el-input-number v-model="recipeInfo.totalWeight" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="配方状态" prop="recipeState">
                  <el-select v-model="recipeInfo.recipeState" placeholder="配方状态" style="width: 100%">
                    <el-option v-for="d in recipe_state" :key="d.value" :label="d.label" :value="d.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="机台名称" prop="machineId">
                  <el-select v-model="recipeInfo.machineId" placeholder="请选择机台" style="width: 100%">
                    <el-option v-for="m in machineOptions" :key="m.machineId" :label="m.machineName || m.machineCode" :value="m.machineId" />
                  </el-select>
                </el-form-item>
                <el-form-item label="超能能量(kw/h)" prop="overTemp">
                  <el-input-number v-model="recipeInfo.overTemp" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
                <el-form-item label="最高进胶温度(℃)" prop="maxInpolytemp">
                  <el-input-number v-model="recipeInfo.maxInpolytemp" :min="0" controls-position="right" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="称量信息" name="weight">
        <div class="tab-toolbar mb-3">
          <el-button type="primary" size="small" @click="calcWeight">计算重量</el-button>
          <el-button size="small" @click="refreshWeight">刷新称量信息</el-button>
        </div>
        <el-card shadow="never" class="mb-3">
          <template #header>称量明细</template>
          <el-table :data="weightList" border>
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column label="物料名称/炭黑名称" prop="childCode" min-width="120">
              <template #default="{ row }">
                <el-input v-if="isEdit" v-model="row.childCode" size="small" placeholder="物料编码" />
                <span v-else>{{ row.childCode || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="物料编码" prop="fatherCode" min-width="100">
              <template #default="{ row }">
                <el-input v-if="isEdit" v-model="row.fatherCode" size="small" />
                <span v-else>{{ row.fatherCode || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="称量动作" prop="actCode" width="100">
              <template #default="{ row }">
                <el-input v-if="isEdit" v-model="row.actCode" size="small" />
                <span v-else>{{ row.actCode || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="设定重量(千克)" prop="setWeight" width="140">
              <template #default="{ row }">
                <el-input-number v-if="isEdit" v-model="row.setWeight" :min="0" :precision="3" size="small" controls-position="right" style="width: 100%" />
                <span v-else>{{ row.setWeight ?? '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="允许误差(千克)" prop="errorAllow" width="140">
              <template #default="{ row }">
                <el-input-number v-if="isEdit" v-model="row.errorAllow" :min="0" :precision="3" size="small" controls-position="right" style="width: 100%" />
                <span v-else>{{ row.errorAllow ?? '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="isEdit" label="操作" width="180" fixed="right" align="center">
              <template #default="{ $index }">
                <el-button link type="primary" size="small" @click="addWeightRow($index)">添加</el-button>
                <el-button link type="primary" size="small" @click="insertWeightRow($index)">插入</el-button>
                <el-button link type="danger" size="small" @click="removeWeightRow($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="mt-2 text-secondary">
            总计 {{ weightTotalWeight }} 千克，允许误差 {{ weightTotalError }} 千克，共 {{ weightList.length }} 条
          </div>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="混炼信息" name="mixing">
        <div class="tab-toolbar mb-3">
          <el-button type="primary" size="small" @click="refreshMixing">调用混炼信息</el-button>
          <el-button size="small" @click="refreshMixing">刷新混炼信息</el-button>
        </div>
        <el-card shadow="never">
          <el-table :data="mixingList" border>
            <el-table-column type="index" label="步骤" width="70" align="center" />
            <el-table-column label="动作" prop="actCode" min-width="120">
              <template #default="{ row }">
                <el-input v-if="isEdit" v-model="row.actCode" size="small" />
                <span v-else>{{ row.actCode || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="条件" prop="condCode" width="100">
              <template #default="{ row }">
                <el-input v-if="isEdit" v-model="row.condCode" size="small" />
                <span v-else>{{ row.condCode || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="时间(s)" prop="setTime" width="90">
              <template #default="{ row }">
                <el-input-number v-if="isEdit" v-model="row.setTime" :min="0" size="small" controls-position="right" style="width: 100%" />
                <span v-else>{{ row.setTime ?? '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="温度(°C)" prop="setTemp" width="90">
              <template #default="{ row }">
                <el-input-number v-if="isEdit" v-model="row.setTemp" :min="0" size="small" controls-position="right" style="width: 100%" />
                <span v-else>{{ row.setTemp ?? '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="能量(kw/h)" prop="setEnergy" width="100">
              <template #default="{ row }">
                <el-input-number v-if="isEdit" v-model="row.setEnergy" :min="0" size="small" controls-position="right" style="width: 100%" />
                <span v-else>{{ row.setEnergy ?? '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="功率(kw)" prop="setPower" width="90">
              <template #default="{ row }">
                <el-input-number v-if="isEdit" v-model="row.setPower" :min="0" size="small" controls-position="right" style="width: 100%" />
                <span v-else>{{ row.setPower ?? '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="压力" prop="setPres" width="80">
              <template #default="{ row }">
                <el-input-number v-if="isEdit" v-model="row.setPres" :min="0" size="small" controls-position="right" style="width: 100%" />
                <span v-else>{{ row.setPres ?? '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="转速(rpm)" prop="setRota" width="100">
              <template #default="{ row }">
                <el-input-number v-if="isEdit" v-model="row.setRota" :min="0" size="small" controls-position="right" style="width: 100%" />
                <span v-else>{{ row.setRota ?? '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="isEdit" label="操作" width="120" fixed="right" align="center">
              <template #default="{ $index }">
                <el-button link type="primary" size="small" @click="insertMixingRow($index)">插入</el-button>
                <el-button link type="danger" size="small" @click="removeMixingRow($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="mt-2 text-secondary">共 {{ mixingList.length }} 条</div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="RecipeInfoDetail" lang="ts">
import { getRecipeInfo, saveRecipeDetail } from '@/api/mes/recipeInfo';
import { listRecipeWeight } from '@/api/mes/recipeWeight';
import { listRecipeMixing } from '@/api/mes/recipeMixing';
import { getProdBaseMachineInfoList } from '@/api/mes/prodBaseMachineInfo';
import type { RecipeInfoForm } from '@/api/mes/recipeInfo/types';
import type { RecipeWeightForm } from '@/api/mes/recipeWeight/types';
import type { RecipeMixingForm } from '@/api/mes/recipeMixing/types';
import type { ProdBaseMachineInfoVO } from '@/api/mes/prodBaseMachineInfo/types';

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { recipe_state } = toRefs<any>(proxy?.useDict('recipe_state'));

const recipeId = computed(() => route.query.recipeId as string || '');
const activeTab = ref('basic');
const isEdit = ref(false);
const saveLoading = ref(false);
const basicFormRef = ref<ElFormInstance>();

const recipeInfo = ref<RecipeInfoForm>({});
const weightList = ref<RecipeWeightForm[]>([]);
const mixingList = ref<RecipeMixingForm[]>([]);
const machineOptions = ref<ProdBaseMachineInfoVO[]>([]);

const weightTotalWeight = computed(() =>
  weightList.value.reduce((s, r) => s + (Number(r.setWeight) || 0), 0).toFixed(3)
);
const weightTotalError = computed(() =>
  weightList.value.reduce((s, r) => s + (Number(r.errorAllow) || 0), 0).toFixed(3)
);

function toggleEdit() {
  isEdit.value = !isEdit.value;
}

async function loadData() {
  if (!recipeId.value) {
    proxy?.$modal.msgWarning('缺少配方ID');
    return;
  }
  try {
    const [infoRes, weightRes, mixingRes] = await Promise.all([
      getRecipeInfo(recipeId.value),
      listRecipeWeight({ recipeId: recipeId.value, pageNum: 1, pageSize: 9999 }),
      listRecipeMixing({ recipeId: recipeId.value, pageNum: 1, pageSize: 9999 })
    ]);
    const infoData = (infoRes as any).data ?? infoRes;
    recipeInfo.value = { ...infoData };
    weightList.value = (weightRes.rows || []).map((r: any) => ({ ...r }));
    const mixRows = mixingRes.rows || [];
    mixingList.value = mixRows.map((r: any) => ({ ...r }));
  } catch (e) {
    proxy?.$modal.msgError('加载失败');
  }
}

async function loadMachines() {
  try {
    const res = await getProdBaseMachineInfoList({});
    machineOptions.value = res.data || [];
  } catch {
    machineOptions.value = [];
  }
}

function addWeightRow(index: number) {
  const base = weightList.value[index] || {};
  weightList.value.splice(index + 1, 0, {
    recipeId: recipeId.value,
    machineId: recipeInfo.value.machineId,
    edtCode: recipeInfo.value.edtCode,
    weightSeq: (weightList.value.length + 1) as any,
    weightType: base.weightType || '',
    scaleCode: base.scaleCode,
    actCode: base.actCode || '称量',
    setWeight: undefined,
    errorAllow: undefined,
    fatherCode: '',
    unitId: undefined,
    childCode: '',
    ifUseBat: '',
    maxRate: ''
  } as RecipeWeightForm);
}

function insertWeightRow(index: number) {
  const base = weightList.value[index] || {};
  weightList.value.splice(index, 0, {
    recipeId: recipeId.value,
    machineId: recipeInfo.value.machineId,
    edtCode: recipeInfo.value.edtCode,
    weightSeq: (index + 1) as any,
    weightType: base.weightType || '',
    scaleCode: base.scaleCode,
    actCode: base.actCode || '称量',
    setWeight: undefined,
    errorAllow: undefined,
    fatherCode: '',
    unitId: undefined,
    childCode: '',
    ifUseBat: '',
    maxRate: ''
  } as RecipeWeightForm);
}

function removeWeightRow(index: number) {
  weightList.value.splice(index, 1);
}

function insertMixingRow(index: number) {
  const base = mixingList.value[index] || {};
  mixingList.value.splice(index, 0, {
    recipeId: recipeId.value,
    machineId: recipeInfo.value.machineId,
    edtCode: recipeInfo.value.edtCode,
    mixId: index + 1,
    condCode: base.condCode || '',
    actCode: base.actCode || '',
    setTime: undefined,
    setTemp: undefined,
    setEnergy: undefined,
    setPower: undefined,
    setPres: undefined,
    setRota: undefined,
    fatherCode: '',
    childCode: '',
    termCode: ''
  } as RecipeMixingForm);
}

function removeMixingRow(index: number) {
  mixingList.value.splice(index, 1);
}

function calcWeight() {
  proxy?.$modal.msg('计算重量功能可按业务规则扩展');
}

async function refreshWeight() {
  await loadData();
  activeTab.value = 'weight';
}

async function refreshMixing() {
  await loadData();
  activeTab.value = 'mixing';
}

async function handleSave() {
  if (!recipeId.value) return;
  saveLoading.value = true;
  try {
    const payload = {
      recipeInfo: { ...recipeInfo.value, recipeId: recipeId.value },
      weightList: weightList.value.map((w, i) => ({
        ...w,
        recipeId: recipeId.value,
        machineId: recipeInfo.value.machineId ?? w.machineId,
        edtCode: recipeInfo.value.edtCode ?? w.edtCode,
        weightSeq: (w.weightSeq ?? i + 1) as number
      })),
      mixingList: mixingList.value.map((m, i) => ({
        ...m,
        recipeId: recipeId.value,
        machineId: recipeInfo.value.machineId ?? m.machineId,
        edtCode: recipeInfo.value.edtCode ?? m.edtCode,
        mixId: (m.mixId ?? i + 1) as number
      }))
    };
    await saveRecipeDetail(payload);
    proxy?.$modal.msgSuccess('保存成功');
    isEdit.value = false;
    await loadData();
  } catch (e) {
    proxy?.$modal.msgError('保存失败');
  } finally {
    saveLoading.value = false;
  }
}

onMounted(() => {
  loadMachines();
  loadData();
});
</script>

<style lang="scss" scoped>
.recipe-detail-page {
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    .page-title { font-size: 18px; font-weight: 600; }
    .header-actions { display: flex; gap: 8px; }
  }
  .tab-toolbar { display: flex; gap: 8px; }
  .form-grid .el-input-number { width: 100%; }
}
</style>
