<template>
  <el-dialog
    v-model="visible"
    title="批量批改配置"
    width="820px"
    :close-on-click-modal="!submitting"
    @close="handleCancel"
    @closed="handleClosed"
  >
    <el-alert
      :title="`已选择 ${currentRecords.length} 条床垫清单，提交后将只批改所选配置中录入类型的明细名称。`"
      type="warning"
      :closable="false"
      class="mb-12"
    />

    <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
      <el-form-item label="配置名称" prop="erp_pzid">
        <el-select v-model="form.erp_pzid" filterable placeholder="请选择配置名称" class="w-full" @change="handleConfigChange">
          <el-option v-for="item in configOptions" :key="item.pzid" :label="item.name" :value="item.pzid" />
        </el-select>
      </el-form-item>
      <el-form-item label="批改后明细名称" prop="new_bj_namemx">
        <el-input v-model="form.new_bj_namemx" maxlength="200" show-word-limit clearable />
      </el-form-item>
    </el-form>

    <div v-if="result" class="batch-result">
      <el-descriptions :column="4" border size="small">
        <el-descriptions-item label="总数">{{ result.totalCount }}</el-descriptions-item>
        <el-descriptions-item label="成功">{{ result.successCount }}</el-descriptions-item>
        <el-descriptions-item label="跳过">{{ result.skipCount }}</el-descriptions-item>
        <el-descriptions-item label="失败">{{ result.failCount }}</el-descriptions-item>
      </el-descriptions>
      <el-table :data="result.items || []" height="260" border class="mt-12">
        <el-table-column prop="biz_code" label="床垫编码" min-width="160" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)" size="small">{{ statusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="err_msg" label="原因" min-width="260" show-overflow-tooltip />
      </el-table>
    </div>

    <template #footer>
      <el-button :disabled="submitting" @click="visible = false">关闭</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">确认批改</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { getConfigureCodeList } from "@/api/modules/basicinfo";
import { BatchModifyMattressInterfaceConfig } from "@/api/modules/quote";

interface Props {
  modelValue?: boolean;
  records?: any[];
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  records: () => []
});

const emit = defineEmits(["cancel", "submit", "close", "closed", "update:modelValue"]);

const visible = ref(false);
const submitting = ref(false);
const currentRecords = ref<any[]>([]);
const configOptions = ref<any[]>([]);
const result = ref<any>(null);
const formRef = ref<FormInstance>();
const configcodetype = ref<number>(0);

const form = reactive({
  erp_pzid: undefined as number | undefined,
  bj_pzname: "",
  new_bj_namemx: ""
});

const rules = computed<FormRules>(() => ({
  erp_pzid: [{ required: true, message: "请选择配置名称", trigger: "change" }],
  new_bj_namemx: [
    {
      validator: (_rule, value, callback) => {
        if (!String(value || "").trim()) {
          callback(new Error("请输入批改后明细名称"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ]
}));

const show = async (rows: any[] = props.records) => {
  result.value = null;
  currentRecords.value = rows;
  form.erp_pzid = undefined;
  form.bj_pzname = "";
  form.new_bj_namemx = "";

  const types = [...new Set(rows.map(item => Number(item.erp_configcodetype || 0)).filter(Boolean))];
  if (types.length !== 1) {
    ElMessage.warning("选中清单存在多个配置字典，请先筛选为同一配置字典类型");
    emit("cancel");
    return;
  }

  configcodetype.value = types[0];
  const res: any = await getConfigureCodeList({ typeid: configcodetype.value, inputtype: 1 });
  const list = res?.datatable || [];
  configOptions.value = list;
  if (!list.length) {
    ElMessage.warning("当前配置字典没有录入类型配置");
    emit("cancel");
    return;
  }
  visible.value = true;
};

const handleConfigChange = (value: number) => {
  const item = configOptions.value.find(option => Number(option.pzid) === Number(value));
  form.bj_pzname = item?.name || "";
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();
  form.new_bj_namemx = form.new_bj_namemx.trim();

  try {
    await ElMessageBox.confirm(
      `本次将批改 ${currentRecords.value.length} 条选中清单，跳过不存在该配置或非录入类型的清单。是否继续？`,
      "确认批改",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false
      }
    );
  } catch {
    return;
  }

  submitting.value = true;
  try {
    const res = await BatchModifyMattressInterfaceConfig({
      list: currentRecords.value.map(item => Number(item.mattressid)),
      configcodetype: configcodetype.value,
      erp_pzid: Number(form.erp_pzid),
      bj_pzname: form.bj_pzname,
      new_bj_namemx: form.new_bj_namemx
    });
    result.value = res;
    ElNotification({
      title: "批改完成",
      message: `成功 ${res.successCount} 条，跳过 ${res.skipCount} 条，失败 ${res.failCount} 条`,
      type: res.failCount > 0 ? "warning" : "success"
    });
  } finally {
    submitting.value = false;
  }
};

const statusText = (status: Number) => {
  if (status === 2) return "成功";
  if (status === 4) return "跳过";
  return "失败";
};

const statusTagType = (status: Number) => {
  if (status === 2) return "success";
  if (status === 4) return "warning";
  return "danger";
};

const handleCancel = () => {
  if (submitting.value) return;
  visible.value = false;
  emit("cancel");
};

const handleClosed = () => {
  if (!submitting.value) {
    formRef.value?.clearValidate();
  }
  emit("closed");
};

watch(
  () => props.modelValue,
  value => {
    if (value) {
      show(props.records);
    } else {
      visible.value = false;
    }
  },
  { immediate: true }
);

defineExpose({ show });
</script>

<style scoped lang="scss">
.batch-result {
  margin-top: 12px;
}
</style>
