<script setup>
import {reactive, ref, watch} from "vue";
import Api from "../../../../../api";
import XImage from "../../../../../components/XImage/Index.vue";
import UploadButton from "../../../../../components/upload/UploadButton.vue";
import {Message} from "@arco-design/web-vue";
import {useSystemStore} from "../../../../../pinia/SystemStore/index.js";

const SystemStore = useSystemStore();
const emits = defineEmits(['success']);
const {task, disabled, yy} = defineProps({
    task: {
        type: Object,
        default: {},
    },
    disabled: {
        type: Boolean,
        default: false,
    },
    yy: {
        type: Boolean,
        default: false,
    }
});
const visible = ref(false);
const TaskSettltment = reactive([]);
const columns = [
    {
        title: '提前约定事项',
        dataIndex: 'intro'
    },
    {
        title: '扣除比例',
        dataIndex: 'ratio'
    },
    {
        title: '扣除金额(元)',
        dataIndex: 'discount',
        slotName: 'discount'
    },
    {
        title: '截图说明',
        dataIndex: 'images',
        slotName: 'images',
        width: 250,
    },
];
const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
});
const selectedKeys = ref([]);

watch(
    () => visible.value,
    (val) => {
        if (val) {
            const api = SystemStore.isRoot ? Api.admin.checkSettlement : Api.merchant.getTaskSettltment;
            api({id: task.task_id || task.id}).then(({data}) => {
                TaskSettltment.length = 0;
                TaskSettltment.push(...data.map((v, index) => ({
                    ...v,
                    key: v.id,
                    images: v?.images ? [...v.images] : [],
                })));

                if (yy) {
                    selectedKeys.value = data.filter(v => v.is_check === 1).map(v => v.id);
                    console.log(selectedKeys.value);
                }

                sumData();
            });
        }
    }
)
const sum = ref(0);
const coin = ref(0);
const sumData = async () => {
    const api = SystemStore.isRoot ? Api.admin.interventionJsTask : Api.merchant.jsTask
    const {data: {real_coin, coin: _coin}} = await api({
        id: task.id,
        ids: TaskSettltment.filter(v => selectedKeys.value.includes(v.id)).map(v => v.id)
    });
    coin.value = _coin;
    sum.value = real_coin;
}

watch(
    () => selectedKeys.value,
    () => {
        sumData();
    },
    {deep: true}
)

const confirmTask = async () => {
    const api = SystemStore.isRoot ? Api.admin.settlement : Api.merchant.confirmTask
    const {msg} = await api({
        id: task.id,
        type: 1,
        content: TaskSettltment.filter(v => selectedKeys.value.includes(v.id)).map(v => ({
            ...v,
            id: v.id,
            images: v.images,
        })),
    });
    visible.value = false;
    Message.success(msg);
    emits('success');
}
</script>

<template>
    <a-link v-if="!$slots.default" @click="disabled ? null : visible = true" :hoverable="false" :disabled="disabled"
            status="success">
        确认结算
    </a-link>
    <div v-else @click="disabled ? null : visible = true">
        <slot></slot>
    </div>

    <a-modal
        width="800px"
        title-align="start"
        :footer="!yy"
        v-model:visible="visible">
        <template v-slot:title>
            <div>确认结算</div>
            <div class="text-[14px] text-[#4E5969] ml-[8px]">提示：若有扣款，请提供对应截图，方便达人理解</div>
        </template>

        <a-table
            :data="TaskSettltment"
            :columns="columns"
            :pagination="false"
            :row-selection="rowSelection"
            v-model:selectedKeys="selectedKeys">
            <template v-slot:discount="{record}">
                {{ record?.discount?.toFixed(2) }}
            </template>
            <template v-slot:images="{record}">
                <div class="flex gap-[16px]">
                    <x-image
                        v-for="(v, index) in record.images"
                        :hide-delete="yy"
                        class="flex-shrink-0"
                        :key="index"
                        width="40px"
                        height="40px"
                        :src="v">
                    </x-image>
                    <upload-button v-if="!yy" :api="SystemStore.isRoot ? Api.system.uploadFile : Api.system.uploadFile2"
                                   @success="e => record.images.push(e)">
                        <template v-slot:upload-button>
                            <div
                                class="size-[40px] bg-[#F2F3F5] flex justify-center items-center flex-col rounded-[8px] cursor-pointer">
                                <icon-plus/>
                                <div>添加</div>
                            </div>
                        </template>
                    </upload-button>
                </div>
            </template>
        </a-table>
        <div class="mt-[22px] flex">
            该子任务需结算：
            <div class="text-[#165DFF] text-[16px]">¥
                {{
                    selectedKeys.length > 0 ? sum : coin
                }}
            </div>
            <div class="text-[14px] text-[#4E5969]" v-if="selectedKeys.length > 0">
                （{{ coin }}
                <span v-for="v in selectedKeys">- {{ TaskSettltment.find(k => k.id === v)?.discount }}</span>
                = {{
                    sum
                }}）
            </div>
        </div>
        <template v-slot:footer>
            <div class="flex justify-end items-center gap-3">
                <a-button @click="visible=false">取消</a-button>
                <a-button type="primary" @click="confirmTask">确定</a-button>
            </div>
        </template>
    </a-modal>
</template>

<style scoped lang="scss">

</style>
