<template>
    <view v-if="!isModify" class="edited-text" @click="showEditor">
        <view v-if="props.componentsType === ComponentsType.TEXTAREA" style="display: inline-flex;">
            <view v-html="visibleName"></view><uni-icons :size="16" color="#bbb" type="right"
                style=" margin-right: -5px;color:#bbb;align-items: center;display: flex;"></uni-icons>
        </view>
        <view v-else style="display: inline-flex;">
            <text>{{ visibleName }} {{ props.inputSuffix }}</text>
            <uni-icons :size="16" color="#bbb" type="right"
                style=" margin-right: -5px;color:#bbb;align-items: center;display: flex;"></uni-icons></view>
    </view>
    <view v-else>
        <view v-if="[ComponentsType.STRINGINPUT, ComponentsType.TEXTAREA].includes(componentsType)">
            <uni-easyinput v-model="editingValue" :placeholder="placeholder" :type="componentsType"
                suffixIcon="checkbox" :focus="true" :autoHeight="true" @iconClick="confirmData" @blur="confirmData" />
        </view>
        <view v-if="[ComponentsType.NUMBERINPUT, ComponentsType.DIGIT].includes(componentsType)">
            <view class="uni-easyinput">
                <view class="uni-easyinput__content is-input-border" :style="{
                    borderColor: is_foucs ? '#2979ff' : '',
                    background: is_foucs ? '#fff' : ''
                }">
                    <input class="uni-easyinput__content-input" v-model="editingValue"
                        placeholder-class="uni-easyinput__placeholder-class" :focus="is_foucs" :type="componentsType"
                        :placeholder="placeholder" @focus="is_foucs = true" @blur="confirmData">
                    <uni-icons class="content-clear-icon" type="checkbox" color="#c0c4cc" @click="confirmData"
                        size="22"></uni-icons>
                </view>
            </view>

        </view>
        <view v-if="[ComponentsType.DATEPICKER].includes(componentsType)">
            <uni-datetime-picker type="date" v-model="editingValue" :focus="true" @maskClick="confirmData"
                @change="confirmData" ref="datepicker" :clear-icon="!notAllowNull" />
        </view>
        <!-- <view v-if="[ComponentsType.CASCADER, ComponentsType.SELECT].includes(componentsType)"> -->

        <!-- <next-tree :ifSearch="true" :showAuxiliaryLine="showAuxiliaryLine" :border="true" labelKey="name"
                ref="treeSelectRef" :checkStrictly="true" :selectParent="selectParent"
                :funcMode="multiple ? 'checkbox' : 'radio'" :treeData="options" @confirm="confirmTreeSelect"
                @cancel="cancelTreeSelect"></next-tree> -->
        <!-- </view> -->

    </view>
    <view v-if="options">
        <next-tree :ifSearch="true" :showAuxiliaryLine="showAuxiliaryLine" :border="true" labelKey="name"
            :allowClear='!notAllowNull' ref="treeSelectRef" :checkStrictly="true" :selectParent="selectParent"
            :funcMode="multiple ? 'checkbox' : 'radio'" :treeData="options" @confirm="confirmTreeSelect"
            @cancel="cancelTreeSelect"></next-tree>
    </view>
</template>
<script setup lang="ts">
import { ComponentsType } from '@/enums/api';

import nextTree from '@/components/next-tree/next-tree.vue'
// import { invoke, until, useCounter } from '@vueuse/core'

interface DataItem {
    id: string | number
    name: string
    children?: DataItem[]
}

const props = defineProps<{
    modelValue?: any
    oldValue?: any
    disabled?: boolean
    placeholder?: string
    componentsType: ComponentsType
    isInputNumber?: boolean
    inputSuffix?: string
    options?: DataItem[]
    multiple?: boolean
    showNumberButton?: boolean
    unCheckStrictly?: boolean
    showAuxiliaryLine?: boolean
    dateType?: string
    notAllowNull?: boolean
    selectParent?: boolean
}>()

const test = ref(0)
const datepicker = ref()
const treeSelectRef = ref()
const emits = defineEmits(['update:modelValue', 'modify'])
const isModify = ref(false)
const is_foucs = ref(true)



const editingValue = ref(
    props.componentsType === ComponentsType.TEXTAREA && props.modelValue
        ? props.modelValue.replace(/<br\/>/g, '\n')
        : props.modelValue
)


function checkedTreeData(treeData: any, selectIds?: any) {
    treeData.map((item: any) => {
        if (selectIds.indexOf(item.id) !== -1) {
            item.checked = true
        } else {
            item.checked = false
        }
        if (item.children && item.children.length) {
            checkedTreeData(item.children, selectIds)
        }
    })
}


const showEditor = async () => {
    isModify.value = true
    if ([ComponentsType.CASCADER, ComponentsType.SELECT].includes(props.componentsType)) {
        nextTick(() => {
            checkedTreeData(props.options, props.multiple ? props.modelValue : [props.modelValue])
            unref(treeSelectRef).showTree = true
        })
    }
}
/**
 * 根据id查找name值，递归则获取路径拼接name
 * @param nodes
 * @param id
 * @param path
 */
function findPathById(
    nodes: DataItem[],
    id: string,
    path: string[] = []
): string | null {
    const result = nodes
        .map(node => {
            if (node.id === id) {
                return [...path, node.name].join(' / ')
            }
            if (node.children) {
                return findPathById(node.children, id, [...path, node.name])
            }
            return null
        })
        .find(p => p !== null)

    return result || null
}

const visibleName = computed(() => {
    if (
        props.componentsType === ComponentsType.STRINGINPUT ||
        props.componentsType === ComponentsType.NUMBERINPUT
    ) {
        return props.modelValue
    }

    if (
        props.componentsType === ComponentsType.SELECT ||
        props.componentsType === ComponentsType.CASCADER
    ) {
        const ids = editingValue.value
        if (props.multiple) {
            const arrName: string[] = []
            ids.map((item: string | number) => {
                const isFind = props.options?.find(p => p.id === item)
                if (isFind) {
                    arrName.push(isFind.name)
                }
                return item
            })
            return arrName.join(',')
        }
        return findPathById(props.options || [], ids)
    }
    return props.modelValue
})

const confirmTreeSelect = (list: any) => {
    if (list.length > 0) {
        if (props.multiple) {
            let ids: any = []
            list.map((item: { id: string | number, name: string }) => {
                ids.push(item.id)
                return item

            })
            editingValue.value = ids
        } else {
            editingValue.value = list[0].id
        }
        const v = editingValue.value
        emits('update:modelValue', v)
        emits('modify', { oldValue: props.oldValue })
    } else {
        if (props.notAllowNull) {
            uni.showToast(({
                icon: 'error',
                title: '不允许为空'
            }))
            return
        }
        const v = editingValue.value
        emits('update:modelValue', null)
        emits('modify', { oldValue: props.oldValue })
    }

    isModify.value = false
}

watch(
    () => props.modelValue,
    () => {
        const v =
            props.componentsType === ComponentsType.TEXTAREA
                ? props.modelValue.replace(/<br\/>/g, '\n')
                : props.modelValue
        editingValue.value = v
    }
)

watch(
    () => datepicker.value,
    () => {
        datepicker.value?.show()
    }
)

/**
 * 确认修改
 */
const confirmData = () => {
    is_foucs.value = false
    const v = editingValue.value
    if (props.notAllowNull && v === '') {
        uni.showToast(({
            icon: 'error',
            title: '不允许为空'
        }))
        return;
    }
    if (props.modelValue === v) {
        isModify.value = false
        return
    }
    const f_value =
        (props.componentsType === ComponentsType.TEXTAREA
            ? v.replace(/\n/g, '<br/>')
            : v)
    emits('update:modelValue', f_value)
    emits('modify', { oldValue: props.oldValue })
    isModify.value = false
}


const cancelTreeSelect = () => {
    // const v = editingValue.value
    // emits('update:modelValue', v)
    // emits('modify', { oldValue: props.oldValue })
    checkedTreeData(unref(props.options), [])
    isModify.value = false
}
</script>
<script lang="ts">
export default {
  options: {
    styleIsolation: 'isolated', //解除样式隔离
  }

}
</script>
<style scoped lang="scss">
.edited-text {
    color: #5d5959;
    font-size: 13px;
    width: 100%;
    height: 100%;
    min-width: 250px;
    text-overflow: ellipsis;
    text-align: right;
    text-wrap: wrap;
    overflow-wrap: anywhere;
    white-space-collapse: collapse;
}

.uni-easyinput {
    /* #ifndef APP-NVUE */
    width: 100%;
    /* #endif */
    flex: 1;
    position: relative;
    text-align: left;
    color: #333;
    font-size: 14px;
}

.uni-easyinput__content {
    flex: 1;
    /* #ifndef APP-NVUE */
    width: 100%;
    display: flex;
    box-sizing: border-box;
    // min-height: 36px;
    /* #endif */
    flex-direction: row;
    align-items: center;
    // 处理border动画刚开始显示黑色的问题
    border-color: #fff;
    transition-property: border-color;
    transition-duration: 0.3s;
}

.is-input-border {
    display: flex;
    box-sizing: border-box;
    flex-direction: row;
    align-items: center;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
}

.uni-easyinput__content-input {
    /* #ifndef APP-NVUE */
    width: auto;
    /* #endif */
    position: relative;
    overflow: hidden;
    flex: 1;
    line-height: 1;
    font-size: 14px;
    padding-left: 10px;
    height: 35px;
    // min-height: 36px;

    /*ifdef H5*/
    & ::-ms-reveal {
        display: none;
    }

    & ::-ms-clear {
        display: none;
    }

    & ::-o-clear {
        display: none;
    }

    /*endif*/
}

.content-clear-icon {
    padding: 0 5px;
}

:deep(.uni-easyinput__placeholder-class) {
    color: #999;
    font-size: 12px;
    // font-weight: 200;
}
</style>