<template>
    <el-dialog v-model="props.modelValue" title="选择配送区域" width="900px" @closed="closeDialog" @open="openDialog">
        <div id="app">
            <TreeTransfer ref="treeTransferRef" nodeKey="id" :fromData="transferData" :propToData="props.data.deliveryRuleRegion"
                :defaultProps="transferProps" :leftTit="'地区选择：'" :rightTit="'已选择：'" :searchPlaceholder="'地区名称'"
                @checkVal="checkVal">
            </TreeTransfer>
        </div>

        <template #footer>
            <div key="dialog-footer">
                <el-button type="primary" @click="handleSave()">添加</el-button>
                <el-button @click="closeDialog()">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
<script setup>
import { getSecondRegionTreeList } from '@/api/business/Custom/Regions/region.js'
import TreeTransfer from '@/components/TreeTransfer/index'
import { ElMessage } from 'element-plus'

const emits = defineEmits(["update:modelValue"]);
const props = defineProps({
    modelValue: Boolean,
    data: Object,
    done: Function,
});

const formData = ref({
    ...props.data
});

const transferData = ref([])
const transferValue = ref([])
const transferProps = ref([])

watch(props, (v) => {
    // console.log(v.data,'数据');
    transferValue.vale = v.data.deliveryRuleRegion.length;
    formData.value = v.data

    // console.log(transferValue.vale,'回传值');
});


// 打开弹窗时
function openDialog() {
    getSecondRegionTreeList().then((res) => {
        if (res.code == 200) {
            transferData.value = res.data
        }
    })
}

// -业务参数

// 可配送区域(文字展示)
let deliveryRuleRegionText = ref("");
// 可配送区域(城市id集)
let deliveryRuleRegion = ref("");



// -业务方法
function checkVal(e) {
    // console.log(e, '弹窗中的数据');

    // 将 id 和 parentName 提取出来并以逗号分隔连接起来
    deliveryRuleRegionText.value = e.reduce((text, item) => {

        if (text && text.includes(item.parentName)) {
            return text;
        }

        if (text) {
            text += ",";
        }
        return text + item.parentName;
    }, "");

    deliveryRuleRegion.value =  e.map(item => item);
    // console.log(deliveryRuleRegionText.value, "可配送区域(文字展示)");
    // console.log(deliveryRuleRegion.value, "可配送区域(城市id集)");
}


// 提交
function handleSave() {
    if (deliveryRuleRegionText.value !== "") {
        formData.value.deliveryRuleRegionText = deliveryRuleRegionText.value
        formData.value.deliveryRuleRegion = deliveryRuleRegion.value
        if (formData.value.deliveryRuleRegionText != null) {
            closeDialog();
            props.done()
        }
    } else {
        ElMessage.error("请选择配送区域")
        return;
    }
}


const closeDialog = () => {
    deliveryRuleRegionText.value = ""
    deliveryRuleRegion.value = []
    emits("update:modelValue", false);
};

</script>