<!-- 客服 -->
<template>
    <el-card style="margin-bottom: 0.5vh;background-color: rgb(243,250,254);">
        <div class="condition">
            <div class="item1">
                <el-text size="large" style="width:4vw;">精网号</el-text>
                <el-input v-model="searchForm.jwcode" placeholder="请输入精网号" style="width:9vw;" clearable />
            </div>
            <div class="item1">
                <el-text size="large" style="width:4vw;">客户姓名</el-text>
                <el-input v-model="searchForm.name" placeholder="请输入客户姓名" style="width:9vw;" clearable />
            </div>
            <div class="item1">
                <el-text size="large" style="width:4vw;">所属地区</el-text>
                <el-cascader style="width: 9vw;" v-model="searchForm.market" :options="market" placeholder="请选择所属地区"
                    clearable @change="handleMarketChange" />
            </div>
            <div class="item1">
                <el-text size="large" style="width:4vw;">产品名称</el-text>
                <el-cascader v-model="searchForm.goodsName" :options="productList" style="width: 10vw;" clearable />
            </div>
            <div class="item1">
                <el-text size="large" style="width:4vw;" multiple>订单状态</el-text>
                <el-select v-model="searchForm.statuses" style="width:9vw;" clearable>
                    <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
        </div>
        <div class="condition">
            <div class="item2">
                <el-text size="large" style="width:4vw;">付款币种</el-text>
                <el-select v-model="searchForm.paymentCurrency" style="width:9vw;" clearable>
                    <el-option v-for="item in currencies" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <div class="item2">
                <el-text size="large" style="width:4vw;">支付方式</el-text>
                <el-select v-model="searchForm.payType" style="width:9vw;" clearable>
                    <el-option v-for="item in channelOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </div>
            <div class="item2" style="width: 28.5vw;">
                <el-text size="large" style="width:4vw;">付款时间</el-text>
                <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="起始时间"
                    end-placeholder="结束时间" style="width:22vw;" :disabled-date="disabledDate" :default-time="defaultTime" clearable />
            </div>
            <div>
                <el-button type="primary" @click="getRefund">查询</el-button>
                <!-- <el-button type="warning">导出excel</el-button>
                <el-button type="primary">查看导出列表</el-button> -->
                <el-button type="success" @click="reset">重置</el-button>
            </div>
        </div>
    </el-card>

    <el-card style="margin-top: 0.5vh;background-color: rgb(231,244,253);">
        <el-table :data="tableData" style="height:64vh;width:82vw;background-color: rgb(243,250,254);">
            <el-table-column type="index" label="序号" width="60" fixed="left" />
            <el-table-column prop="jwcode" label="Homily ID" width="120" fixed="left" />
            <el-table-column prop="name" label="姓名" width="120" fixed="left" show-overflow-tooltip />
            <el-table-column prop="market" label="所属地区" width="120" />
            <el-table-column prop="activity" label="活动名称" width="120px" show-overflow-tooltip />
            <el-table-column prop="goodsName" label="产品名称" width="130" show-overflow-tooltip />
            <el-table-column prop="goodNum" label="产品数量" width="120" />
            <el-table-column prop="paymentCurrency" label="付款币种" width="120" />
            <el-table-column prop="paymentAmount" label="付款金额" width="120" />
            <el-table-column prop="payType" label="支付方式" width="140" />
            <el-table-column prop="payTime" label="付款时间" width="180" />
            <el-table-column prop="voucher" label="转账凭证" width="120" show-overflow-tooltip>
                <template #default="scope">
                    <img v-if="scope.row.voucher" :src="scope.row.voucher" style="width: 40px; height: 40px;" />
                    <span v-else>无转账凭证</span>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip />
            <el-table-column prop="status" label="订单状态" width="120">
                <template #default="scope">
                    {{
                        [10, 20, 30, 40].includes(scope.row.status) ? '审核中' :
                            [12, 22, 32].includes(scope.row.status) ? '已驳回' :
                                [11].includes(scope.row.status) ? '已撤回' :
                                    scope.row.status === 41 ? '退款完成' : scope.row.status
                    }}
                </template>
            </el-table-column>
            <el-table-column prop="operation" label="操作" fixed="right" width="100px">
                <template #default="scope">
                    <div class="operation">
                        <el-button v-if="scope.row.status === 10" type="primary" text
                            @click="showBackDialog(scope.row)">
                            撤回
                        </el-button>
                        <el-button v-if="scope.row.status === 11" type="primary" text
                            @click="showEditDialog(scope.row)">
                            编辑
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
            @size-change="handlePageSizeChange" @current-change="handleCurrentChange"
            style="margin-top: 1vh;"></el-pagination>
    </el-card>

    <el-dialog v-model="showEdit" title="退款" class="editDialog" overflow draggable style="width: 40vw;">
        <div style="display: flex;">
            <div class="left">
                <div class="add-item">
                    <el-text style="width:4vw;">精网号</el-text>
                    <el-input v-model="editRow.jwcode" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">客户姓名</el-text>
                    <el-input v-model="editRow.name" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">所属地区</el-text>
                    <el-input v-model="editRow.marketName" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">活动名称</el-text>
                    <el-input v-model="editRow.activity" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">产品名称</el-text>
                    <el-input v-model="editRow.goodsName" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">产品数量</el-text>
                    <el-input v-model="editRow.goodNum" style="width:10vw;" disabled />
                    &nbsp;个
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">付款币种</el-text>
                    <el-input v-model="editRow.paymentCurrency" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">付款金额</el-text>
                    <el-input v-model="editRow.paymentAmount" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">支付方式</el-text>
                    <el-input v-model="editRow.payType" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">付款时间</el-text>
                    <el-date-picker v-model="editRow.payTime" type="datetime" style="width:10vw;" disabled />
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">转账凭证</el-text>
                    <img v-if="editRow.voucher" :src="editRow.voucher"
                        style="width: 80px; height: 80px; object-fit: cover;">
                    <div v-else>
                        无转账凭证
                    </div>
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">备注</el-text>
                    <el-input v-model="editRow.remark" style="width:10vw;" :rows="3" type="textarea" maxLength="100"
                        disabled show-word-limit />
                </div>
            </div>
            <div class="right">
                <div class="add-item">
                    <el-text style="width:4vw;">退款类型</el-text>
                    <el-radio-group v-model="editForm.refundModel">
                        <el-radio value="0">全部退款</el-radio>
                        <el-radio value="1">部分退款</el-radio>
                    </el-radio-group>
                </div>
                <div class="add-item">
                    <el-text style="width:4vw;">退款理由</el-text>
                    <el-input v-model="editForm.refundReason" style="width:10vw;" :rows="5" maxlength="150"
                        show-word-limit type="textarea" />
                </div>
                <div>ps:请在退款理由表明用户的退款需求。</div>
                <div style="display:flex;justify-content: center;margin-top: 5vh;">
                    <el-button type="default" @click="resetEdit">重置</el-button>
                    <el-button type="primary" @click="submitEdit">提交</el-button>
                </div>
            </div>
        </div>
    </el-dialog>

    <ConfirmDialog v-model="showBack" message="撤回该信息!" @confirm="recall" @cancel="showBack = false"
        @close="showBack = false" />

    <el-dialog v-model="showError" overflow draggable class="back-dialog" :style="{
        backgroundImage: 'url(/src/assets/images/撤回.png)',
        backgroundSize: 'cover',
        backgroundPosition: 'center'
    }">
        <div class="back-text">退 款 金 额 填 写 有 误</div>
        <div class="back-btn">
            <el-button type="default" @click="showError = false">取消</el-button>
            <el-button type="primary" @click="" style="margin-left: 2vw;">确定</el-button>
        </div>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import API from '@/util/http.js'
const uploadUrl = 'https://api.homilychart.com/hljw/api/aws/upload'
import { useAdminStore } from "@/store/index.js"
import { storeToRefs } from "pinia"
import dayjs from 'dayjs'
const adminStore = useAdminStore()
const { adminData, menuTree } = storeToRefs(adminStore)
import { permissionMapping, findMenuById, hasMenuPermission } from "@/utils/menuTreePermission.js"
import ConfirmDialog from '@/components/dialogs/ConfirmDialog.vue'
import { pa } from 'element-plus/es/locales.mjs'

const dateRange = ref([])
const searchForm = ref({
    jwcode: '',
    market: [],
    statuses: []
})
const market = ref([])
const backRow = ref({})// 撤回存数据
const editRow = ref({})// 编辑存数据
const editForm = ref({
    refundModel: '',
    refundReason: ''
})
const auditForm = ref({
    refundType: ''
})
const pagination = ref({
    pageNum: 1,
    pageSize: 50,
    total: 0
})
const tableData = ref([])
const showEdit = ref(false)
const uploadRef = ref(null)
const showBack = ref(false)
const showError = ref(false)
const isKF = adminData.value.adminName.includes('客服')
const statusList = ref([
    {
        value: 'waiting',
        label: '待审核',
    },
    {
        value: 'pending',
        label: '审核中'
    },
    {
        value: 'completed',
        label: '退款完成'
    }
])
// 查全部
const getRefund = async function () {
    if (!hasMenuPermission(menuTree.value, permissionMapping.refundServiceShow)) {
        ElMessage.error('无此权限')
        return
    }
    try {
        if (searchForm.value.statuses === 'completed') {
            searchForm.value.statuses = [41]
        } else if (searchForm.value.statuses === 'pending') {
            searchForm.value.statuses = [20, 30, 40]
        } else if (searchForm.value.statuses === 'waiting') {
            searchForm.value.statuses = [10]
        }
        const params = {
            pageNum: pagination.value.pageNum,
            pageSize: pagination.value.pageSize,
            cashRecordDone: {
                jwcode: searchForm.value.jwcode,//精网号
                name: searchForm.value.name,//姓名
                markets: searchForm.value.market,//地区
                goodsNames: searchForm.value.goodsName,//商品名
                statuses: searchForm.value.statuses,//10：地区财务待审核；12：地区财务驳回；
                // 20：地区负责人待审核；22：地区负责人驳回；
                // 30：总部财务待审核；32：总部财务驳回；
                // 40：执行人待处理；41：执行人已处理，退款完成；
                paymentCurrency: searchForm.value.paymentCurrency,//付款币种
                payType: searchForm.value.payType,//支付方式
                startTime: dateRange.value && dateRange.value[0] ? dayjs(dateRange.value[0]).format('YYYY-MM-DD HH:mm:ss') : "",
                endTime: dateRange.value && dateRange.value[1] ? dayjs(dateRange.value[1]).format('YYYY-MM-DD HH:mm:ss') : "",
                submitterId: adminData.value.id
            }
        }

        const result = await API({
            url: '/Money/selecta',
            method: 'POST',
            data: params
        })

        tableData.value = result.data.list || []
        pagination.value.total = result.data.total || 0
    } catch (error) {
        ElMessage.error(error.message || '查询失败')
    }
}
// 撤回
const recall = async function () {
    if (!hasMenuPermission(menuTree.value, permissionMapping.refundServiceBack)) {
        ElMessage.error('无此权限')
        return
    }
    try {
        console.log(backRow.value)
        const params = {
            id: backRow.value.id,
            status: backRow.value.status,
            orderType: backRow.value.orderType
        }
        const result = await API({
            url: '/Money/update',
            data: params
        })
        if (result.code === 200) {
            ElMessage.success(result.msg || '退款成功')
            showBack.value = false
            getRefund()
        } else {
            ElMessage.error(result.msg || '退款失败')
        }
    } catch (error) {
        ElMessage.error(error.message || '退款失败')
    }
}
// 编辑
const submitEdit = async function () {
    if (!hasMenuPermission(menuTree.value, permissionMapping.refundServiceEdit)) {
        ElMessage.error('无此权限')
        return
    }
    try {
        console.log(editRow.value)
        const params = {
            id: editRow.value.id,
            status: editRow.value.status,
            refundModel: editForm.value.refundModel,
            refundReason: editForm.value.refundReason,
            jwcode: editRow.value.jwcode,
            paymentAmount: editRow.value.paymentAmount,
            paymentCurrency: editRow.value.paymentCurrency
        }
        const result = await API({
            url: '/Money/update',
            data: params
        })
        if (result.code === 200) {
            ElMessage.success(result.msg || '编辑成功')
            showEdit.value = false
            getRefund()
        } else {
            ElMessage.error(result.msg || '编辑失败')
        }
    } catch (error) {
        ElMessage.error(error.message || '编辑失败')
    }
}
const getMarket = async function () {
    try {
        const result = await API({

            url: '/market/selectMarket',
        })
        console.log('看看地区树', result)

        const transformTree = (nodes) => {
            const allChildren = nodes.flatMap(node => node.children || []);

            return allChildren.map(child => {
                const grandchildren = child.children && child.children.length
                    ? transformTree([child])
                    : null;

                return {
                    value: child.name,
                    label: child.name,
                    children: grandchildren
                };
            });
        };
        market.value = transformTree(result.data)
        console.log('转换后的地区树==============', market.value)
    } catch (error) {
        console.log('请求失败', error)
    }
}
const currencies = ref([
    {
        value: '新币',
        label: '新币'
    },
    {
        value: '港币',
        label: '港币'
    },
    {
        value: '马币',
        label: '马币'
    },
    {
        value: '加币',
        label: '加币'
    },
    {
        value: '泰铢',
        label: '泰铢'
    },
    {
        value: '越南盾',
        label: '越南盾'
    }
])
const channelOptions = ref([{
    value: '银行转账',
    label: '银行转账'
},
{
    value: '现金',
    label: '现金'
},
{
    value: '支票',
    label: '支票'
},
{
    value: '刷卡',
    label: '刷卡'
},
{
    value: 'Grabpay',
    label: 'Grabpay'
},
{
    value: 'Nets',
    label: 'Nets'
},
{
    value: 'PayPal',
    label: 'PayPal'
},
{
    value: 'Stripe-链接收款',
    label: 'Stripe-链接收款'
},
{
    value: 'Ipay88-链接收款',
    label: 'Ipay88-链接收款'
},
{
    value: 'PaymentAsia-链接收款',
    label: 'PaymentAsia-链接收款'
},
{
    value: 'Stripe-Link平台',
    label: 'Stripe-Link平台'
},
{
    value: 'PaymentAsia-Link平台',
    label: 'PaymentAsia-Link平台'
},
{
    value: 'FirstData-Link平台-Link平台',
    label: 'FirstData-Link平台-Link平台'
},
{
    value: 'IOS-Link平台',
    label: 'IOS-Link平台'
},
{
    value: 'Ipay88-Link平台',
    label: 'Ipay88-Link平台'
}
])
const productList = [
    {
        "value": "金币产品",
        "label": "金币产品",
        "children": [
            {
                "value": "金币充值",
                "label": "金币充值",
            }
        ]
    },
    {
        "value": "软件产品",
        "label": "软件产品",
        "children": [
            {
                "value": "美股",
                "label": "美股",
                "children": [
                    {
                        "value": "美股软件",
                        "label": "美股软件"
                    }
                ]
            },
            {
                "value": "港股",
                "label": "港股",
                "children": [
                    {
                        "value": "港股软件",
                        "label": "港股软件"
                    }
                ]
            },
            {
                "value": "A股",
                "label": "A股",
                "children": [
                    {
                        "value": "A股软件",
                        "label": "A股软件"
                    }
                ]
            },
            {
                "value": "新加坡股",
                "label": "新加坡股",
                "children": [
                    {
                        "value": "新加坡股软件",
                        "label": "新加坡股软件"
                    }
                ]
            },
            {
                "value": "马股",
                "label": "马股",
                "children": [
                    {
                        "value": "马股软件",
                        "label": "马股软件"
                    }
                ]
            },
            {
                "value": "日本股",
                "label": "日本股",
                "children": [
                    {
                        "value": "日本股软件",
                        "label": "日本股软件"
                    }
                ]
            },
            {
                "value": "泰股",
                "label": "泰股",
                "children": [
                    {
                        "value": "泰股软件",
                        "label": "泰股软件"
                    }
                ]
            },
            {
                "value": "越南股",
                "label": "越南股",
                "children": [
                    {
                        "value": "越南股软件",
                        "label": "越南股软件"
                    }
                ]
            },
            {
                "value": "印尼股",
                "label": "印尼股",
                "children": [
                    {
                        "value": "印尼股软件",
                        "label": "印尼股软件"
                    }
                ]
            },
            {
                "value": "韩国股",
                "label": "韩国股",
                "children": [
                    {
                        "value": "韩国股软件",
                        "label": "韩国股软件"
                    }
                ]
            },
            {
                "value": "台湾股",
                "label": "台湾股",
                "children": [
                    {
                        "value": "台湾股软件",
                        "label": "台湾股软件"
                    }
                ]
            }
        ]
    },

]
const reset = function () {
    searchForm.value = {
        jwcode: '',
        market: searchForm.value.market,
        statuses: searchForm.value.statuses
    }
    dateRange.value = []
    getRefund()
}
const resetEdit = function () {
    editForm.value = {
        refundModel: '',
        refundReason: ''
    }
}
const showBackDialog = function (row) {
    backRow.value = row
    showBack.value = true
}
const showEditDialog = function (row) {
    editRow.value = row
    showEdit.value = true
}
const handlePageSizeChange = function (val) {
    pagination.value.pageSize = val
    getRefund()
}
const handleCurrentChange = function (val) {
    pagination.value.pageNum = val
    getRefund()
}
const disabledDate = (time) => {
    const limitDate = new Date(2025, 0, 1);
    return time.getTime() < limitDate.getTime();
}
const handleMarketChange = (value) => {
    searchForm.value.market = value || []
}
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]
onMounted(() => {
    getRefund()
    getMarket()
    console.log('???????????????????', adminData.value)
})
</script>
<style scoped lang="scss">
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
:deep(.el-table__body td) {
    background-color: #F3FAFE !important;
}

:deep(.el-table__header th) {
    background-color: #F3FAFE !important;
}

.condition {
    width: 82vw;
    display: flex;
    align-items: center;
    height: 4vh;

    .item1 {
        width: 18%;
        display: flex;
        align-items: center;
        margin-bottom: 1vh;
        margin-right: 0.5vw;
    }

    .item2 {
        width: 18%;
        display: flex;
        align-items: center;
        margin-right: 0.5vw;
    }
}

.editDialog {
    .left {
        width: 50%;
        height: 70vh;
        padding: 0 2vw;

        .add-item {
            display: flex;
            align-items: center;
            margin-bottom: 1vh;
        }

        .image {
            width: 4vw !important;
            height: 4vw !important;
        }
    }

    .right {
        width: 50%;
        height: 50vh;

        .add-item {
            display: flex;
            align-items: center;
            margin-bottom: 1vh;
        }
    }
}

.back-dialog {
    width: 700px;
    height: auto;

    .back-text {
        font-size: 60px;
        font-weight: bold;
        color: #000000;
        text-align: center;
        justify-content: center;
        margin-top: 22vh;
    }

    .back-btn {
        height: 20vh;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}
</style>