<template>
    <div>
        <!-- 输入框 -->
        <template v-if="item.type === 'input'">
            <el-input
                :placeholder="item.placeholder"
                :maxlength="item.maxlength || 255"
                v-model.trim="_searchParam[`${item.prop}`]"
                style="width: 224px"
                @input="handleInput(item)"
                @keyup.enter="search"
                clearable
                @clear="handleEmitClear(item)"
            />
        </template>
        <template v-if="item.type === 'inputBtn'">
            <el-input
                :placeholder="item.placeholder"
                :maxlength="item.maxlength || 255"
                v-model.trim="_searchParam[`${item.prop}`]"
                style="width: 224px"
                @input="handleInput(item)"
                @keyup.enter="search"
                clearable
                @clear="handleEmitClear(item)"
            >
                <template #append>
                    <div @click="handleClick(item)" style="cursor: pointer">...</div>
                </template>
            </el-input>
        </template>
        <!-- 下拉框 -->
        <template v-if="item.type === 'select'">
            <el-select
                v-model="_searchParam[`${item.prop}`]"
                :placeholder="item.placeholder"
                clearable
                ref="selectRef"
                style="width: 224px"
            >
                <el-option v-for="option in item.options" :label="option.label" :value="option.value" :key="option.label" />
            </el-select>
        </template>
        <!-- 开始-结束-日期选择器 -->
        <template v-if="item.type === 'daterange'">
            <el-date-picker
                v-model="_searchParam[`${item.prop}`]"
                :type="item.type"
                :start-placeholder="item.startPlaceholder"
                :end-placeholder="item.endPlaceholder"
                :defaultTime="item.value"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 205px"
                @change="handlePicker(item)"
            />
        </template>
        <!-- 远程搜索 -->
        <template v-if="item.type === 'selectRemote'">
            <el-select
                v-model="_searchParam[`${item.prop}`]"
                :placeholder="item.placeholder"
                clearable
                remote
                filterable
                @clear="handleClear(item)"
                :loading="loading"
                class="m-2 select"
                remote-show-suffix
                :remote-method="
                              (query:any) => {
                                remoteMethod(
                                  query,
                                  item
                                );
                              }
                            "
                :disabled="item.disabled"
                style="width: 224px"
            >
                <el-option :label="option.name" :value="option.code" v-for="option in item.options" :key="option.code" />
            </el-select>
            <!--item.prop -->
        </template>
        <!-- 远程搜索 -->
        <template v-if="item.type === 'selectRemote1'">
            <el-select
                v-model="_searchParam[`${item.prop}`]"
                :placeholder="item.placeholder"
                clearable
                remote
                filterable
                @clear="handleClear(item)"
                class="m-2 select"
                :loading="loading1"
                no-data-text=""
                remote-show-suffix
                :remote-method="
                              (query:any) => {
                                remoteMethod1(
                                  query,
                                  item
                                );
                              }
                            "
                :disabled="item.disabled"
                style="width: 224px"
            >
                <el-option
                    :label="option.specifications"
                    :value="option.materialNumber"
                    v-for="option in item.options"
                    :key="option.materialNumber"
                />
            </el-select>
            <!--item.prop -->
        </template>
        <!-- 双 -->
        <template v-if="item.type === 'inputs'">
            <el-input
                v-model.trim="_searchParam[`${item.startProp}`]"
                :placeholder="item.startPlaceholder"
                :disabled="item.disabled"
                maxlength="255"
                style="width: 105px !important"
                @input="handleInput(item)"
            >
            </el-input>
            <span style="margin: 0 3px">-</span>
            <el-input
                v-model.trim="_searchParam[`${item.endProp}`]"
                :placeholder="item.endPlaceholder"
                :disabled="item.disabled"
                maxlength="255"
                style="width: 106px !important"
                @input="handleInput(item)"
            />
        </template>
        <template v-if="item.type === 'selectInputs'">
            <div></div>
            <el-select
                v-model="selectInputValue"
                placeholder="Select"
                style="width: 102px; height: 30px; margin-right: 6px"
                class="selectInputs-box"
                @change="handleChange(item)"
            >
                <el-option
                    v-for="optionsItem in options"
                    :key="optionsItem.value"
                    :label="optionsItem.label"
                    :value="optionsItem.value"
                />
            </el-select>

            <el-input
                v-model.trim="_searchParam[`${item.startProp}`]"
                :placeholder="item.startPlaceholder"
                :disabled="item.disabled"
                maxlength="255"
                style="width: 105px !important"
                @input="handleInput(item)"
            >
            </el-input>
            <span style="margin: 0 3px">-</span>
            <el-input
                v-model.trim="_searchParam[`${item.endProp}`]"
                :placeholder="item.endPlaceholder"
                :disabled="item.disabled"
                maxlength="255"
                style="width: 106px !important"
                @input="handleInput(item)"
            />
        </template>
        <el-dialog v-model="dialogTableVisible" title="批量查询" width="650">
            <el-input
                v-model="textarea"
                maxlength="5000"
                placeholder="粘贴内容到这里,每行作为一条数据"
                show-word-limit
                :rows="20"
                type="textarea"
            />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleQX()">取消</el-button>
                    <el-button @click="handleQK()">清空</el-button>
                    <el-button type="primary" @click="handleQR"> 确认 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="SearchFormItem">
import { verificationInput } from "./utils/verificationInput";
import { cloneDeep } from "lodash-es";
// import { debounce, cloneDeep } from 'lodash-es';
import $Bus from "@/utils/mittBus";
import { getSupplierApi } from "@/api/modules/global";
import { getMaterialListApi } from "@/api/modules/boxMark";
import { useUserStore } from "@/stores/modules/user";
import { ref } from "vue";
const $router = useRouter();
const routeName: any = ref($router.currentRoute.value.name);
const userStore: any = useUserStore();
let dialogTableVisible = ref(false);
let inputBtnType = ref<any>(null);
let textarea = ref();
interface SearchFormItem {
    item: { [key: string]: any };
    searchParam: { [key: string]: any };
    search: (params: any) => void; // 搜索方法
    handleEmitClear?: (item: any) => void;
}
let selectInputValue = ref(1);
const options = [
    {
        value: 1,
        label: "序号"
    },
    {
        value: 2,
        label: "数字序列号"
    }
];

const props = defineProps<SearchFormItem>();
const _searchParam = computed(() => props.searchParam);

if (routeName.value === "boxCode" || routeName.value === "barCode" || routeName.value === "antiCode") {
    _searchParam.value.createUser = userStore.userInfo.nickname;
}
if (routeName.value === "boxMarkIndex") {
    _searchParam.value.creator = userStore.userInfo.nickname;
}
let loading = ref(false);
let loading1 = ref(false);
//序列号按钮
const handleClick = (item: any) => {
    inputBtnType.value = item.prop;
    dialogTableVisible.value = true; //serialNumbers
    textarea.value = "";

    if (_searchParam.value[inputBtnType.value] && _searchParam.value[inputBtnType.value].length) {
        let serialNumbersClone = cloneDeep(_searchParam.value[inputBtnType.value]);
        textarea.value = serialNumbersClone.join("\n");
    }
};
//清空
const handleQK = () => {
    textarea.value = "";
    console.log(inputBtnType.value);
    _searchParam.value[inputBtnType.value] = "";
};
const handleQX = () => {
    dialogTableVisible.value = false;
    textarea.value = "";
};
//确认
const handleQR = () => {
    if (textarea.value) {
        const result = textarea.value?.split("\n")?.join(",");
        const newArr = result.split(",");
        //去除数组中的空数据
        const resultArray = newArr.filter((item: any) => item !== null && item !== undefined && item !== "");
        console.log(inputBtnType.value, "=inputBtnType.value=");

        if (_searchParam.value[inputBtnType.value]) {
            // ...resultArray ..._searchParam.value[inputBtnType.value],
            _searchParam.value[inputBtnType.value] = [...resultArray];
            _searchParam.value[inputBtnType.value] = [...new Set(_searchParam.value[inputBtnType.value])];
        } else {
            _searchParam.value[inputBtnType.value] = resultArray;
        }
    }

    dialogTableVisible.value = false;
};
//日期选择后重选赋值
const handlePicker = (item: any) => {
    const { prop } = item;
    if (prop === "Time" || prop === "Time1") {
        if (Array.isArray(_searchParam.value[prop]) && _searchParam.value[prop].length > 0) {
            _searchParam.value[item.startDate] = _searchParam.value[prop][0];
            _searchParam.value[item.endDate] = _searchParam.value[prop][1];
        } else {
            _searchParam.value[item.startDate] = "";
            _searchParam.value[item.endDate] = "";
        }
    }
};
//远程搜索(供应商)
const remoteMethod = async (query: any, item: any) => {
    loading.value = true;
    if (!query) {
        loading.value = false;
        return;
    }

    let valClone = query.replace(/^\s*|\s*$/g, "");
    if (!valClone.length) {
        loading.value = false;
        return;
    }
    const result = await getSupplierApi({ name: valClone, orgCode: userStore.orgCode });
    if (result.status === 200) {
        const { data } = result;
        item.options = data;
    }
    loading.value = false;
};
//远程搜索(物料)
const remoteMethod1 = async (query: any, item: any) => {
    loading1.value = true;
    if (!query) {
        loading1.value = false;
        return;
    }
    let valClone = query.replace(/^\s*|\s*$/g, "");
    if (!valClone.length) {
        loading1.value = false;
        return;
    }
    const result = await getMaterialListApi(valClone);
    if (result.status === 200) {
        const { data } = result;
        item.options = data;
    }
    loading1.value = false;
};
const handleClear = (item: any) => {
    item.options = [];
};

//input输入监听
const handleInput = (item: any) => {
    if (routeName.value === "barCode" && item.prop === "createUser") {
        $Bus.emit("setBarCodeInputCreateUser", {
            createUser: _searchParam.value["createUser"]
        });
    }
    if (routeName.value === "boxCode" && item.prop === "createUser") {
        $Bus.emit("setBoxCodeInputCreateUser", {
            createUser: _searchParam.value["createUser"]
        });
    }
    if (routeName.value === "antiCode" && item.prop === "createUser") {
        $Bus.emit("setAntiCodeInputCreateUser", {
            createUser: _searchParam.value["createUser"]
        });
    }

    if (routeName.value === "boxMarkIndex" && item.prop === "creator") {
        $Bus.emit("setBoxMarkIndexInputCreateUser", {
            creator: _searchParam.value["creator"]
        });
    }
    //验证
    verificationInput(item, _searchParam, selectInputValue.value);
};
const handleChange = (item: any) => {
    _searchParam.value[item.endProp] = "";
    _searchParam.value[item.startProp] = "";
    _searchParam.value["serialNumberBegin"] = "";
    _searchParam.value["numberCodeBegin"] = "";
    _searchParam.value["serialNumberEnd"] = "";
    _searchParam.value["numberCodeEnd"] = "";
};

const handleEmitClear = (item: any) => {
    console.log(item);

    if (routeName.value === "barCode") {
        $Bus.emit("clearBarCodeCreateUser");
    }
    if (routeName.value === "boxCode") {
        $Bus.emit("clearBoxCodeCreateUser");
    }
    if (routeName.value === "boxMarkIndex") {
        $Bus.emit("clearBoxMarkIndexCreator");
    }
    if (routeName.value === "antiCode") {
        $Bus.emit("clearBoxMarkIndexCreator");
    }
};
//
// $Bus.on("setBarCodeFormCreateUser", () => {
//     if (routeName.value === "boxCode" || routeName.value === "barCode" || routeName.value === "antiCode") {
//         _searchParam.value.createUser = userStore.userInfo.nickname;
//         console.log(_searchParam.value, "= _searchParam.value.createUser=");
//     }
//     if (routeName.value === "boxMarkIndex") {
//         _searchParam.value.creator = userStore.userInfo.nickname;
//     }
// });
</script>
<style lang="scss" scope>
@import "../index.scss";
</style>
