<template>
    <popup
        class="active-upload-popup"
        v-model:show="show"
        closeable
        :close-on-click-overlay="false"
    >
        <div class="header">
            <div class="title">
                <span class="required">*</span>
                请上传执行照片
            </div>
        </div>
        <upload exampleImg class="upload-wrap" @handleUpload="handleUpload">
            <img class="example" src="@/assets/img/home/example-4.png" alt="" />
            <img class="example" src="@/assets/img/home/plus.png" alt="">
        </upload>
        <div class="btn" @click="handleConfirm">请求确认</div>
    </popup>
    <FnShareSheet v-model:show="showShare" @select="onSelect" :class="className" />
</template>

<script setup>
import wx from 'weixin-js-sdk';
import { Popup } from "vant";
import { ref } from "vue";
import upload from "@/components/upload";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import FnShareSheet from "@/components/pageComponents/FnShareSheet.vue";
import { base_img_url2 } from "@/api/config";

const router = useRouter();
const props = defineProps({
    onlyShare: {
        type: Boolean,
        default: false,
    },
});

const emit = defineEmits(['uploadSuccess']);

const show = ref(false);
const className = ref(null);
const farmWorkRecordId = ref(null);
const farmData = ref({});
function showPopup(data,classNameVal) {
    if (props.onlyShare) {
        showShare.value = true;
        className.value = classNameVal;
    } else {
        show.value = true;
        farmWorkRecordId.value = data.id;
    }
    farmData.value = data;
}
const images = ref([]);
function handleUpload({imgArr}) {
    images.value = imgArr;
}

function handleConfirm() {
    const params = {
        recordId: farmWorkRecordId.value,
        executeEvidence: images.value,
    };
    VE_API.z_farm_work_record.addExecuteImg(params).then((res) => {
        if (res.code === 0) {
            // ElMessage.success('请求确认成功');
            show.value = false;
            VE_API.z_farm_work_record.getDetail({ id: farmData.value.id }).then(({ data }) => {
                const dataItem = data[0];
                farmData.value = {
                    farmMiniUserId: dataItem.farmMiniUserId || (dataItem.users && dataItem.users.length > 0 ? dataItem.users[0]?.userId : null),
                    farmMiniUserName: dataItem.farmMiniUserName || dataItem.expertUserName,
                    farmWorkOrderId: dataItem.orderId,
                    farmId: dataItem.farmId,
                    executeEvidence:JSON.stringify(dataItem.executeEvidence),
                    farmWorkName: dataItem.farmWorkName,
                    id: dataItem.id,
                }
                farmData.value.type = 'confirmExecute'
                // 通知父组件上传成功，需要刷新数据
                emit('uploadSuccess', farmData.value.id);
                showShare.value = true;
            });
        }
    });
}

const showShare = ref(false);
const onSelect = async ({type}) => {
    if(farmData.value.type === 'remindExecute' || farmData.value.type === 'remindUser') {
        await getTriggerImg();
    }
    if(type === 'birdseye') {
        if(farmData.value.farmMiniUserId){
            if(triggerImg.value.length) {
                farmData.value.imageList = triggerImg.value;
            }
            router.push(`/chat_frame?userId=${farmData.value.farmMiniUserId}&name=${farmData.value.farmMiniUserName}&farmId=${farmData.value.farmId}&pageParams=${JSON.stringify(farmData.value)}`);
        }else{
            ElMessage.warning('尚未绑定用户,暂时无法分享')
        }
    } else {
        if (farmData.value.type === 'quotation') {
            const query = { askInfo: {title: "服务报价单", content: "是否分享该服务报价单给好友"}, shareText: "向您发送了一张 服务报价单", id: farmData.value.id, farmWorkOrderId: farmData.value.orderId, isAssign: true }
            wx.miniProgram.navigateTo({
                url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=priceSheet`,
            });
        } else if (farmData.value.type === 'remindExecute') {
            const query = { askInfo: {title: "提醒执行", content: "是否分享该提示给好友"}, shareText: " 请您尽快执行" + farmData.value.farmWorkName + "农事", id: farmData.value.id, farmWorkOrderId: farmData.value.orderId, postImg: triggerImg.value.length ? base_img_url2 + triggerImg.value[triggerImg.value.length - 1].cloudFilename : '' }
            wx.miniProgram.navigateTo({
                url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=priceSheet`,
            });
        } else if (farmData.value.type === 'remindUser') {
            const query = { askInfo: {title: "提醒拍照", content: "是否分享该提示给好友"}, shareText: " 请您尽快完成复核", id: farmData.value.id, farmWorkOrderId: farmData.value.orderId, postImg: triggerImg.value.length ? base_img_url2 + triggerImg.value[triggerImg.value.length - 1].cloudFilename : '' }
            // reviewWork跳转到农事复核
            wx.miniProgram.navigateTo({
                url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=reviewWork`,
            });
        } else {
            const img = JSON.parse(farmData.value.executeEvidence);
            const imgUrl = base_img_url2 + img[img.length - 1];
            const query = { askInfo: {title: "农事确认单", content: "是否分享该农事确认单给好友"}, shareText: farmData.value.farmWorkName + " 农事已完成，请您确认", id: farmData.value.id, farmWorkOrderId: farmData.value.orderId, postImg: imgUrl }
            wx.miniProgram.navigateTo({
                url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=priceSheet`,
            });
        }
    }
};

const triggerImg = ref([]);
const getTriggerImg = async () => {
    const { data } = await VE_API.z_farm_work_record.getTriggerImg({ farmWorkRecordId: farmData.value.id });
    triggerImg.value = data || [];
}

defineExpose({
    showPopup,
});

</script>

<style lang="scss" scoped>
.active-upload-popup {
    width: 90%;
    box-sizing: border-box;
    padding: 24px 18px 20px;
    background: linear-gradient(0deg, #ffffff 70%, #d1ebff 100%);
    border-radius: 10px;
    ::v-deep {
        .van-popup__close-icon {
            color: #000;
        }
    }
    .header {
        .title {
            font-size: 16px;
            font-weight: 500;
            display: flex;
            align-items: center;
            .required {
                color: #ff4d4f;
                margin-right: 4px;
            }
        }
        .date-input {
            margin: 12px 0;
        }
    }
    .tips-text {
        font-weight: 500;
    }
    .upload-wrap {
        margin: 12px 0 24px;
        .example {
            width: 80px;
            height: 80px;
        }
        .example + .example {
            margin-left: 12px;
        }
    }
}

.btn {
    padding: 8px;
    background: #2199f8;
    border-radius: 25px;
    color: #fff;
    font-size: 16px;
    text-align: center;
}

</style>
<style>
.share-sheet{
    bottom: 50px;
}
</style>