<template>
    <vxe-modal v-model="dialogVisible" :title="title" show-zoom resize show-footer destroy-on-close transfer @hide="close" :width="width">
        <template #default>
            <div style="height: 80vh" class="d-flex flex-cln">
                <div class="pd-16 border-bottom d-flex j-sb pb-4">
                    <div>
                        <searchTabs v-model="tabActive" :list="[{ label: '按检测项目', value: '1' }, { label: '按执行标准', value: '2' }]" :is-num="false"></searchTabs>
                    </div>
                    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="auto">
                        <el-form-item label="检测项名称：" prop="name">
                            <el-input v-model="queryParams.name" placeholder="请输入检测项名称关键字" clearable style="width: 180px" @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>
                </div>
                <div class="flex1 ov-hd d-flex content-border">
                    <div class="tree-wrap">
                        <div v-show="tabActive === '1'">
                            <el-tree ref="treeItemsRef" class="base-tree-tabs" auto-expand-parent default-expand-all node-key="id" :data="itemsData" :props="{ label: 'name' }" highlight-current @node-click="itemsClick">
                                <template #default="{ node, data }">
                                    <span>
                                        {{ node.label }}
                                        <template v-if="!data?.children">（{{ data?.itemCount || '0' }}）</template>
                                    </span>
                                </template>
                            </el-tree>
                        </div>
                        <div v-show="tabActive === '2'">
                            <el-tree ref="treeStandardsRef" class="base-tree-tabs" auto-expand-parent :data="standards" node-key="id" :props="{ label: 'name' }" highlight-current @node-click="standardsClick">
                                <template #default="{ node, data }">
                                    <span>
                                        {{ node.label }}
                                        <template v-if="!data?.children">（{{ data?.itemCount || '0' }}）</template>
                                    </span>
                                </template>
                            </el-tree>
                        </div>
                    </div>
                    <div class="flex1 ov-hd d-flex flex-cln">
                        <div class="flex1 ov-hd">
                            <vxe-table ref="tableLeftRef" :loading="loading" border :data="list" height="100%" :column-config="{ resizable: true }" :row-config="{keyField: 'id',isCurrent: true, isHover: true}" :checkbox-config="{ highlight: true, range: true, trigger: 'row', reserve: true }">
                                <vxe-column type="checkbox" width="60"></vxe-column>
                                <!-- 序号 -->
                                <vxe-column type="seq" width="60" title="序号" align="center" />
                                <vxe-column title="检测项目" align="center" field="name" min-width="100" :formatter="colNoData" />
                                <vxe-column title="单价（元、批次）" align="center" field="price" min-width="100" :formatter="colNoData" />
                            </vxe-table>
                        </div>
                    </div>
                    <div class="d-flex j-c a-c flex-cln pd-10">
                        <el-button type="primary" @click="transferRight">
                            <el-icon>
                                <DArrowRight />
                            </el-icon>
                        </el-button>
                        <div class="pd-10"></div>
                        <el-button type="primary" @click="transferLeft">
                            <el-icon>
                                <DArrowLeft />
                            </el-icon>
                        </el-button>
                    </div>
                    <div class="flex1 ov-hd d-flex flex-cln">
                        <div class="flex1 ov-hd">
                            <vxe-table ref="tableRightRef" :loading="loading" border :data="targetList" height="100%" :column-config="{ resizable: true }" :row-config="{ keyField: 'id', isCurrent: true, isHover: true }" :checkbox-config="{ highlight: true, range: true, trigger: 'row', reserve: true }">
                                <vxe-column type="checkbox" width="60"></vxe-column>
                                <vxe-column type="seq" width="60" title="序号" align="center" />
                                <vxe-column title="检测项目" align="center" field="name" min-width="100" :formatter="colNoData" />
                                <vxe-column title="单价（元、批次）" align="center" field="price" min-width="100" :formatter="colNoData" />
                            </vxe-table>
                        </div>
                    </div>
                </div>
            </div>
        </template>
        <template #footer>
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="submitForm">确认添加</el-button>
        </template>
    </vxe-modal>
</template>

<script setup name="transferItems" lang="ts">
import { itemsList, itemsListByTree, itemsStandardList } from '@/api/cdt/items';
import { colNoData } from '@/utils/noData';
import { propTypes } from '@/utils/propTypes';
import { searchTabs } from '@/views/models';
import { FormInstance } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dialogVisible = ref(false);
const emit = defineEmits(['update:show', 'close', 'change']);
const props = defineProps({
    show: propTypes.bool.def(false),
    title: propTypes.string.def('选择检测项目'),
    width: propTypes.string.def('80vw'),
    info: propTypes.any.def(null),
    items: propTypes.array.def([]) // 已选检测项目
});
const treeItemsRef = ref<any>();
const treeStandardsRef = ref<any>();
const tabActive = ref('1');
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 300,
    name: '',
    itemTypeId: '',
    packageId: ''
});
const loading = ref(false);
const total = ref(0);
const list = ref<any>([]);
const targetList = ref<any>([]);
const itemsData = ref<any>([]);
// 是否打开过刚才id
const mapIdsOpened = ref<any>({});
const getList = async () => {
    loading.value = true;
    const res = await itemsList(queryParams.value);
    if (!res || res.code !== 200) return;
    res.rows.forEach(element => {
        mapIdsOpened.value[element.id] = true;
    });
    list.value = res.rows
    total.value = res.total;
    loading.value = false;
    tableLeftRef.value?.setCheckboxRow(targetList.value, true);
};
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
const resetQuery = () => {
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        name: '',
        itemTypeId: '',
        packageId: ''
    };
    // 重置树高亮
    treeItemsRef.value?.setCurrentKey(null, true);
    treeStandardsRef.value?.setCurrentKey(null, true);
    handleQuery();
};
const getTabsTree = async () => {
    const res = await itemsListByTree();
    if (!res || res.code !== 200) return;
    itemsData.value = res.data;
};
const itemsClick = (data: any) => {
    if (!data.children) {
        queryParams.value.itemTypeId = data.id;
        queryParams.value.packageId = '';
    }
    handleQuery();
};
const standardsClick = (data: any) => {
    if (!data.children) {
        queryParams.value.packageId = data.id;
        queryParams.value.itemTypeId = '';
    }
    handleQuery();
};
// 查询执行标准列表
const standards = ref<any>([]);
const getStandardList = async () => {
    const res = await itemsStandardList({ pageNum: 1, pageSize: 10000 });
    if (!res || res.code !== 200) return;
    standards.value = res.rows;
};
const formRef = ref<FormInstance>();
const close = () => {
    emit('update:show', false);
    emit('close', false);
};
const submitForm = async () => {
    try {
        if (!targetList.value.length) {
            // 抛出错误
            return proxy.$modal.msgWarning('请选择检测项目');
        }
        emit('change', targetList.value);
        close();
    } catch (error) {
        proxy.$modal.msgWarning(error);
    }
};
const tableLeftRef = ref<any>();
const tableRightRef = ref<any>();
const transferRight = () => {
    // 去重
    const newsList = tableLeftRef.value?.getCheckboxReserveRecords(true).concat(tableLeftRef.value?.getCheckboxRecords());
    // 过滤没打开过的
    const noOpenList = targetList.value.filter((item: any) => !mapIdsOpened.value[item.id]);
    // 合并newsList和noOpenList
    targetList.value = newsList
};
const transferLeft = () => {
    targetList.value = targetList.value.filter((item: any) => !tableRightRef.value?.getCheckboxRecords().includes(item));
    tableLeftRef.value?.setCheckboxRow(tableRightRef.value?.getCheckboxRecords(), false);
    tableRightRef.value.setCheckboxRow(tableRightRef.value?.getCheckboxRecords(), false);
};

const checkRowKeys = ref<any>([]);
watch(
    () => props.show,
    (val) => {
        dialogVisible.value = val;
        if (val) {
            getTabsTree();
            getStandardList();
        }
    },
    { immediate: true }
);
watch(
    () => props.items,
    (val) => {
        console.log(val);
        if (val && val.length) {
            targetList.value = val;
        } else {
            targetList.value = [];
            checkRowKeys.value = [];
        }
    },
    { immediate: true }
);
</script>
<style lang="scss" scoped>
.tree-wrap {
    width: 310px;
    box-sizing: border-box;
    border-right: 1px solid #ebeef5;
    padding: 16px;
}

.content-border {
    border: 1px solid var(--border-color);
}
</style>
