<script lang="ts" setup>
import DefaultToolButton from "@/components/base/default-tool-button/DefaultToolButton.vue";
import DefaultOperateButtonColumn from "@/components/base/default-column/DefaultOperateButtonColumn.vue";
import { $t } from "@/common/languages";
import BaseTableForm from "@/components/base/base-table-form/BaseTableForm.vue";
import { formatDate } from "@/common/utils/format-utils";
import ExpandablePageableTable from "@/components/base/expandable-pageable-table/ExpandablePageableTable.vue";
import DefaultStatusSwitchColumn from "@/components/base/default-column/DefaultStatusSwitchColumn.vue";
import { useStatus } from "@/common/languages/mapping/base-info-mapping";
import { usePage } from "@/composables/use-page";
import { get, post } from "@/common/http/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref } from "vue";
import { generateDucumentNo } from "@/common/utils/document-no-generator/document-no-generator";
import { DocumentType } from "@/common/enums/DocumentType";
import BaseItemDialog from "@/components/base/base-item-dialog/BaseItemDialog.vue";

/**
 * 必须要的变量
 */

const getPageUrl = "/production/productionissue/getProductionIssuePage";
const getItemUrl = "/production/productionissue/getProductionIssueItemList";
const approveUrl = "/production/productionissue/approvingProductionIssue";
const rejectUrl = "/production/productionissue/rejectProductionIssue";
const generateProductionReturnUrl = "/production/productionissue/productionReturn";
const searchers = [{ name: "searchCode", type: "text" as const, placeholder: $t("_prop.common.searchCode") }];
/**
 * 基本不变通用变量
 */
const tableRef = ref<InstanceType<typeof ExpandablePageableTable> | null>(null);
const { getFormStatusLabel } = useStatus();
const { useApprove, useReject, useGeneralPageRef } = usePage(tableRef);
const { itemVisible, itemParentId } = useGeneralPageRef();
const productionReturnRef = ref<InstanceType<typeof BaseTableForm>>();
const productionReturnVisible = ref(false);
const productionReturnTableData = ref([]);
const currentIssueId = ref();
const currentIssueRow = ref<any>({});
/**
 * 可以自定义的变量
 */

const approve = (row: any) => {
  useApprove(approveUrl, row.id);
};
const reject = (row: any) => {
  useReject(rejectUrl, row.id);
};
const productionReturn = async (row: any) => {
  // 检查发料单状态，只有审核通过的才能生成退料单
  if (row.formStatus !== 1) {
    ElMessage.warning($t("_message.production.production_issue.only_approved_can_return"));
    return;
  }

  currentIssueId.value = row.id;
  currentIssueRow.value = row;
  try {
    const rowData = await get(getItemUrl, { issueId: row.id }).then(res => res.data);
    productionReturnTableData.value = rowData.map((item: any) => ({
      partNumber: item.partNumber,
      productSpecs: item.productSpecs,
      expectedReturnQty: item.actualQty - item.requiredQty > 0 ? item.actualQty - item.requiredQty : 0,
      actualReturnQty: item.actualQty - item.requiredQty > 0 ? item.actualQty - item.requiredQty : 0,
    }));
    productionReturnVisible.value = true;
  } catch (error) {
    ElMessage.error($t("_message.production.production_issue.get_detail_failed"));
    console.error("获取发料单明细失败:", error);
  }
};

const showItem = (row: any) => {
  itemParentId.value = row.id;
  itemVisible.value = true;
};

const operateButtonClick = (eventName: string, row: any) => {
  switch (eventName) {
    case "approve":
      approve(row);
      break;
    case "reject":
      reject(row);
      break;
    case "productionReturn":
      productionReturn(row);
      break;
    case "showItem":
      showItem(row);
      break;
  }
};
const authShowFunc = (row: any, button: globalThis.ButtonProp) => {
  if (row.formStatus === 0 && button.eventName === "reject") return false;
  if (row.formStatus === 1 && button.eventName === "approve") return false;
  if (
    row.formStatus === 8 &&
    (button.eventName === "approve" || button.eventName === "reject" || button.eventName === "productionReturn")
  )
    return false;
  return true;
};

// 表单状态标签类型映射
const getFormStatusTagType = (code: number | null): string => {
  const tagTypeMap: Record<number, string> = {
    0: "info", // 未审核
    1: "success", // 已审核
    2: "danger", // 已驳回
    3: "warning", // 未完成
    4: "success", // 已完成
    5: "primary", // 入库中
    6: "info", // 已导入
    7: "warning", // 审核中
    8: "danger", // 已退回
  };
  return tagTypeMap[code ?? -1] || "info";
};

const generateProductionReturn = async () => {
  if (!productionReturnTableData.value || productionReturnTableData.value.length === 0) {
    ElMessage.warning($t("_message.production.production_issue.no_return_data"));
    return;
  }

  const hasValidReturn = productionReturnTableData.value.some((item: any) => item.actualReturnQty > 0);
  if (!hasValidReturn) {
    ElMessage.warning($t("_message.production.production_issue.enter_valid_return_qty"));
    return;
  }

  ElMessageBox.confirm($t("_message.production.production_issue.generate_return_confirm"), $t("_level.warning"), {
    confirmButtonText: $t("_button.confirm"),
    cancelButtonText: $t("_button.cancel"),
    type: "warning",
  }).then(async () => {
    try {
      const formCode = generateDucumentNo(DocumentType.ProductionReturn);
      const formMark =
        $t("_message.common.generate_document_mark_prefix") +
        currentIssueRow.value.formCode +
        $t("_message.production.production_issue.generate_return_mark_suffix") +
        formCode +
        $t("_message.common.generate_document_mark_suffix");

      const requestData = {
        formCode,
        formMark,
        storeNo: currentIssueRow.value.storeNo,
        storeName: currentIssueRow.value.storeName,
        items: productionReturnTableData.value
          .filter((item: any) => item.actualReturnQty > 0)
          .map((item: any) => ({
            partNumber: item.partNumber,
            storeNo: currentIssueRow.value.storeNo,
            productCount: item.actualReturnQty,
            demandCount: item.expectedReturnQty - item.actualReturnQty,
          })),
      };

      const res = await post(generateProductionReturnUrl + "?id=" + currentIssueId.value, requestData);
      if (res.code === 0) {
        ElMessage.success($t("_message.production.production_issue.generate_return_success"));
        productionReturnVisible.value = false;
        tableRef.value?.reload();
      } else {
        ElMessage.error($t("_message.production.production_issue.generate_return_fail") + res.msg);
      }
    } catch (error) {
      ElMessage.error($t("_message.production.production_issue.generate_return_fail") + error);
      console.error("生成退料单失败:", error);
    }
  });
};
</script>
<template>
  <ExpandablePageableTable
    :url="getPageUrl"
    ref="tableRef"
    :searchers="searchers"
    :item-url="getItemUrl"
    item-id-key="id"
    item-id-name="issueId"
    item-field-name="issueItems"
  >
    <template #tool-button>
      <DefaultToolButton />
    </template>
    <template #columns>
      <el-table-column :label="$t('_prop.production.production_issue.formCode')" prop="formCode" />
      <el-table-column :label="$t('_prop.production.production_issue.storeName')" prop="storeName" />
      <el-table-column :label="$t('_prop.production.production_issue.formMark')" prop="formMark" />
      <el-table-column :label="$t('_prop.common.createDate')" prop="createDate" :formatter="formatDate" />
      <DefaultStatusSwitchColumn
        status-param-name="formStatus"
        :status-label-mapping="getFormStatusLabel"
        :tag-type-mapping="getFormStatusTagType"
      />
      <DefaultOperateButtonColumn @operate-button-click="operateButtonClick" :auth-show-func="authShowFunc" />
    </template>
    <template #item-content="{ itemData }">
      <el-table :data="itemData" size="small" border stripe>
        <el-table-column :label="$t('_prop.warehouse.warehouse_item.partNumber')" prop="partNumber" />
        <el-table-column :label="$t('_prop.warehouse.warehouse_item.productSpecs')" prop="productSpecs" />
        <el-table-column :label="$t('_prop.production.production_issue.requiredQty')" prop="requiredQty" />
        <el-table-column :label="$t('_prop.production.production_issue.actualQty')" prop="actualQty" />
      </el-table>
    </template>
  </ExpandablePageableTable>
  <BaseTableForm
    ref="productionReturnRef"
    v-model:visible="productionReturnVisible"
    :title="$t('_title.production.production_issue.returnDialog')"
    :tableData="productionReturnTableData"
    :selectable="false"
    :useAuth="false"
  >
    <template #table-columns>
      <el-table-column :label="$t('_prop.production.bom_item.partNumber')" prop="partNumber" />
      <el-table-column :label="$t('_prop.production.bom_item.productSpecs')" prop="productSpecs" />
      <el-table-column :label="$t('_prop.production.production_issue.expectedReturnQty')" prop="expectedReturnQty" />
      <el-table-column :label="$t('_prop.production.production_issue.actualReturnQty')" prop="actualReturnQty">
        <template #default="{ row }">
          <el-input-number v-model="row.actualReturnQty" :min="0" :max="row.expectedReturnQty" />
        </template>
      </el-table-column>
    </template>
    <template #attachment>
      <el-button type="primary" @click="generateProductionReturn">
        {{ $t("_button.submit") }}
      </el-button>
    </template>
  </BaseTableForm>
  <BaseItemDialog
    :title="$t('_title.production.production_issue.showItem')"
    v-model:visible="itemVisible"
    :url="getItemUrl"
    parent-param-name="issueId"
    v-model:parent-param-value="itemParentId"
  >
    <template #columns>
      <el-table-column :label="$t('_prop.warehouse.warehouse_item.partNumber')" prop="partNumber" />
      <el-table-column :label="$t('_prop.warehouse.warehouse_item.productSpecs')" prop="productSpecs" />
      <el-table-column :label="$t('_prop.production.production_issue.requiredQty')" prop="requiredQty" />
      <el-table-column :label="$t('_prop.production.production_issue.actualQty')" prop="actualQty" />
    </template>
  </BaseItemDialog>
</template>
