<template>
  <div>
    <el-dialog v-model="materialDialog.visible.value" :title="materialDialog.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="SAP物料编码" prop="materialCode">
                    <el-input v-model="queryParams.materialCode" placeholder="请输入SAP物料编码" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="SAP物料名称" prop="materialName">
                    <el-input v-model="queryParams.materialName" placeholder="请输入SAP物料名称" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="物料品牌" prop="materialBrand">
                    <el-input v-model="queryParams.materialBrand" placeholder="请输入物料品牌" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="物料型号" prop="materialModel">
                    <el-input v-model="queryParams.materialModel" placeholder="请输入物料型号" clearable @keyup.enter="handleQuery" />
                  </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="material in selectMaterialList" :key="material.materialId" closable style="margin: 2px" @close="handleCloseTag(material)">
                {{ material.materialName }}
              </el-tag>
            </template>

            <vxe-table
              ref="tableRef"
              height="400px"
              border
              show-overflow
              :data="materialInfoList"
              :loading="loading"
              :row-config="{ keyField: 'materialId', 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="materialId" title="物料ID" align="center" field="materialId" />-->
              <vxe-column key="materialCode" title="SAP物料编码" align="center" field="materialCode" width="120" />
              <vxe-column key="materialName" title="SAP物料名称" align="center" field="materialName" width="320" />
              <vxe-column key="materialBrand" title="物料品牌" align="center" field="materialBrand" width="120" />
              <vxe-column key="materialModel" title="物料型号" align="center" field="materialModel" width="120" />
              <vxe-column key="unitName" title="物料单位" align="center" field="unitName" />
              <vxe-column key="materialParameter" title="物料参数" align="center" field="materialParameter" />
<!--              <vxe-column key="purchasePrice" title="采购单价(元)" align="center" field="purchasePrice" width="120" />-->
<!--              <vxe-column key="foreignPrice" title="售前对外单价(元)" align="center" field="foreignPrice" width="140" />-->
<!--              <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 { listMaterialInfo } from '@/api/oa/base/materialInfo';
import { MaterialInfoVO, MaterialInfoQuery } from '@/api/oa/base/materialInfo/types';
import { VxeTableInstance } from 'vxe-table';
import useDialog from '@/hooks/useDialog';

interface PropType {
  modelValue?: MaterialInfoVO[] | MaterialInfoVO | 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 materialInfoList = ref<MaterialInfoVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const selectMaterialList = ref<MaterialInfoVO[]>([]);

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

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

const queryParams = ref<MaterialInfoQuery>({
  pageNum: 1,
  pageSize: 10,
  materialCode: undefined,
  materialName: undefined,
  materialBrand: undefined,
  materialModel: undefined,
  unitId: undefined,
  materialParameter: undefined,
  purchasePrice: undefined,
  foreignPrice: undefined,
  stockingPeriod: undefined,
  activeFlag: undefined,
  params: {}
});

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

const confirm = () => {
  emit('update:modelValue', selectMaterialList.value);
  emit('confirmCallBack', selectMaterialList.value);
  materialDialog.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('<MaterialSelect> The data type of data should be array or string or number, but I received other');
    return [];
  }
};

/** 查询物料信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMaterialInfo(queryParams.value);
  loading.value = false;
  materialInfoList.value = res.rows;
  total.value = res.total;
};

const pageList = async () => {
  await getList();
  const materials = materialInfoList.value.filter((item) => {
    return selectMaterialList.value.some((material) => material.materialId === item.materialId);
  });
  await tableRef.value.setCheckboxRow(materials, true);
};

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

/** 重置按钮操作 */
const resetQuery = (refresh = true) => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  refresh && handleQuery();
};

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

const handleCheckboxAll = (checked) => {
  const rows = materialInfoList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectMaterialList.value.some((item) => item.materialId === row.materialId)) {
        selectMaterialList.value.push(row);
      }
    });
  } else {
    selectMaterialList.value = selectMaterialList.value.filter((item) => {
      return !rows.some((row) => row.materialId === item.materialId);
    });
  }
};

const handleCloseTag = (material: MaterialInfoVO) => {
  const materialId = material.materialId;
  // 使用splice删除物料
  const index = selectMaterialList.value.findIndex((item) => item.materialId === materialId);
  const rows = selectMaterialList.value[index];
  tableRef.value?.setCheckboxRow(rows, false);
  selectMaterialList.value.splice(index, 1);
};

const initSelectMaterial = async () => {
  if (defaultSelectMaterialIds.value.length > 0) {
    // 从当前列表中筛选已选择的物料
    const materials = materialInfoList.value.filter((item) => {
      return defaultSelectMaterialIds.value.includes(String(item.materialId));
    });
    selectMaterialList.value = materials;
    await nextTick(() => {
      tableRef.value.setCheckboxRow(materials, true);
    });
  }
};

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

watch(
  () => materialDialog.visible.value,
  async (newValue: boolean) => {
    if (newValue) {
      await getList(); // 初始化列表数据
      await initSelectMaterial();
    } else {
      tableRef.value.clearCheckboxReserve();
      tableRef.value.clearCheckboxRow();
      resetQuery(false);
      selectMaterialList.value = [];
    }
  }
);

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