<template>
    <view class="certification-main">
        <Step :step="step" />
        <view v-if="data.auditStatus === '30'" class="certification-error">
            <view class="appStatus-error-icon"></view>
            <view>{{data.auditRemark}}</view>
        </view>
        <view class="certification-scroll">
            <view>
                <view class="certification-content">
                    <!-- 上传资质 -->
                    <view class="flex_c_l certification-title"><text class="text-red" v-if="viewStatus">*</text>{{
                        viewStatus ? '请选择' : '' }}发布服务类目：</view>
                    <!-- 服务类目 -->
                    <Category />
                    <view class="flex_c_l certification-title"><text class="text-red" v-if="viewStatus">*</text>{{
                        viewStatus ? '请填写' : '' }}服务信息：</view>
                    <CategoryInfo />

                    <CategoryImags />

                    <!-- 规格信息 -->
                    <Specifications :viewStatus="viewStatus" />
                </view>
            </view>
        </view>
        <view class="certification-footer flex_c_c">
            <view v-if="[0].includes(step)">
                <view class="btn-w certification-btn flex_c_c" @click="goNext">提交</view>
            </view>
            <view v-if="[1].includes(step)" class="flex_c_c flex-gap">
                <view class="certification-btn-bols flex_c_c btn-p2" @click="onDelete">删除</view>
                <view class="certification-btn flex_c_c btn-p" @click="onEdit">修改</view>
            </view>
            <view v-if="[2].includes(step)" class="flex_c_c flex-gap-30 step-more-main">
                <view class="more-btns" v-if="moreBtn">
                    <view class="more-btn" @click="onDelete">删除</view>
                    <view class="more-btn" @click="onAdd">新增</view>
                </view>
                <view class="more-box" @click="moreBtn = !moreBtn">
                    <view :class="[moreBtn ? 'icon-down' : 'icon-up']"></view>
                    更多
                </view>
                <view class="certification-btn-bols flex_c_c btn-p2" @click="onServeStatus"
                    v-if="data.auditStatus === '20'">
                    {{ data.serviceStatus === '10' ? '下线' : '上线' }}
                </view>
                <view class="certification-btn flex_c_c btn-p" @click="onEdit" v-if="data.auditStatus === '20'">修改
                </view>
                <view class="certification-btn-bols flex_c_c btn-p3" @click="onEdit" v-if="data.auditStatus === '30'">修改
                </view>
            </view>
        </view>
    </view>


</template>

<script setup>
import { computed, ref, reactive, watch } from 'vue';
import { provide, inject } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import store from '@/store';
import { applyVolunteerService, reapplyVolunteerService, volunteerServiceDetails, volunteerServiceDelete, volunteerServiceUp, volunteerServiceDown } from '@/api/volunteer';

import Step from './Step.vue';
import Category from './Category.vue';
import CategoryInfo from './CategoryInfo.vue';
import CategoryImags from './CategoryImags.vue';
import Specifications from './Specifications.vue';

const step = ref(0);
const moreBtn = ref(false);

const volunteerServiceId = ref(null);//服务id


// true: 显示1、2步骤 false: 2、3步骤（查看）
const viewStatus = computed(() => {
    return ![1, 2].includes(step.value)
})
provide('viewStatus', viewStatus);
const data = reactive({

    //服务
    project: {
        // id: '13',
        // businessTierName: '居家陪伴',
    },
    activeProjects: [
        {
            id: '13',
            businessTierName: '居家陪伴',
        },
        {
            id: '14',
            businessTierName: '出行陪伴',
        }
    ],



    auditStatus: '1',  //审批状态 1待审批2已通过3已驳回
    projectImages: [],//图片  注:第一张用于封面展示
    businessManagementId: '',//服务类型id
    name: '',//服务名称
    coverUrl: '', //服务封面图片地址
    url: '',//服务展示图片地址，多张照片使用逗号隔开
    serviceDescribe: '',//服务描述
    volunteerServiceSpecList: [ //服务规格列表
        {
            specDescribe: null,//规格说明
            price: null,//服务价格（元）
            unit: null,//购买单位，例如：次、小时、天等
            minPurchaseQuantity: null,//最少购买数，默认为1
            duration: null,//服务时长（分钟），非时效服务可为空
            serviceType: null,//服务规格类型: 10周期服务 20单次服务 30非时效服务
            isDefault: null,//是否默认规格 0：否 1：是
            isDefault: 1,//是否默认规格 0：否 1：是
        }
    ]

});

provide('formData', data);


watch(data, (newVal, oldVal) => {
    uni.$u.debounce(storageData, 500)
})

const storageData = () => {
    //新增的时候做数据存储
    !volunteerServiceId.value && store.dispatch('handlerReleaseFormData', data)
}
//清除数据
const resetFormData = () => {
    data.projectImages = [];
    data.businessManagementId = '';
    data.name = '';
    data.coverUrl = '';
    data.url = '';
    data.serviceDescribe = '';
    data.project = {};

    data.auditStatus = null;

    data.volunteerServiceSpecList = [
        {
            specDescribe: null,
            price: null,
            unit: null,
            minPurchaseQuantity: null,
            duration: null,
            serviceType: null,
            isDefault: null
        }
    ];
}
// 服务规格必填校验
const specListVerify = () => {
    return new Promise((resolve, reject) => {
        const { volunteerServiceSpecList } = data;

        if (!volunteerServiceSpecList || volunteerServiceSpecList.length === 0) {
            reject('请至少添加一个服务规格');
            return;
        }

        for (let i = 0; i < volunteerServiceSpecList.length; i++) {
            const item = volunteerServiceSpecList[i];
            if (!item.duration) {
                reject('服务时常不能为空');
                return;
            }
            if (!item.specDescribe) {
                reject('规格说明不能为空');
                return;
            }
            if (!item.price || isNaN(item.price) || Number(item.price) <= 0) {
                reject('请输入正确的服务价格');
                return;
            }
            if (!item.unit) {
                reject('购买单位不能为空');
                return;
            }
            if (!item.minPurchaseQuantity || Number(item.minPurchaseQuantity) < 1) {
                reject('最少购买数量必须大于等于1');
                return;
            }
            if (!item.serviceType) {
                reject('请选择服务类型');
                return;
            }
        }

        resolve(true);
    });
};
//服务必选验证
const projectVerify = async () => {
    return new Promise(async (resolve, reject) => {
        if (!data.project.id) reject('请选择服务类目');
        if (data.name.trim().length === 0) reject('请填写服务名称');
        if (data.serviceDescribe.trim().length === 0) reject('请填写服务描述');
        if (data.projectImages.length === 0) reject('请上传服务相关图片');
        //服务规格描述校验
        try {
            await specListVerify(); // 校验服务规格列表
        } catch (error) {
            reject(error);
            return;
        }
        resolve(true)
    })
}

const goNext = async () => {
    try {
        if (step.value === 0) {
            const verify = await projectVerify();
            verify && onSubmit()
        }
        step.value = step.value + 1;
    } catch (error) {
        uni.showToast({
            title: error,
            icon: 'none'
        })
        console.log("TCL: goNext -> error", error)
    }
}

//服务申请
const onSubmit = async () => {
    console.log('提交', data);
    return new Promise(async (resolve, reject) => {
        const {
            name,//服务名称
            serviceDescribe,//服务描述
            volunteerServiceSpecList,
            projectImages,//图片
            project,//选择的服务

        } = data;
        const submit_data = {
            volunteerId: store.getters.userId,//志愿者id
            businessManagementId: project.id,//服务类型id
            name,//服务名称
            coverUrl: projectImages[0], //服务封面图片地址
            url: projectImages.slice(1).join(','),//服务展示图片地址，多张照片使用逗号隔开
            serviceDescribe,//服务描述
            volunteerServiceSpecList,
        }
        console.log('submit', submit_data);
        let res = null;
        //修改
        if (volunteerServiceId.value) {
            submit_data.volunteerServiceId = volunteerServiceId.value;
            res = await reapplyVolunteerService(submit_data);
        } else {
            res = await applyVolunteerService(submit_data);
        }

        console.log("TCL: onSubmit -> res", res)
        if (res.code === 200) {
            store.dispatch('clearReleaseFormData')
            uni.showToast({
                title: volunteerServiceId.value ? '提交成功' : '申请成功',
                icon: 'success'
            })
            resolve();
        }
        reject(res.msg);
    })
}

const getServeDetails = async () => {
    try {
        const res = await volunteerServiceDetails(volunteerServiceId.value);
        if (res.code === 200) {
            const imgs = [res.data.coverUrl, ...res.data.url.split(',')]

            const res_data = {
                ...res.data,
                projectImages: imgs,
                project: {
                    id: res.data.businessManagementId,
                    businessTierName: res.data.businessTierName,
                },
            }
            if (res.data.auditStatus === '10') { //未审核
                step.value = 1;
            }
            if (['20', '30', '40'].includes(res.data.auditStatus)) { //已通过、未通过
                step.value = 2;
            }
            Object.assign(data, res_data);
        }
        console.log("TCL: getServeDetails -> res", res)

    } catch (error) {
        console.log("TCL: getServeDetails -> error", error)

    }
}

const onDelete = async () => {
    try {
        uni.showModal({
            title: '提示',
            content: '确定要删除该服务吗？',
            success: async (res) => {
                if (res.confirm) {
                    // 调用删除接口
                    try {
                        await volunteerServiceDelete(volunteerServiceId.value);
                        uni.showToast({ title: '删除成功' });
                        setTimeout(() => {
                            uni.navigateBack({
                                delta: 1
                            });
                        }, 300)
                    } catch (err) {
                        uni.showToast({ title: '删除失败', icon: 'none' });
                    }
                }
            }
        });
    } catch (error) {
        console.log("TCL: onDelete -> error", error)

    }
}
const onAdd = async () => {
    try {
        resetFormData();
        step.value = 0;
    } catch (error) {
        console.log("TCL: onAdd -> error", error)

    }
}
const onEdit = async () => {
    try {
        data.auditStatus = null;
        step.value = 0;
    } catch (error) {
        console.log("TCL: onEdit -> onEdit", error)

    }
}

const onDown = async () => {
    try {

        uni.showModal({
            title: '提示',
            content: '确定要下线该服务吗？',
            success: async (res) => {
                if (res.confirm) {
                    // 调用删除接口
                    try {
                        const res = await volunteerServiceDown(volunteerServiceId.value);
                        if (res.code === 200) {
                            uni.showToast({
                                title: '下线成功',
                                icon: 'success'
                            })
                            getServeDetails();
                        }
                    } catch (err) {
                        uni.showToast({ title: '下线失败', icon: 'none' });
                    }
                }
            }
        });
    } catch (error) {
        console.log("TCL: onDown -> onEdit", error)

    }
}
const onUp = async () => {
    try {
        const res = await volunteerServiceUp(volunteerServiceId.value);
        if (res.code === 200) {
            uni.showToast({
                title: '服务上线成功',
                icon: 'success'
            })
            getServeDetails();
        }
    } catch (error) {
        console.log("TCL: onDown -> onEdit", error)

    }
}
const onServeStatus = async () => {
    try {
        //下线
        if (data.serviceStatus === '10') {
            await onDown();
        } else {
            await onUp();
        }
        getServeDetails();
    } catch (error) {
        console.log("TCL: onDown -> error", error)
    }
}

//选取服务返回
const activeProjectBack = (options) => {

    if (options.serves) {
        const serves = JSON.parse(decodeURIComponent(options.serves));
        Object.assign(data, { project: serves });
    }
}

// 初始化数据
const initData = () => {
    console.log('初始化数据', store.state.business);
    try {
        const initD = store.state.business.releaseFormData;
        if (initD) {
            Object.assign(data, initD);
        }
    } catch (error) {
        console.log("TCL: initData -> error", error)
    }
}

onLoad((options) => {
    console.log("TCL: options", options);
    if (options.volunteerServiceId) {
        volunteerServiceId.value = options.volunteerServiceId;
        getServeDetails();
        return;
    }
    initData();
})


defineExpose({ activeProjectBack });
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>