<template>
    <el-dialog v-model="visableDialog" title="余额明细" top="10vh" width="550" @closed="closeHandle">
        <div class="box">
            <div class="box1" v-loading="tableData.loading">
                <div class="dialog_footer" v-for="(item, index) in tableData.list" :key="index">
                    <div class="dialog_footer_left">
                        <span>{{ labelFilter(item.bizCode) }}</span>
                        <span>{{ item.createTime }}</span>
                    </div>
                    <div class="dialog_footer_right">
                        <span class="active" v-if="item.amount > 0">
                            +￥{{ formatDecimal(item.amount) }}
                        </span>
                        <span v-else>
                            -￥{{ formatDecimal(+JSON.stringify(item.amount).replace('-', '')) }}
                        </span>
                        <span>余额：￥{{ formatDecimal(item.balance) }}</span>
                    </div>
                    <div class="btm" style="width: 80px;">
                        <el-button type="primary"
                            v-if="item.bizCode == 'cashIn' || item.bizCode == 'wechatIn' || item.bizCode == 'alipayIn'"
                            @click="showRefundHandle(item)" :disabled="item.amount == item.refundAmount">
                            <template v-if="item.refundAmount < item.amount">退款</template>
                            <template v-if="item.amount == item.refundAmount">已退</template>
                        </el-button>
                    </div>
                </div>
                <el-empty description="暂无数据" v-if="!tableData.list.length" />
            </div>
            <div class="page_wrap">
                <el-pagination v-model:current-page="tableData.page" background layout="prev, pager, next, total"
                    :total="tableData.total" :pager-count="5" @current-change="memberqueryMemberAccountAjax" />
            </div>
            <el-dialog v-model="showDialog" top="1vh" title="会员充值退款">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="100">
                    <el-form-item label="当前余额">
                        <span>{{ refundItem.amount }}</span>
                    </el-form-item>
                    <el-form-item label="充值金额">
                        <span>{{ refundItem.inAmount }}</span>
                    </el-form-item>
                    <el-form-item label="已退金额">
                        <el-input v-model="refundItem.inRefundAmount" disabled />
                    </el-form-item>
                    <template v-if="refundItem.giftAmount - refundItem.giftRefundAmount > 0">
                        <el-form-item label="赠送金额">
                            <el-input v-model="refundItem.giftAmount" disabled />
                        </el-form-item>
                        <el-form-item label="已退赠送金额">
                            <el-input v-model="refundItem.giftRefundAmount" disabled />
                        </el-form-item>
                    </template>
                    <el-form-item label="退款金额" prop="amount">
                        <el-input-number v-model="form.amount" :min="0.01" :max="form.max" placeholder="请输入" />
                        <div class="tips" v-if="refundItem.giftAmount - refundItem.giftRefundAmount > 0">
                            注意：一旦退款，优先扣除赠送金额</div>
                    </el-form-item>
                    <el-form-item label="退款说明" prop="remark">
                        <el-input v-model="form.remark" placeholder="请输入退款说明" />
                        <div class="remark_tag">
                            <div class="item" v-for="(item, index) in remarkTagList" :key="index"
                                @click="addRmarkHandle(item)">
                                {{ item }}
                            </div>
                            <div class="item" @click="form.remark = ''">
                                <el-icon>
                                    <CircleClose />
                                </el-icon>
                                清空
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div style="padding: 0 20px 20px;width: 100%;display: flex;justify-content: space-between;">
                        <el-button type="danger" @click="handleRefund">手动退款</el-button>
                        <div class="btn" style="display: flex;">
                            <el-button @click="showDialog = false">取消</el-button>
                            <el-button type="primary" :loading="loading" @click="refundHandle">原路返回</el-button>
                        </div>
                    </div>
                </template>
            </el-dialog>
            <takeFoodCode ref="takeFoodCodeRef" title="退款密码" :type="2" input-type="password" placeholder="请输入退款密码"
                @success="passwordSuccess" />
        </div>
    </el-dialog>
</template>

<script setup>
import md5 from "js-md5";
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { formatDecimal } from '@/utils/index'
import { shopUserChargeFlow } from '@/api/account.js'
import { refundVipBefore, refundVip } from '@/api/order.js'
import { staffPermission } from '@/api/user.js'
import takeFoodCode from "@/components/takeFoodCode.vue";
import { useGlobal } from '@/store/global.js'
import { useUser } from '@/store/user.js'
import { ElMessageBox } from 'element-plus'

const userStore = useUser()
const globalStore = useGlobal()
const userInfo = ref('')
const visableDialog = ref(false)
const tableData = reactive({
    page: 1,
    total: 0,
    loading: false,
    list: []
})

// 重置
function closeHandle() {
    tableData.page = 1
    tableData.total = 0
    tableData.loading = false
    tableData.list = []
}

// 过滤流水名称
function labelFilter(type) {
    let item = globalStore.bizCodes.find(item => item.type == type)
    if (item) {
        return item.label
    } else {
        return type
    }
}

// 会员流水
async function memberqueryMemberAccountAjax() {
    try {
        tableData.loading = true
        let res = await shopUserChargeFlow({
            userId: userInfo.value.userId,
            bizCode: '',
            page: tableData.page,
            pageSize: 10
        })
        tableData.loading = false
        tableData.total = +res.totalRow
        tableData.list = res.records
    } catch (error) {
        console.log(error);
    }
}

const emits = defineEmits(['refund'])

const takeFoodCodeRef = ref(null)
const showDialog = ref(false)
const form = reactive({
    amount: 0,
    max: 999,
    remark: ''
})
const rules = reactive({
    amount: [
        {
            trigger: 'blur',
            required: true,
            message: '请输入退款金额'
        }
    ],
    remark: [
        {
            trigger: 'blur',
            required: true,
            message: '请输入退款原因'
        }
    ]
})
const loading = ref(false)
const refundItem = ref({})
const formRef = ref(null)
const flowItem = ref({})
const cashRefund = ref(false)
const remarkTagList = ref([
    '点错了',
    '不要了',
    '没货了'
])

// 添加备注
function addRmarkHandle(item) {
    if (form.remark.length) {
        form.remark += `，${item}`
    } else {
        form.remark = item
    }
}

// 显示充值退款
async function showRefundHandle(item) {
    try {
        // await staffPermission('yun_xu_tui_kuan')
        // 退款前置操作
        flowItem.value = item
        const res = await refundVipBefore({
            shopId: item.shopId,
            userId: item.userId,
            flowId: item.id
        })
        refundItem.value = res

        if (res.amount - (res.giftAmount - res.giftRefundAmount) - (res.inAmount - res.inRefundAmount) <= 0) {
            ElMessage.error('剩余可退款金额不足')
            form.amount = 0
            return
        }

        if (res.amount - (res.giftAmount - res.giftRefundAmount) >= (res.inAmount - res.inRefundAmount)) {
            form.amount = formatDecimal(res.inAmount - res.inRefundAmount, 2, true)
        } else {
            form.amount = formatDecimal(res.amount - res.giftAmount - res.giftRefundAmount, 2, true)
        }

        form.max = form.amount
        showDialog.value = true
    } catch (error) {
        console.log(error);
    }
}

// 线上充值退款
function refundHandle() {
    formRef.value.validate(async valid => {
        try {
            if (valid) {
                loading.value = true
                // 更新店铺详情获取最新的密码规则
                await userStore.getShopInfo()
                loading.value = false
                if (userStore.shopInfo.isMemberInPwd == 1) {
                    takeFoodCodeRef.value.show();
                } else {
                    passwordSuccess()
                }
            }
        } catch (error) {
            console.log(error);
        }
        loading.value = false
    })
}

// 显示手动退款
function handleRefund() {
    ElMessageBox.confirm('请线下手动转账给客户或现金，一旦操作完成无法修改订单状态，请慎重操作！', '注意', {
        confirmButtonText: '已在线下完成退款'
    }).then(async () => {
        cashRefund.value = true
        await userStore.getShopInfo()
        loading.value = false
        if (userStore.shopInfo.isMemberInPwd == 1) {
            takeFoodCodeRef.value.show();
        } else {
            passwordSuccess()
        }
    }).catch(() => { })
}

// 得到退款密码
async function passwordSuccess(e = '') {
    try {
        loading.value = true
        await refundVip({
            shopId: flowItem.value.shopId,
            userId: flowItem.value.userId,
            flowId: flowItem.value.id,
            refAmount: form.amount,
            remark: form.remark,
            outOfRange: false,
            cashRefund: cashRefund.value,
            pwd: e,
        })
        ElMessage.success('退款成功')
        form.amount = 1
        form.remark = ''
        showDialog.value = false
        loading.value = false
        emits('refund')
        memberqueryMemberAccountAjax()
    } catch (error) {
        console.log(error);
    }
    loading.value = false
}

function show(row) {
    userInfo.value = row
    visableDialog.value = true
    cashRefund.value = false
    memberqueryMemberAccountAjax()
}

defineExpose({
    show
})
</script>

<style scoped lang="scss">
.remark_tag {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding-top: 10px;

    .item {
        height: 35px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        padding: 6px 12px;
        border: 1px solid #ddd;
        background-color: #fff;
        border-radius: 4px;
        color: #555;

        &:active {
            background-color: #ddd;
        }
    }
}

.box {

    .box1 {
        height: 350px;
        overflow-y: auto;
    }

    .page_wrap {
        padding-top: 20px;
    }

    .dialog_footer:nth-child(1) {
        margin-top: 0;
    }

    .dialog_footer {
        margin-top: 10px;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #ececec;
        padding-bottom: 6px;

        .dialog_footer_left {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: flex-start;

            span:nth-child(1) {
                font-size: 18px;
                font-weight: 500;

            }

            span:nth-child(2) {
                margin-top: 10px;
                color: #999;
                font-size: 12px;
            }
        }

        .dialog_footer_right {
            width: 150px;
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            padding-right: 20px;

            span:nth-child(1) {
                font-size: 16px;

                &.active {
                    color: #fc3d3d;
                }

            }

            span:nth-child(2) {
                margin-top: 10px;
                font-size: 14px;
                color: #999;
            }
        }
    }
}
</style>