<template>
  <div>
    <el-dialog v-model="productDialog.visible.value" :title="productDialog.title.value" width="80%" append-to-body>
      <el-row :gutter="20">
        <el-col :span="24">
          <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="mb-[10px]">
              <el-card shadow="hover">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
                  <el-form-item label="物料编码" prop="productCode">
                    <el-input v-model="queryParams.productCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="物料名称" prop="productName">
                    <el-input v-model="queryParams.productName" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="品牌" prop="externalBrand">
                    <el-input v-model="queryParams.externalBrand" placeholder="请输入品牌" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <!--<el-form-item label="激活标识" prop="activeFlag">
                    <el-select v-model="queryParams.activeFlag" placeholder="请选择激活标识" clearable>
                      <el-option v-for="dict in active_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                  </el-form-item>-->
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
          </transition>

          <el-card shadow="hover">
            <template v-if="prop.multiple" #header>
              <el-tag v-for="product in selectProductList" :key="product.productId" closable style="margin: 2px" @close="handleCloseTag(product)">
                {{ product.productName }}
              </el-tag>
            </template>

            <vxe-table
              ref="tableRef"
              height="400px"
              border
              show-overflow
              :data="wmsBaseProductList"
              :loading="loading"
              :row-config="{ keyField: 'productId', isHover: true }"
              :checkbox-config="{ reserve: true, trigger: 'row', highlight: true, showHeader: prop.multiple }"
              @checkbox-all="handleCheckboxAll"
              @checkbox-change="handleCheckboxChange"
            >
              <vxe-column type="checkbox" width="50" align="center" />
              <vxe-column key="productCode" title="物料编码" align="center" field="productCode" />
              <vxe-column key="productName" title="物料名称" align="center" field="productName" />
              <vxe-column key="productSpe" title="物料描述" align="center" field="productSpe" />
              <vxe-column key="productSpe" title="品牌" align="center" field="externalBrand" />
              <vxe-column key="unitName" title="单位" align="center" field="unitName" />
              <!--<vxe-column key="purchasePrice" title="参考成本" align="center" field="purchasePrice" />-->
              <!--<vxe-column key="foreignPrice" title="统一报价(参考)" align="center" field="foreignPrice" />-->
              <!--<vxe-column key="stockingPeriod" title="备货期(天)" align="center" field="stockingPeriod" />-->
              <!-- <vxe-column key="activeFlag" title="激活标识" align="center">
                <template #default="scope">
                  <dict-tag :options="active_flag" :value="scope.row.activeFlag"></dict-tag>
                </template>
              </vxe-column>-->
            </vxe-table>

            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :total="total"
              @pagination="pageList"
            />
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listWmsBaseProduct } from '@/api/wms/wmsBaseProduct';
import { WmsBaseProductQuery, WmsBaseProductVO } from '@/api/wms/wmsBaseProduct/types';
import { VxeTableInstance } from 'vxe-table';
import useDialog from '@/hooks/useDialog';
import { getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs, watch, computed } from 'vue';

interface PropType {
  modelValue?: WmsBaseProductVO[] | WmsBaseProductVO | undefined;
  multiple?: boolean;
  data?: string | number | (string | number)[] | undefined;
}

const prop = withDefaults(defineProps<PropType>(), {
  multiple: true,
  modelValue: undefined,
  data: undefined
});
const emit = defineEmits(['update:modelValue', 'confirmCallBack']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { active_flag } = toRefs<any>(proxy?.useDict('active_flag'));

const wmsBaseProductList = ref<WmsBaseProductVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const selectProductList = ref<WmsBaseProductVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<VxeTableInstance<WmsBaseProductVO>>();

const productDialog = useDialog({
  title: '物料选择'
});

const queryParams = ref<WmsBaseProductQuery>({
  pageNum: 1,
  pageSize: 500,
  productCode: undefined,
  productName: undefined,
  activeFlag: undefined,
  params: {}
});

const defaultSelectProductIds = computed(() => computedIds(prop.data));

const confirm = () => {
  emit('update:modelValue', selectProductList.value);
  emit('confirmCallBack', selectProductList.value);
  productDialog.closeDialog();
};

const computedIds = (data) => {
  if (data === '' || data === null || data === undefined) {
    return [];
  }
  if (data instanceof Array) {
    return data.map((item) => String(item));
  } else if (typeof data === 'string') {
    return data.split(',');
  } else if (typeof data === 'number') {
    return [String(data)];
  } else {
    console.warn('<ProductSelect> 未支持的数据类型');
    return [];
  }
};

/** 查询物料信息列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listWmsBaseProduct(queryParams.value);
    wmsBaseProductList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('查询物料列表失败:', error);
  } finally {
    loading.value = false;
  }
};

const pageList = async () => {
  await getList();
  const products = wmsBaseProductList.value.filter((item) => {
    return selectProductList.value.some((product) => product.productId === item.productId);
  });
  await tableRef.value?.setCheckboxRow(products, true);
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.productCode = undefined;
  queryParams.value.productName = undefined;
  queryParams.value.activeFlag = undefined;
  handleQuery();
};

const handleCheckboxChange = (checked) => {
  if (!prop.multiple && checked.checked) {
    tableRef.value?.setCheckboxRow(selectProductList.value, false);
    selectProductList.value = [];
  }
  const row = checked.row;
  if (checked.checked) {
    selectProductList.value.push(row);
  } else {
    selectProductList.value = selectProductList.value.filter((item) => {
      return item.productId !== row.productId;
    });
  }
};

const handleCheckboxAll = (checked) => {
  const rows = wmsBaseProductList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectProductList.value.some((item) => item.productId === row.productId)) {
        selectProductList.value.push(row);
      }
    });
  } else {
    selectProductList.value = selectProductList.value.filter((item) => {
      return !rows.some((row) => row.productId === item.productId);
    });
  }
};

const handleCloseTag = (product: WmsBaseProductVO) => {
  const productId = product.productId;
  const index = selectProductList.value.findIndex((item) => item.productId === productId);
  if (index > -1) {
    const row = selectProductList.value[index];
    tableRef.value?.setCheckboxRow(row, false);
    selectProductList.value.splice(index, 1);
  }
};

const initSelectProduct = async () => {
  if (defaultSelectProductIds.value.length > 0) {
    const products = wmsBaseProductList.value.filter((item) => {
      return defaultSelectProductIds.value.includes(String(item.productId));
    });
    selectProductList.value = products;
    await nextTick(() => {
      tableRef.value?.setCheckboxRow(products, true);
    });
  }
};

const close = () => {
  productDialog.closeDialog();
};

watch(
  () => productDialog.visible.value,
  async (newValue: boolean) => {
    if (newValue) {
      await getList();
      await initSelectProduct();
    } else {
      tableRef.value?.clearCheckboxReserve();
      tableRef.value?.clearCheckboxRow();
      resetQuery();
      selectProductList.value = [];
    }
  }
);

defineExpose({
  open: productDialog.openDialog,
  close: productDialog.closeDialog
});
</script>
