<script lang="ts" setup>
import BasePageableTable from "@/components/base/base-pageable-table/BasePageableTable.vue";
import DefaultToolButton from "@/components/base/default-tool-button/DefaultToolButton.vue";
import DefaultOperateButtonColumn from "@/components/base/default-column/DefaultOperateButtonColumn.vue";
import { usePage } from "@/composables/use-page";
import BaseFormWithTable from "@/components/base/base-form-with-table/BaseFormWithTable.vue";
import BaseSelect from "@/components/base/base-select/BaseSelect.vue";
import { $t } from "@/common/languages";
import type { FormInstance, FormRules } from "element-plus";
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 { get, post } from "@/common/http/request";
import { ElMessage } 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 { type FieldMappingConfig, type DetailLoadConfig } from "@/components/base/base-form-with-table/type";
import BaseItemDialog from "@/components/base/base-item-dialog/BaseItemDialog.vue";

const getPageUrl = "/warehouse/warehousereceipt/getWarehouseReceiptPage";
const getItemUrl = "/warehouse/warehousereceipt/getWarehouseReceiptDetail";
const addUrl = "/warehouse/warehousereceipt/addWarehouseReceipt";
const editUrl = "/warehouse/warehousereceipt/updateWarehouseReceipt";
const removeUrl = "/warehouse/warehousereceipt/deleteWarehouseReceipt";
const approveUrl = "/warehouse/warehousereceipt/approveWarehouseReceipt";
const rejectUrl = "/warehouse/warehousereceipt/rejectWarehouseReceipt";
const partNumberExistsUrl = "/warehouse/warehouseitem/existsWarehouseItem";
const getWarehouseSelectListUrl = "/warehouse/warehouse/getWarehouseSelectList";

const searchers = [{ name: "searchCode", type: "text" as const, placeholder: $t("_prop.common.searchCode") }];

const tableRef = ref<InstanceType<typeof ExpandablePageableTable> | null>(null);
const { useAdd, useEdit, useRemove, useGeneralPageRef, useApprove, useReject } = usePage(tableRef);
const { title, visible, formType, form, itemVisible, itemParentId } = useGeneralPageRef();
const { getFormStatusLabel } = useStatus();
const baseFormWithTableRef = ref<InstanceType<typeof BaseFormWithTable>>();
const warehouseSelectRef = ref<InstanceType<typeof BaseSelect>>();

const itemArrayName = "receiptItems";

const rules = reactive<FormRules>({
  storeNo: [{ required: true, message: $t("_message.warehouse.warehousereceipt.select_storeId"), trigger: "change" }],
  storeName: [{ required: true, message: $t("_message.warehouse.warehousereceipt.select_storeId"), trigger: "change" }],
  formCode: [{ required: true, message: $t("_message.warehouse.warehousereceipt.input_formCode"), trigger: "blur" }],
  formName: [{ required: true, message: $t("_message.warehouse.warehousereceipt.input_formName"), trigger: "blur" }],
  formMark: [{ required: false, message: $t("_message.warehouse.warehousereceipt.input_formMark"), trigger: "blur" }],
  receiptItems: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === undefined || value.length === 0) {
          callback($t("_message.warehouse.warehousereceipt.no_items"));
        }
        callback();
      },
      trigger: "change",
    },
  ],
});

const mappingConfig: FieldMappingConfig = {
  partNumber: {
    sourceKey: ["商品编号", "物料编号", "partNumber", "物料编码"],
    header: $t("_prop.warehouse.warehousereceipt.partNumber"),
    width: 20,
    defaultValue: "",
  },
  productSpec: {
    sourceKey: ["物料规格", "型号", "物料型号", "规格", "规格型号", "productSpecs", "productSpec"],
    header: $t("_prop.warehouse.warehousereceipt.productSpec"),
    width: 20,
    defaultValue: "",
  },
  productCount: {
    sourceKey: ["数量", "入库数量", "productCount", "入库数"],
    header: $t("_prop.warehouse.warehousereceipt.productCount"),
    width: 15,
    defaultValue: 0,
    transform: (val: any) => {
      const num = Number(val);
      return isNaN(num) ? 0 : num;
    },
  },
};

const detailConfig: DetailLoadConfig = {
  url: getItemUrl,
  paramName: "id",
  dataPath: "data",
};

const add = () => {
  form.value = {
    formCode: generateDucumentNo(DocumentType.WarehouseReceipt),
    formName: "",
    formMark: "",
    storeNo: null,
    storeName: "",
    receiptItems: [],
  };
  title.value = "_title.warehouse.warehousereceipt.add";
  visible.value = true;
  formType.value = false;
};

const edit = (row: any) => {
  title.value = "_title.warehouse.warehousereceipt.edit";
  form.value = { ...row };
  visible.value = true;
  formType.value = true;
};

const remove = (row: any) => {
  useRemove(removeUrl, row.id, "_message.warehouse.warehousereceipt.delete_message");
};

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

const approve = (row: any) => {
  useApprove(approveUrl, row.id, "_message.warehouse.warehousereceipt.approve_confirm");
};

const reject = (row: any) => {
  useReject(rejectUrl, row.id, "_message.warehouse.warehousereceipt.reject_confirm");
};

const topButtonClick = (eventName: string) => {
  switch (eventName) {
    case "add":
      add();
      break;
  }
};

const operateButtonClick = (eventName: string, row: any) => {
  switch (eventName) {
    case "edit":
      edit(row);
      break;
    case "remove":
      remove(row);
      break;
    case "showItem":
      showItem(row);
      break;
    case "approve":
      approve(row);
      break;
    case "reject":
      reject(row);
      break;
  }
};

const authShowFunc = (row: any, button: globalThis.ButtonProp) => {
  if (row.status === 0 && button.eventName === "reject") return false;
  if (row.status === 1 && button.eventName === "approve") return false;
  if (row.status === 1 && button.eventName === "edit") 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 submit = (form: any, formRef: FormInstance | undefined) => {
  const targetRef = formRef || (baseFormWithTableRef.value as any)?.baseFormRef;
  if (!targetRef) return;

  // 从 BaseSelect 获取仓库名称
  const storeName = warehouseSelectRef.value?.getLabel();
  if (storeName) {
    form.storeName = storeName;
  }

  targetRef.validate((valid: any) => {
    if (valid) {
      if (formType.value) useEdit(editUrl, form, visible);
      else useAdd(addUrl, form, visible);
    }
  });
};
</script>
<template>
  <ExpandablePageableTable
    :url="getPageUrl"
    :searchers="searchers"
    ref="tableRef"
    :item-url="getItemUrl"
    item-id-key="id"
    item-id-name="id"
    item-field-name="receiptItems"
  >
    <template #tool-button>
      <DefaultToolButton @top-button-click="topButtonClick" />
    </template>
    <template #columns>
      <el-table-column :label="$t('_prop.warehouse.warehousereceipt.formCode')" prop="formCode" />
      <el-table-column :label="$t('_prop.warehouse.warehousereceipt.storeName')" prop="storeName" />
      <el-table-column :label="$t('_prop.warehouse.warehousereceipt.formName')" prop="formName" />
      <el-table-column :label="$t('_prop.warehouse.warehousereceipt.formMark')" prop="formMark" />
      <el-table-column :label="$t('_prop.common.createDate')" prop="createDate" :formatter="formatDate" />
      <DefaultStatusSwitchColumn
        status-param-name="status"
        :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.warehousereceipt.partNumber')" prop="partNumber" />
        <el-table-column :label="$t('_prop.warehouse.warehousereceipt.productSpec')" prop="productSpec" />
        <el-table-column :label="$t('_prop.warehouse.warehousereceipt.productCount')" prop="productCount" />
      </el-table>
    </template>
  </ExpandablePageableTable>
  <BaseFormWithTable
    ref="baseFormWithTableRef"
    v-model:visible="visible"
    @submit="submit"
    v-model:form="form"
    :title="$t(title)"
    :rules="rules"
    :base-title="$t('_title.warehouse.warehousereceipt.baseTitle')"
    :table-title="$t('_title.warehouse.warehousereceipt.tableTitle')"
    item-array-name="receiptItems"
    :mapping-config="mappingConfig"
    :template-file-name="$t('_title.warehouse.warehousereceipt.templateFileName')"
    :detail-config="detailConfig"
  >
    <template #form-items>
      <el-form-item prop="id" v-if="false"><el-input v-model="form.id" /></el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.warehouse.warehousereceipt.formCode')" prop="formCode">
            <el-input
              v-model="form.formCode"
              :placeholder="$t('_message.warehouse.warehousereceipt.input_formCode')"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.warehouse.warehousereceipt.storeName')" prop="storeNo">
            <BaseSelect
              v-model="form.storeNo"
              :url="getWarehouseSelectListUrl"
              ref="warehouseSelectRef"
              :placeholder="$t('_message.warehouse.warehousereceipt.select_storeId')"
              :props="{ label: 'storeName', value: 'id' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.warehouse.warehousereceipt.formName')" prop="formName">
            <el-input v-model="form.formName" :placeholder="$t('_message.warehouse.warehousereceipt.input_formName')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="$t('_prop.warehouse.warehousereceipt.formMark')" prop="formMark">
        <el-input
          v-model="form.formMark"
          :placeholder="$t('_message.warehouse.warehousereceipt.input_formMark')"
          type="textarea"
          autosize
        />
      </el-form-item>
    </template>
    <template #form-table-columns>
      <el-table-column :label="$t('_prop.warehouse.warehousereceipt.partNumber')" width="180">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${itemArrayName}.${$index}.partNumber`"
            :rules="{
              required: true,
              validator: (rule: any, value: any, callback: any) => {
                if (!value) {
                  callback($t('_message.warehouse.warehousereceipt.input_partNumber'));
                }
                (async () => {
                  try {
                    const isExists = await get(partNumberExistsUrl, { partNumber: value }).then(res => res.data);
                    if (isExists) {
                      callback();
                    }
                    callback($t('_message.warehouse.warehousereceipt.not_exist_partNumber'));
                  } catch (err: any) {
                    callback(new Error(err));
                  }
                })();
              },
              trigger: 'blur',
            }"
          >
            <el-input v-model="row.partNumber" size="small" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column :label="$t('_prop.warehouse.warehousereceipt.productSpec')" width="200">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${itemArrayName}.${$index}.productSpec`">
            <el-input v-model="row.productSpec" size="small" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column :label="$t('_prop.warehouse.warehousereceipt.productCount')" width="150">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${itemArrayName}.${$index}.productCount`"
            :rules="{
              required: true,
              validator: (rule: any, value: any, callback: any) => {
                if (!value || value <= 0) {
                  callback($t('_message.warehouse.warehousereceipt.input_productCount'));
                }
                callback();
              },
              trigger: 'blur',
            }"
          >
            <el-input-number v-model="row.productCount" size="small" :min="1" />
          </el-form-item>
        </template>
      </el-table-column>
    </template>
  </BaseFormWithTable>
  <BaseItemDialog
    :title="$t('_title.warehouse.warehousereceipt.showItem')"
    v-model:visible="itemVisible"
    :url="getItemUrl"
    parent-param-name="id"
    v-model:parent-param-value="itemParentId"
  >
    <template #columns>
      <el-table-column
        :label="$t('_prop.warehouse.warehousereceipt.partNumber')"
        prop="partNumber"
        min-width="180"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('_prop.warehouse.warehousereceipt.productSpec')"
        prop="productSpec"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('_prop.warehouse.warehousereceipt.productCount')"
        prop="productCount"
        min-width="120"
        align="right"
      />
    </template>
  </BaseItemDialog>
</template>
