<script setup>
import {ref,watch} from 'vue'
import draggable from 'vuedraggable'
import {
    apiMyChartClassifyList,
    apiMyChartClassifySort,
    apiMyChartClassifyDel,
    apiMyChartClassifyAdd,
    apiMyChartClassifyEdit
} from '@/api/myChart'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router=useRouter()
const emit=defineEmits(['change'])

let list=ref([])
async function getMyClassifyOpt(){
    const res=await apiMyChartClassifyList()
    if(res.code===200){
        list.value=res.data||[]
    }
}
getMyClassifyOpt()


// 排序结束
function onSortEnd(){
    // console.log('sort end');
    updateClassifySort()
}

// 更新排序
async function updateClassifySort(){
    const arr=list.value.map((item,index)=>{
        return {
            sort:index+1,
            classify_id:item.my_chart_classify_id
        }
    })
    const res=await apiMyChartClassifySort(arr)
    if(res.code===200){
        ElMessage.success('移动成功')
        emit('change')
    }else{
        ElMessage.warning(res.msg)
    }
}

// 删除
function handleDel(item){
    ElMessageBox({
        title:`操作提示`,
        message:`是否确认删除分类“${item.my_chart_classify_name}”`,
        center: true,
        dangerouslyUseHTMLString: true,
        confirmButtonText:'确定',
        confirmButtonClass:'self-elmessage-confirm-btn',
        showCancelButton:true,
        cancelButtonText:'取消',
        cancelButtonClass:'self-elmessage-cancel-btn'
    }).then(()=>{
        apiMyChartClassifyDel({classify_id:Number(item.my_chart_classify_id)}).then(res=>{
            if(res.code===200){
                ElMessage.success('删除成功')
                emit('change')
                getMyClassifyOpt()
            }else if(res.code===4001){
                ElMessageBox({
                    title:`操作提示`,
                    message:`删除失败，该分类下有图表`,
                    center: false,
                    dangerouslyUseHTMLString: true,
                    confirmButtonText:'知道了',
                    confirmButtonClass:'self-elmessage-confirm-btn',
                    showCancelButton:false,
                }) 
            }else{
                ElMessage.warning(res.msg)
            }
        })
    }).catch(()=>{
            
    })
}

//编辑
function handleEdit(item){
    inputText.value=item.my_chart_classify_name
    cid.value=item.my_chart_classify_id
    showAdd.value=true
}

//添加分类
let showAdd=ref(false)
let inputText=ref('')
let cid=ref(0)

watch(
    ()=>showAdd.value,
    (n)=>{
        if(!n){
            inputText.value=''
            cid.value=0
        }
    }
)

async function handleConfirmAdd(){
    if(!inputText.value){
        ElMessage.warning('请填写分类名称')
        return
    }
    let res=null
    if(cid.value){
        res=await apiMyChartClassifyEdit({
            classify_name:inputText.value,
            classify_id:cid.value
        })
    }else{
        res=await apiMyChartClassifyAdd({
            classify_name:inputText.value
        })
    }
    if(res.code===200){
        ElMessage.success(`${cid?'编辑':'新增'}成功`)
        emit('change')
        getMyClassifyOpt()
        showAdd.value=false
    }
}


function goSearch(item){
    router.push({
        path:'/mychart/search',
        query:{
            cid:item.my_chart_classify_id,
            cname:item.my_chart_classify_name
        }
    })
}

</script>

<template>
    <el-popover
        placement="bottom-start"
        :width="400"
        trigger="hover"
        popper-class="top-popper"
    >
        <template #reference>
            <img style="width:109px;cursor: pointer;" src="@/assets/myChart/btn-img.png" alt="">
        </template>
        <template #default>
            <div class="sort-classify-wrap">
                <draggable 
                    class="list"
                    v-model="list" 
                    item-key="my_chart_classify_id"
                    animation="300"
                    @end="onSortEnd"
                    :disabled="true"
                >
                    <template #item="{element}">
                        <div class="item" @click="goSearch(element)">
                            <span>{{element.my_chart_classify_name}}</span>
                            <img src="@/assets/myChart/edit-icon.png" v-if="element.my_chart_classify_id!==-1" @click.stop="handleEdit(element)" alt="">
                            <img src="@/assets/myChart/del-icon.png" v-if="element.my_chart_classify_id!==-1" alt="" @click.stop="handleDel(element)">
                            <!-- <img src="@/assets/myChart/drag-icon.png" alt=""> -->
                        </div>
                    </template>
                </draggable>
                <div class="add-btn" @click="showAdd=true">添加分类</div>
            </div>
        </template>
    </el-popover>
    
    <!-- 添加分类弹窗 -->
    <el-dialog
        v-model="showAdd"
        :title="cid?'编辑分类':'添加分类'"
        :width="450"
        draggable
        :close-on-click-modal="false"
        append-to-body
    >
        <div class="add-box">
            <input v-model="inputText" type="text" placeholder="请输入分类名称" maxlength="10">
            <p style="color:#999">注：字数控制在10个字以内</p>
            <div style="text-align:center;margin:40px 0 20px 0">
                <el-button round plain size="large" style="width:100px" @click="showAdd=false">取消</el-button>
                <el-button round size="large" type="primary" style="width:100px" @click="handleConfirmAdd">确定</el-button>
            </div>
        </div>
    </el-dialog>
</template>

<style>
.top-popper{
    padding: 0 !important;
}    
</style>
<style lang="scss" scoped>
.sort-classify-wrap{
    .list{
        min-height: 300px;
        max-height: 500px;
        .item{
            cursor: pointer;
            padding: 10px 20px;
            font-size: 16px;
            display: flex;
            &:hover{
                background-color: #FFFBF4;
            }
            span{
                flex: 1;
            }
            img{
                width: 20px;
                margin-left: 20px;
            }
        }
    }
    .add-btn{
        background: #F3A52F;
        color: #fff;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
    }
}
.add-box{
    input{
        width: 100%;
        display: block;
        line-height: 40px;
        border: 1px solid #DCDFE6;
        padding: 0 15px;
        box-sizing: border-box;
        border-radius: 40px;
        &:focus{
            outline: none;
        }
    }
}
</style>