<script lang="ts" setup>
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 { $t } from "@/common/languages";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import BaseItemDialog from "@/components/base/base-item-dialog/BaseItemDialog.vue";
import BaseFormWithTable from "@/components/base/base-form-with-table/BaseFormWithTable.vue";
import { get } from "@/common/http/request";
import { type FieldMappingConfig } from "@/components/base/base-form-with-table/type";
import ExpandablePageableTable from "@/components/base/expandable-pageable-table/ExpandablePageableTable.vue";
import BaseSelect from "@/components/base/base-select/BaseSelect.vue";

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

const getPageUrl = "/warehouse/inventorycount/getInventoryCountPage";
const addUrl = "/warehouse/inventorycount/addInventoryCount";
const editUrl = "/warehouse/inventorycount/updateInventoryCount";
const removeUrl = "/warehouse/inventorycount/deleteInventoryCount";
const itemUrl = "/warehouse/inventorycount/getInventoryCountDetail";

const warehouseSelectUrl = "/warehouse/warehouse/getWarehouseSelectList";
const partNumberExistsUrl = "/warehouse/warehouseitem/existsWarehouseItem";

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

const rules = reactive<FormRules>({
  formName: [{ required: true, message: $t("_message.warehouse.inventorycount.input_formName"), trigger: "blur" }],
  storeNo: [{ required: true, message: $t("_message.warehouse.inventorycount.select_storeId"), trigger: "change" }],
  storeName: [{ required: true, message: $t("_message.warehouse.inventorycount.select_storeId"), trigger: "change" }],
  isInit: [{ required: true, message: "请选择是否初始库存", trigger: "change" }],
  countItems: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === undefined || value.length === 0) {
          callback($t("_message.warehouse.inventorycount.upload_countItems"));
        }
        callback();
      },
      trigger: "change",
    },
  ],
  partNumber: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback($t("_message.warehouse.inventorycount.input_partNumber"));
        }
        (async () => {
          try {
            const isExists = await get(partNumberExistsUrl, { partNumber: value }).then(res => res.data);
            if (isExists) {
              callback();
            } else {
              callback($t("_message.warehouse.inventorycount.not_exist_partNumber"));
            }
          } catch (err: any) {
            callback(new Error(err));
          }
        })();
      },
      trigger: "blur",
    },
  ],
});

const itemArrayName = "countItems";

/**
 * 基本不变通用变量
 */
const tableRef = ref<InstanceType<typeof ExpandablePageableTable> | null>(null);
const { useAdd, useEdit, useRemove, useGeneralPageRef } = usePage(tableRef);
const { title, visible, formType, form, itemVisible, itemParentId } = useGeneralPageRef();
const baseFormWithTableRef = ref<InstanceType<typeof BaseFormWithTable>>();

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

const add = () => {
  form.value = {};
  // 前端生成单据编号
  form.value.formCode = "PD" + new Date().toISOString().slice(0, 19).replace(/[-T:]/g, "");
  form.value.isInit = 0;
  title.value = "_title.warehouse.inventorycount.add";
  visible.value = true;
  formType.value = false;
};

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

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

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

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;
  }
};

// Excel导入配置
const mappingConfig: FieldMappingConfig = {
  partNumber: {
    sourceKey: "物料编号",
    defaultValue: "",
  },
  productSpec: {
    sourceKey: "物料型号",
    defaultValue: "",
  },
  productCount: {
    sourceKey: "数量",
    defaultValue: 0,
    transform: (val: any) => {
      const num = Number(val);
      return isNaN(num) ? 0 : num;
    },
  },
};

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

  if (!targetRef) return;

  targetRef.validate((valid: any) => {
    if (valid) {
      // 设置storeName
      if (formData.storeNo && baseSelectRef.value) {
        formData.storeName = baseSelectRef.value.getLabel();
      }
      if (formType.value) useEdit(editUrl, formData, visible);
      else useAdd(addUrl, formData, visible);
    }
  });
};

const baseSelectRef = ref<InstanceType<typeof BaseSelect> | null>(null);

// 处理仓库选择变化
const handleStoreChange = (val: number) => {
  if (val && baseSelectRef.value) {
    form.value.storeName = baseSelectRef.value.getLabel();
  }
};

// 获取单据类型显示文本
const getFormTypeText = (reserve1: number) => {
  return reserve1 === 1 ? $t("_prop.warehouse.inventorycount.isInit") : "盘点";
};
</script>
<template>
  <ExpandablePageableTable
    :url="getPageUrl"
    :searchers="searchers"
    ref="tableRef"
    :item-url="itemUrl"
    item-id-key="id"
    item-id-name="id"
    itemFieldName="inventory_count"
  >
    <template #tool-button>
      <DefaultToolButton @top-button-click="topButtonClick" />
    </template>
    <template #columns>
      <el-table-column :label="$t('_prop.warehouse.inventorycount.reserve1')" width="100">
        <template #default="{ row }">
          <span>{{ getFormTypeText(row.reserve1) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('_prop.warehouse.inventorycount.formCode')" prop="formCode" width="180" />
      <el-table-column :label="$t('_prop.warehouse.inventorycount.storeName')" prop="storeName" width="120" />
      <el-table-column :label="$t('_prop.warehouse.inventorycount.formName')" prop="formName" />
      <el-table-column :label="$t('_prop.warehouse.inventorycount.formMark')" prop="formMark" show-overflow-tooltip />
      <el-table-column :label="$t('_prop.common.createDate')" prop="createDate" width="180" />
      <DefaultOperateButtonColumn @operate-button-click="operateButtonClick" />
    </template>
    <template #item-content="{ itemData }">
      <el-table :data="itemData" size="small" border stripe>
        <el-table-column :label="$t('_prop.warehouse.inventorycount.partNumber')" prop="partNumber" width="150" />
        <el-table-column :label="$t('_prop.warehouse.inventorycount.productSpec')" prop="productSpec" width="200" />
        <el-table-column :label="$t('_prop.warehouse.inventorycount.productCount')" prop="productCount" width="100" />
        <el-table-column
          :label="$t('_prop.warehouse.inventorycount.originalProductCount')"
          prop="originalProductCount"
          width="100"
        />
        <el-table-column :label="$t('_prop.warehouse.inventorycount.diffCount')" prop="diffCount" width="100">
          <template #default="{ row }">
            <span :style="{ color: row.diffCount !== 0 ? '#f56c6c' : '#67c23a' }">
              {{ row.diffCount }}
            </span>
          </template>
        </el-table-column>
      </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.inventorycount.baseTitle')"
    :table-title="$t('_title.warehouse.inventorycount.tableTitle')"
    item-array-name="countItems"
    :mapping-config="mappingConfig"
    :template-file-name="$t('_title.warehouse.inventorycount.templateFileName')"
  >
    <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.inventorycount.storeId')" prop="storeNo">
            <BaseSelect
              ref="baseSelectRef"
              v-model="form.storeNo"
              :url="warehouseSelectUrl"
              name="value"
              label="label"
              @change="handleStoreChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.warehouse.inventorycount.formCode')" prop="formCode">
            <el-input v-model="form.formCode" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.warehouse.inventorycount.formName')" prop="formName">
            <el-input v-model="form.formName" :placeholder="$t('_message.warehouse.inventorycount.input_formName')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.warehouse.inventorycount.isInit')" prop="isInit">
            <el-switch
              v-model="form.isInit"
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="$t('_prop.warehouse.inventorycount.formMark')" prop="formMark">
        <el-input
          v-model="form.formMark"
          :placeholder="$t('_message.warehouse.inventorycount.input_formMark')"
          type="textarea"
        />
      </el-form-item>
    </template>

    <template #form-table-columns>
      <el-table-column :label="$t('_prop.warehouse.inventorycount.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.warehouse.inventorycount.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.inventorycount.productCount')" width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${itemArrayName}.${$index}.productCount`">
            <el-input-number v-model="row.productCount" size="small" :min="0" />
          </el-form-item>
        </template>
      </el-table-column>
    </template>
  </BaseFormWithTable>

  <BaseItemDialog
    :title="$t('_title.warehouse.inventorycount.showItem')"
    v-model:visible="itemVisible"
    :url="itemUrl"
    parent-param-name="id"
    v-model:parent-param-value="itemParentId"
  >
    <template #columns>
      <el-table-column :label="$t('_prop.warehouse.inventorycount.partNumber')" prop="partNumber" width="150" />
      <el-table-column :label="$t('_prop.warehouse.inventorycount.productSpec')" prop="productSpec" width="200" />
      <el-table-column :label="$t('_prop.warehouse.inventorycount.productCount')" prop="productCount" width="100" />
      <el-table-column
        :label="$t('_prop.warehouse.inventorycount.originalProductCount')"
        prop="originalProductCount"
        width="100"
      />
      <el-table-column :label="$t('_prop.warehouse.inventorycount.diffCount')" prop="diffCount" width="100">
        <template #default="{ row }">
          <span :style="{ color: row.diffCount !== 0 ? '#f56c6c' : '#67c23a' }">
            {{ row.diffCount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('_prop.warehouse.inventorycount.stockTakingMark')" prop="stockTakingMark" />
    </template>
  </BaseItemDialog>
</template>
