<script lang="ts" setup>
import DefaultToolButton from "@/components/base/default-tool-button/DefaultToolButton.vue";
import DefaultOperateButtonColumn from "@/components/base/default-column/DefaultOperateButtonColumn.vue";
import DefaultStatusSwitchColumn from "@/components/base/default-column/DefaultStatusSwitchColumn.vue";
import { usePage } from "@/composables/use-page";
import { $t } from "@/common/languages";
import { formatDate } from "@/common/utils/format-utils";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import BaseFormWithTable from "@/components/base/base-form-with-table/BaseFormWithTable.vue";
import BaseItemDialog from "@/components/base/base-item-dialog/BaseItemDialog.vue";
import BaseSelect from "@/components/base/base-select/BaseSelect.vue";
import ExpandablePageableTable from "@/components/base/expandable-pageable-table/ExpandablePageableTable.vue";
import { get, post } from "@/common/http/request";
import { type FieldMappingConfig, type DetailLoadConfig } from "@/components/base/base-form-with-table/type";
import { useStatus } from "@/common/languages/mapping/base-info-mapping";

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

const getPageUrl = "/sale/saleorder/getSaleOrderPage";
const addUrl = "/sale/saleorder/addSaleOrder";
const editUrl = "/sale/saleorder/updateSaleOrder";
const removeUrl = "/sale/saleorder/deleteSaleOrder";
const approveUrl = "/sale/saleorder/approveSaleOrder";
const rejectUrl = "/sale/saleorder/unapproveSaleOrder";
const itemUrl = "/sale/saleorder/getSaleOrderItemList";
const keyAccountSelectUrl = "/sys/keyaccount/getKeyAccountSelectList";
const partNumberExistsUrl = "/warehouse/warehouseitem/existsWarehouseItem";
const warehouseSelectUrl = "/warehouse/warehouse/getWarehouseSelectList";

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

const rules = reactive<FormRules>({
  formCode: [{ required: true, message: $t("_message.sale.saleorder.input_formCode"), trigger: "blur" }],
  formName: [{ required: true, message: $t("_message.sale.saleorder.input_formName"), trigger: "blur" }],
  customerId: [{ required: true, message: $t("_message.sale.saleorder.select_customerId"), trigger: "change" }],
  customerName: [{ required: true, message: $t("_message.sale.saleorder.select_customerId"), trigger: "change" }],
  storeNo: [{ required: true, message: $t("_message.sale.saleorder.select_storeNo"), trigger: "change" }],
  partNumber: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback($t("_message.sale.saleorder.input_partNumber"));
        }
        (async () => {
          try {
            const isExists = await get(partNumberExistsUrl, { partNumber: value }).then(res => res.data);
            if (isExists) {
              callback();
            }
            callback($t("_message.purchase.purchase_order.part_number_not_exists"));
          } catch (err: any) {
            callback(new Error(err));
          }
        })();
      },
      trigger: "blur",
    },
  ],
  saleOrderItems: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === undefined || value.length === 0) {
          callback($t("_message.sale.saleorder.no_sale_order_items"));
        }
        callback();
      },
      trigger: "change",
    },
  ],
});

const itemArrayName = "saleOrderItems";
const getDetailUrl = "/sale/saleorder/getSaleOrderItemList";

/**
 * 基本不变通用变量
 */
const tableRef = ref<InstanceType<typeof ExpandablePageableTable> | null>(null);
const { useAdd, useEdit, useRemove, useApprove, useReject, useGeneralPageRef } = 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 keyAccountOptions = ref<{ label: string; value: string }[]>([]);

const loadKeyAccountOptions = async () => {
  const res = await get(keyAccountSelectUrl);
  if (res.data) {
    keyAccountOptions.value = res.data.map((item: { label: string; value: string }) => ({
      label: item.label,
      value: item.value,
    }));
  }
};

onMounted(() => {
  loadKeyAccountOptions();
});

// 生成单据编号
const generateFormCode = () => {
  const now = new Date();
  const dateStr =
    now.getFullYear().toString() +
    String(now.getMonth() + 1).padStart(2, "0") +
    String(now.getDate()).padStart(2, "0") +
    String(now.getHours()).padStart(2, "0") +
    String(now.getMinutes()).padStart(2, "0") +
    String(now.getSeconds()).padStart(2, "0");
  return "PO" + dateStr;
};

// 监听客户选择变化，同步更新客户名称
const handleCustomerChange = (value: number) => {
  const selected = keyAccountOptions.value.find(item => Number(item.value) === value);
  if (selected) {
    form.value.customerName = selected.label;
  }
};

// 监听仓库选择变化，同步更新仓库名称
const handleWarehouseChange = () => {
  const label = warehouseSelectRef.value?.getLabel();
  if (label) {
    form.value.storeName = label;
  }
};

const add = () => {
  form.value = {
    formCode: generateFormCode(),
  };
  title.value = "_title.sale.saleorder.add";
  visible.value = true;
  formType.value = false;
};

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

  // 延迟设置仓库名称，等待 BaseSelect 加载完成
  if (row.storeNo) {
    setTimeout(() => {
      const label = warehouseSelectRef.value?.getLabel();
      if (label && !form.value.storeName) {
        form.value.storeName = label;
      }
    }, 300);
  }
};

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

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

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

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

const submit = (formData: any, formRef: FormInstance | undefined) => {
  const targetRef = formRef || (baseFormWithTableRef.value as any)?.baseFormRef;
  if (!targetRef) return;

  targetRef.validate((valid: any) => {
    if (valid) {
      if (formType.value) {
        useEdit(editUrl, formData, visible);
      } else {
        useAdd(addUrl, formData, visible);
      }
    }
  });
};

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 "approve":
      approve(row);
      break;
    case "reject":
      reject(row);
      break;
    case "showItem":
      showItem(row);
      break;
  }
};

const authShowFunc = (row: any, button: globalThis.ButtonProp) => {
  // 已审核(formStatus=1)时不显示审核按钮，显示反审按钮
  // 未审核(formStatus=0)时显示审核按钮，不显示反审按钮
  if (row.formStatus === 0 && button.eventName === "reject") return false;
  if (row.formStatus === 1 && button.eventName === "approve") return false;
  // 已审核后不能编辑和删除
  if (row.formStatus === 1 && (button.eventName === "edit" || button.eventName === "remove")) return false;
  return true;
};

const mappingConfig: FieldMappingConfig = {
  partNumber: {
    sourceKey: ["物料编号", "partNumber"],
    header: $t("_prop.sale.saleorder.partNumber"),
    width: 20,
    defaultValue: "",
  },
  productSpecs: {
    sourceKey: ["物料型号", "productSpecs"],
    header: $t("_prop.sale.saleorder.productSpecs"),
    width: 20,
    defaultValue: "",
  },
  saleCount: {
    sourceKey: ["数量", "saleCount"],
    header: $t("_prop.sale.saleorder.saleCount"),
    width: 15,
    defaultValue: 0,
    transform: (val: any) => {
      const num = Number(val);
      return isNaN(num) ? 0 : num;
    },
  },
  price: {
    sourceKey: ["单价", "price"],
    header: $t("_prop.sale.saleorder.price"),
    width: 15,
    defaultValue: 0,
    transform: (val: any) => {
      const num = Number(val);
      return isNaN(num) ? 0 : num;
    },
  },
  saleMark: {
    sourceKey: ["备注", "saleMark"],
    header: $t("_prop.sale.saleorder.saleMark"),
    width: 20,
    defaultValue: "",
  },
};

const detailConfig: DetailLoadConfig = {
  url: getDetailUrl,
  paramName: "saleOrderId",
  dataPath: "data",
};

// 计算总价
const calculateTotalPrice = (row: any) => {
  if (row.saleCount && row.price) {
    row.totalPrice = Number((row.saleCount * row.price).toFixed(2));
  }
};

// 表单状态标签类型映射
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";
};
</script>
<template>
  <ExpandablePageableTable
    :url="getPageUrl"
    :searchers="searchers"
    ref="tableRef"
    :item-url="itemUrl"
    item-id-key="id"
    item-id-name="saleOrderId"
    item-field-name="saleOrderItems"
  >
    <template #tool-button>
      <DefaultToolButton @top-button-click="topButtonClick" />
    </template>
    <template #columns>
      <el-table-column :label="$t('_prop.sale.saleorder.formCode')" prop="formCode" />
      <el-table-column :label="$t('_prop.sale.saleorder.customerName')" prop="customerName" />
      <el-table-column :label="$t('_prop.sale.saleorder.storeName')" prop="storeName" />
      <el-table-column :label="$t('_prop.sale.saleorder.totalValue')" prop="totalValue" />
      <el-table-column :label="$t('_prop.sale.saleorder.formName')" prop="formName" />
      <el-table-column :label="$t('_prop.sale.saleorder.formMark')" prop="formMark" show-overflow-tooltip />
      <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.sale.saleorder.partNumber')" prop="partNumber" width="150" />
        <el-table-column :label="$t('_prop.sale.saleorder.productSpecs')" prop="productSpecs" width="200" />
        <el-table-column :label="$t('_prop.sale.saleorder.saleCount')" prop="saleCount" />
        <el-table-column :label="$t('_prop.sale.saleorder.price')" prop="price" />
        <el-table-column :label="$t('_prop.sale.saleorder.totalPrice')" prop="totalPrice" />
      </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.sale.saleorder.baseTitle')"
    :table-title="$t('_title.sale.saleorder.tableTitle')"
    item-array-name="saleOrderItems"
    :mapping-config="mappingConfig"
    :template-file-name="$t('_title.sale.saleorder.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="8">
          <el-form-item :label="$t('_prop.sale.saleorder.formCode')" prop="formCode">
            <el-input v-model="form.formCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('_prop.sale.saleorder.customerId')" prop="customerId">
            <el-select v-model="form.customerId" clearable style="width: 100%" @change="handleCustomerChange">
              <el-option
                v-for="item in keyAccountOptions"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('_prop.sale.saleorder.formName')" prop="formName">
            <el-input v-model="form.formName" :placeholder="$t('_message.sale.saleorder.input_formName')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item :label="$t('_prop.sale.saleorder.storeNo')" prop="storeNo">
            <BaseSelect
              ref="warehouseSelectRef"
              v-model="form.storeNo"
              :url="warehouseSelectUrl"
              style="width: 100%"
              @change="handleWarehouseChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item :label="$t('_prop.sale.saleorder.formMark')" prop="formMark">
            <el-input
              v-model="form.formMark"
              :placeholder="$t('_message.sale.saleorder.input_formMark')"
              type="textarea"
              :rows="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </template>
    <template #form-table-columns>
      <el-table-column :label="$t('_prop.sale.saleorder.partNumber')" width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${itemArrayName}.${$index}.partNumber`" :rules="rules.partNumber">
            <el-input v-model="row.partNumber" size="small" />
          </el-form-item>
        </template>
      </el-table-column>

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

      <el-table-column :label="$t('_prop.sale.saleorder.saleCount')" width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${itemArrayName}.${$index}.saleCount`">
            <el-input-number v-model="row.saleCount" size="small" :min="1" @change="calculateTotalPrice(row)" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column :label="$t('_prop.sale.saleorder.price')" width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${itemArrayName}.${$index}.price`">
            <el-input-number
              v-model="row.price"
              size="small"
              :min="0"
              :precision="2"
              @change="calculateTotalPrice(row)"
            />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column :label="$t('_prop.sale.saleorder.totalPrice')" width="120">
        <template #default="{ row }">
          <span>{{ row.totalPrice?.toFixed(2) || "0.00" }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('_prop.sale.saleorder.saleMark')" width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${itemArrayName}.${$index}.saleMark`">
            <el-input v-model="row.saleMark" :placeholder="$t('_message.sale.saleorder.input_saleMark')" size="small" />
          </el-form-item>
        </template>
      </el-table-column>
    </template>
  </BaseFormWithTable>
  <BaseItemDialog
    :title="$t('_title.sale.saleorder.showItem')"
    v-model:visible="itemVisible"
    :url="getDetailUrl"
    parent-param-name="saleOrderId"
    v-model:parent-param-value="itemParentId"
  >
    <template #columns>
      <el-table-column :label="$t('_prop.sale.saleorder.partNumber')" prop="partNumber" width="150" />
      <el-table-column :label="$t('_prop.sale.saleorder.productSpecs')" prop="productSpecs" width="200" />
      <el-table-column :label="$t('_prop.sale.saleorder.saleCount')" prop="saleCount" />
      <el-table-column :label="$t('_prop.sale.saleorder.price')" prop="price" />
      <el-table-column :label="$t('_prop.sale.saleorder.totalPrice')" prop="totalPrice" />
      <el-table-column :label="$t('_prop.sale.saleorder.saleMark')" prop="saleMark" />
    </template>
  </BaseItemDialog>
</template>
