<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, 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 ExpandablePageableTable from "@/components/base/expandable-pageable-table/ExpandablePageableTable.vue";
import { get } from "@/common/http/request";
import { type FieldMappingConfig } 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 searchers = [
  {
    name: "customerName",
    type: "text" as const,
    placeholder: $t("_prop.sale.saleorder.customerName"),
    clearable: true,
  },
];

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" }],
  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, useGeneralPageRef, useApprove, useReject } = usePage(tableRef);
const { title, visible, formType, form, itemVisible, itemParentId } = useGeneralPageRef();
const { getFormStatusLabel } = useStatus();
const baseFormWithTableRef = ref<InstanceType<typeof BaseFormWithTable>>();

/**
 * 可以自定义的变量
 */

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 "SO" + dateStr;
};

// 监听客户选择变化，同步更新客户名称
const handleCustomerChange = (value: number) => {
  const selected = keyAccountOptions.value.find(item => Number(item.value) === value);
  if (selected) {
    form.value.customerName = selected.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,
    saleOrderItems: [],
  };
  visible.value = true;
  formType.value = true;

  // 加载明细数据
  get(getDetailUrl, { saleOrderId: row.id })
    .then(res => {
      form.value.saleOrderItems = res.data || [];
    })
    .catch(err => {
      console.error("Failed to load sale order items:", err);
    });
};

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

const approve = (row: any) => {
  useApprove(approveUrl, row.id);
};

const reject = (row: any) => {
  useReject(rejectUrl, row.id);
};

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) => {
  if (row.formStatus === 1 && button.eventName === "approve") return false;
  if (row.formStatus === 0 && button.eventName === "reject") return false;
  if (row.formStatus === 1 && button.eventName === "edit") return false;
  if (row.formStatus === 1 && button.eventName === "remove") return false;
  return true;
};

const mappingConfig: FieldMappingConfig = {
  partNumber: {
    sourceKey: "物料编号",
    defaultValue: "",
  },
  productSpecs: {
    sourceKey: "物料型号",
    defaultValue: "",
  },
  saleCount: {
    sourceKey: "数量",
    defaultValue: 0,
    transform: (val: any) => {
      const num = Number(val);
      return isNaN(num) ? 0 : num;
    },
  },
  price: {
    sourceKey: "单价",
    defaultValue: 0,
    transform: (val: any) => {
      const num = Number(val);
      return isNaN(num) ? 0 : num;
    },
  },
  saleMark: {
    sourceKey: "备注",
    defaultValue: "",
  },
};

// 计算总价
const calculateTotalPrice = (row: any) => {
  if (row.saleCount && row.price) {
    row.totalPrice = Number((row.saleCount * row.price).toFixed(2));
  }
};
</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.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="formStatus"
        :status-label-mapping="getFormStatusLabel"
        :switch-on-value="1"
        :switch-off-value="0"
      />
      <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"
    upload-desc="销售明细"
    :mapping-config="mappingConfig"
  >
    <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-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="2"
        />
      </el-form-item>
    </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.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="请输入备注" 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>
