<template>
    <view class="flex">
        <!-- 联系客服 -->
        <!-- <template v-if="contract">
            <button
                class="Btn mr-2 bg-white text-base text-black leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="handleShowModal"
            >
                联系客服
            </button>
        </template> -->

        <!-- 取消订单 -->
        <template v-if="cancel">
            <button
                class="Btn mr-2 bg-white text-base text-black leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="handleOrderCancel(orderId)"
            >
                取消订单
            </button>
        </template>

        <!-- 删除订单 -->
        <template v-if="orderStatus == 4 || del">
            <button
                class="Btn mr-2 bg-white text-base text-black leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="handleOrderDel(orderId)"
            >
                删除订单
            </button>
        </template>

        <!-- 去评价：0-隐藏 1-显示 -->
        <!-- @click.stop="goPage('/bundle/pages/evaluate_list/index')" -->
        <template v-if="evaluate">
            <button
                class="Btn evaluate bg-white text-sm text-muted leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="goPage(`/bundle/pages/evaluate_submit/index?id=${orderId}`)"
            >
                去评价
            </button>
        </template>

        <!-- 联系师傅 -->
        <template
            v-if="
                staffMobile?.length > 0 &&
                !(confirmService || verification) &&
                ((isDispatch && orderStatus == 1) || orderStatus == 2)
            "
        >
            <button
                class="Btn flex-1 mr-2 bg-white text-sm text-black leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="handleContactMobile()"
            >
                联系师傅
            </button>
        </template>

        <!-- 联系客户 -->
        <template v-if="mobile && (confirmService || verification)">
            <!-- <button
                class="Btn flex-1 mr-2 bg-white text-sm text-black leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="handleCustomerMobile()"
            >
                联系客户
            </button> -->
            <view
                class="px-[24rpx] items-center flex-1 mr-2 bg-white text-sm text-black leading-[70rpx] h-[70rpx] rounded-full"
                style="border: 1px solid rgb(187, 187, 187)"
                @click.stop="handleCustomerMobile()"
            >
                <u-icon size="40" name="phone"></u-icon>
            </view>
        </template>

        <!-- 去支付 -->
        <template v-if="pay">
            <button
                class="bg-primary text-lg ml-[20rpx] text-white leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="handlePayment"
            >
                去支付
            </button>
        </template>

        <!-- 确认服务 -->
        <template v-if="confirmService && isCanConfirmService">
            <button
                class="bg-primary text-lg text-white leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="handleConfirmService(orderId)"
            >
                开始服务
            </button>
        </template>
        <!-- 还不可以确认服务 -->
        <template v-if="confirmService && !isCanConfirmService">
            <button
                class="BtnDisable text-lg text-[#cecece] leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="handleNotConfirmService(orderId)"
            >
                开始服务
            </button>
        </template>

        <!-- 核销订单 -->
        <template v-if="verification">
            <view class="flex justify-around">
                <button
                    class="Btn flex-1 mr-2 bg-white text-sm text-black leading-[70rpx] h-[70rpx] rounded-full"
                    @click.stop="showInputCode = true"
                >
                    手动核销码
                </button>
                <button
                    class="flex-1 mr-2 bg-primary text-sm text-white leading-[70rpx] h-[70rpx] rounded-full"
                    @click.stop="handleScanQRCode"
                >
                    扫码核销
                </button>
                <button
                    class="bg-primary text-sm text-white leading-[70rpx] h-[70rpx] rounded-full"
                    @click.stop="handleNavigate"
                >
                    拍照上传
                </button>
            </view>

            <!-- 手动输入核销码MODAL -->
            <u-modal
                ref="uModalInput"
                v-model="showInputCode"
                show-cancel-button
                confirmColor="#1296DB"
                confirm-text="确定"
                @confirm="inputOrderCode"
                @cancel="handleCancel"
                title="手动核销"
            >
                <view class="slot-content justify-center" style="padding: 60rpx 40rpx">
                    <u-input
                        type="number"
                        v-model="code"
                        :border="true"
                        placeholder="请输入核销码"
                        style="width: 100%"
                    />
                </view>
            </u-modal>
        </template>
        <!-- 已完成 -->
        <template v-if="uploadServiceImgBtn && orderStatus == 3">
            <button
                class="bg-primary text-sm text-white leading-[70rpx] h-[70rpx] rounded-full"
                @click.stop="handleNavigate"
            >
                拍照上传
            </button>
        </template>
    </view>
    <u-popup
        v-model="showConfirmPop"
        mode="center"
        height="500"
        border-radius="14"
        :mask-close-able="false"
        closeable
    >
        <view class="text-center w-[560rpx] py-[40rpx]">
            <view class="w-[160rpx] h-[160rpx] px-[200rpx]">
                <u-image width="160" height="160" :src="goodsImage" />
            </view>
            <view class="mt-[20rpx] truncate">{{ goodsName }}</view>
            <view class="mt-[10rpx] mb-[40rpx] text-[#f36161]">完成服务请点击确认</view>
            <button
                class="flex-1 bg-primary text-sm text-white leading-[70rpx] h-[70rpx] rounded-full mx-[40rpx]"
                @click.stop="confirmVerification"
            >
                确认核销
            </button>
        </view>
    </u-popup>
    <u-popup v-model="isHide" mode="center" closeable border-radius="14" v-if="isHide">
        <view class="text-center w-[660rpx] py-[40rpx]">
            <view class="reason">
                <view v-if="isShowScore" class="mb-[20rpx]">是否确认取消订单？</view>
                <!-- <view v-if="isShowScore" class="mb-[20rpx]">
                    上门服务前
                    <text class="text-error mx-[8rpx]">{{ state.intervalTime }}</text>
                    分钟内取消订单，扣款比例
                    <text class="text-error mx-[8rpx]">{{ state.value }}</text>
                    %，扣款金额
                    <text class="text-error mx-[8rpx]">{{ state.deductMoney }}</text>
                    元
                </view> -->
                <u-input
                    class="textarea"
                    v-model="reason"
                    type="textarea"
                    :maxlength="255"
                    :trim="true"
                    :border="true"
                    placeholder="请输入取消订单原因"
                    :height="200"
                />
                <text class="limit">{{ reason.length }}/255</text>
            </view>
            <view class="operation-btn">
                <button
                    @click="handleShowModal"
                    class="Btn flex-1 mr-2 bg-white text-sm text-black leading-[70rpx] h-[70rpx] rounded-full"
                >
                    联系客服
                </button>
                <button
                    @click="handleConfirmModal"
                    class="bg-primary text-lg text-white leading-[70rpx] h-[70rpx] rounded-full"
                >
                    确定
                </button>
            </view>
        </view>
    </u-popup>
</template>

<script lang="ts" setup>
import {
    apiByteQueryRefund,
    apiCancelOrderRule,
    apiOrderCancel,
    apiOrderDel,
    apiStaffOrderConfirmService,
    apiStaffOrderVerification
} from '@/api/order'
import { OrderStatusEnum, PayFromType } from '@/enums/appEnums'
import { useUserStore } from '@/stores/user'
import { getClient, isWeixinClient } from '@/utils/client'
import { toast } from '@/utils/util'
import { storeToRefs } from 'pinia'
import { onMounted, onUnmounted, reactive, ref, unref } from 'vue'

const emit = defineEmits(['refresh', 'backRefresh', 'contact'])
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const props = withDefaults(
    defineProps<{
        orderId?: any // 订单ID
        orderSn?: any // 订单编号
        cancel?: boolean | number | null // 取消订单
        evaluate?: boolean | number | null // 评价
        pay?: boolean | number | null // 支付
        confirmService?: boolean | number | null // 确认服务
        verification?: boolean | number | null // 核销订单
        goodsImage?: string | null // 商品图片
        goodsName?: string | null // 商品名称
        order_amount?: number | string | null // 订单金额
        mobile?: number | string | null // 手机号码
        contact?: number | boolean // 联系师傅
        staffId?: any
        type?: number | null // 支付方式
        orderStatus?: number | string | null // 订单状态;0-待支付;1-预约中;2-服务中;3-已完成;4-已退款;5-退款中
        del?: boolean | number | null // 删除订单
        appointTime?: string // 上门日期
        appointTimeStartStr?: string //上门服务开始时间
        isDispatch?: number | null // 是否派单
        staffMobile?: string | null // 师傅联系电话
        contract: number | null
        goodsId?: number | string
        uploadServiceImgBtn: number | string | boolean
    }>(),
    {
        orderId: '',
        orderSn: '',
        cancel: false,
        evaluate: false,
        pay: false,
        confirmService: false,
        verification: false,
        goodsImage: '',
        goodsName: '',
        del: false,
        contact: false,
        mobile: '',
        staffId: '',
        type: 2,
        orderStatus: '',
        appointTime: '',
        appointTimeStartStr: '',
        isDispatch: 0, // 是否派单 0=否 1=是 默认为0
        staffMobile: '',
        contract: null,
        goodsId: '',
        uploadServiceImgBtn: false
    }
)
const code = ref<number | string>('') // 输入核销码
const showInputCode = ref<boolean>(false) // 显示(输入核销码)：是 | 否

// 页面跳转
const goPage = (url: string) => {
    uni.navigateTo({ url })
}

const isHide = ref(false)
const reason = ref('')
const isShowScore = ref(false)
const state = reactive({
    intervalTime: '',
    value: '',
    deductMoney: ''
})

/**取消订单-取消 */
const handleCloseModal = () => {
    reason.value = ''
}
/**取消订单-确定 */
const handleConfirmModal = async () => {
    if (!unref(reason).length) return toast('请输入取消订单原因')
    await cancelOrderAction()
    isHide.value = false
}
// 取消订单
const handleOrderCancel = async (id: number | string): Promise<void> => {
    /**待支付 */
    if (props.orderStatus === OrderStatusEnum.NO_PAYMENT) {
        uni.showModal({
            title: '温馨提示',
            content: '确定取消订单？',
            success: async res => {
                if (res.cancel) return
                await cancelOrderAction()
            }
        })
        return
    }
    try {
        const data = {
            orderId: props.orderId,
            goodsId: props.goodsId
        }
        const res = await apiCancelOrderRule(data)
        isShowScore.value = !Object.keys(res).length ? false : true
        if (isShowScore.value) {
            state.intervalTime = res.intervalTime ?? '--'
            state.value = res.value ?? '--'
            state.deductMoney = res.deductMoney ?? '--'
        }
        isHide.value = true
    } catch (error) {}
}
/**调用取消订单接口 */
async function cancelOrderAction() {
    try {
        const data = {
            id: props.orderId,
            userId: userInfo.value.id,
            source: getClient(),
            refundReason: unref(reason),
            goodsId: props.goodsId,
            serviceTimeBeforeMinute: state.intervalTime,
            deductionRatio: state.value
        }
        await apiOrderCancel(data)
        // #ifdef MP-TOUTIAO
        if (props.orderStatus === 0 || props.orderStatus === 1) {
            // 非抖音不需要，先指定MP-TOUTIAO，防止微信小程序报数据不存在
            await apiByteQueryRefund({
                order_id: props.orderId
            })
        }
        // #endif
        uni.$u.toast('操作成功')
    } catch (error) {
        console.log('错误信息：', error, props.orderId)
    }
    emit('refresh')
}
// 删除订单
const handleOrderDel = async (id: number | string): Promise<void> => {
    const modelRes = await uni.showModal({
        title: '温馨提示',
        content: '确认删除该订单吗？'
    })
    if (modelRes.cancel) return

    try {
        await apiOrderDel({ id })
        uni.$u.toast('操作成功')
    } catch (error) {
        console.log('错误信息：', error, props.orderId)
    }

    emit('refresh')
}

// 支付
const handlePayment = () => {
    const param = {
        order_id: props.orderId,
        sn: props.orderSn,
        from: PayFromType.ORDER,
        order_amount: props.order_amount
    }
    uni.$emit('payment', param)
}
// 联系师傅
const handleContactMobile = () => {
    uni.makePhoneCall({
        phoneNumber: props.staffMobile //仅为示例
    })
}
// 联系客户
const handleCustomerMobile = () => {
    uni.makePhoneCall({
        phoneNumber: props.mobile //仅为示例
    })
}
// 确认服务
const handleConfirmService = async (id: number | string): Promise<void> => {
    const modelRes = await uni.showModal({
        title: '温馨提示',
        content: '确认开始服务该订单吗？'
    })
    if (modelRes.cancel) return
    await apiStaffOrderConfirmService({ id })
    uni.$u.toast('操作成功')
    emit('refresh')
}
const handleNotConfirmService = async (id: number | string): Promise<void> => {
    const modelRes = await uni.showModal({
        title: '温馨提示',
        content: '预约前2小时才可以开始服务'
    })
}

// 扫码
const handleScanQRCode = () => {
    // #ifdef H5
    if (!isWeixinClient()) return uni.$u.toast('h5暂不支持扫码')
    showInputCode.value = true
    // #endif

    // #ifdef MP
    wx.scanCode({
        success: data => {
            code.value = data.result
            showConfirmPop.value = true
        },
        fail: err => {
            console.log(err)
        }
    })
    // #endif
}

// 确认核销
const showConfirmPop = ref(false)
const confirmVerification = async () => {
    try {
        await apiStaffOrderVerification({ id: props.orderId, code: code.value })
        code.value = ''
        uni.$u.toast('订单核销成功')
        showConfirmPop.value = false
        emit('refresh')
    } catch (error) {
        uni.$u.toast(error)
    }
}
// 手动输入核销码
const inputOrderCode = async (): Promise<void> => {
    if (code.value === '') return uni.$u.toast('请输入核销码')
    try {
        await apiStaffOrderVerification({ id: props.orderId, code: code.value })
        uni.$u.toast('订单核销成功')
        emit('refresh')
    } catch (error) {
        console.log(error)
    }
    code.value = ''
}

// 取消核销码弹框
const handleCancel = () => {
    code.value = ''
    emit('refresh')
}
const handleNavigate = () => {
    uni.navigateTo({
        url: `/bundle/pages/service_order_image/index?id=${props.orderId}`
    })
}
// 以下为确认服务相关判定，在预约时间的前2小时前，才可以确认服务
const isCanConfirmService = ref(false) // 检查是否可以确认服务，在预约时间的前2小时前，才可以确认
const checkconfirmService = () => {
    if (!props.confirmService) {
        return
    }
    if (isCanConfirmService.value) {
        return
    }

    const date = new Date(props.appointTime + ' ' + props.appointTimeStartStr)
    const now = new Date()

    const isBefore = now.getTime() < date.getTime()
    const isAfter = date.getTime() < now.getTime()

    const minutesBeforeAndAfter = Math.abs(now.getTime() - date.getTime()) / 1000 / 60 // 毫秒到分钟

    console.log(
        '当前时间',
        new Date(Date.parse(new Date().toString())),
        props.appointTime + ' ' + props.appointTimeStartStr,
        isBefore,
        isAfter,
        minutesBeforeAndAfter
    )

    //即前2小时内
    if (isBefore && minutesBeforeAndAfter < 60 * 2) {
        console.log('即前2小时内')
        isCanConfirmService.value = true
    }

    //即后10小时内
    // if (isAfter && minutesBeforeAndAfter < 60 * 10) {
    if (isAfter) {
        isCanConfirmService.value = true
    }

    // 临时更改- 都可以确认服务（初步上线）
    isCanConfirmService.value = true
}
/**联系客服 */
const handleShowModal = () => {
    emit('contact')
}
const _timer = ref(null) // 定时器用于检查卡片是否被中断，防止死锁。开始时有一
onMounted(() => {
    isCanConfirmService.value = false
    if (props.confirmService) {
        checkconfirmService()
        _timer.value = setInterval(() => {
            checkconfirmService()
        }, 10000)
    }
})

// 清除定时器
onUnmounted(() => {
    clearInterval(_timer.value)
    if (props.confirmService) {
        console.log('--- 退出定时器 --', new Date(Date.parse(new Date().toString())))
    }
})
</script>

<style lang="scss" scoped>
.reason {
    padding: 30rpx;
    position: relative;
    font-size: 28rpx;

    .limit {
        position: absolute;
        right: 50rpx;
        bottom: 40rpx;
        font-size: 28rpx;
    }
}

.operation-btn {
    display: flex;
    gap: 20rpx;
    padding: 0 30rpx;

    > button {
        flex: 1;
    }
}

.Btn {
    border: 1px solid rgba(187, 187, 187, 1);
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    text-align: center;
}

.evaluate {
    border: 1px solid $blue5;
    color: $blue5;
}

.BtnDisable {
    border: 1px solid rgba(187, 187, 187, 1);
    background-color: rgba(255, 255, 255, 1);
    color: rgb(88, 88, 88);
    text-align: center;
}
</style>
