<template>
    <div class='pages' v-if="detail">
        <section>
            <div class="card  m-top12">
                <div class="m-top5 flex flex-center font-pingfangB" v-if="this.selfObj.source === 1">
                    {{ this.detail.title || '--' }}<br>
                </div>
                <div class="m-top5 flex flex-center">
                    <img src="@/assets/images/icon/address.png" class="small_img m-right7">
                    {{ detail.serviceTargetName || '--' }} {{ detail.serviceTargetMobile }}<br>
                </div>

                <div class="opacity5 font-size13 m-top5" style="margin-left: 29px;" v-if="selfObj.source == 4">{{
                    detail.serviceTargetAddress }}
                </div>
                <div class="opacity5 font-size13 m-top5" style="margin-left: 29px;" v-else-if="detail.serviceTargetAddresses">{{
                    detail.serviceTargetAddresses.join('，') }}
                </div>
                <div class="opacity5 font-size13 m-top5" style="margin-left: 29px;" v-else>--
                </div>
                <div class="m-top5  flex flex-center" v-if="selfObj.source  === 4">
                    <img src="@/assets/images/icon/time.png" class="small_img m-right7">
                    <div>
                        {{ detail.serviceStartTime || '--' }}
                    </div>
                </div>
                <div class="m-top5  flex flex-center" v-else>
                    <img src="@/assets/images/icon/time.png" class="small_img m-right7">
                    <div style="font-size: 15px;">
                        {{ detail.serviceTimeStart || '--' }} 至 {{ detail.serviceTimeEnd || '--' }}
                    </div>
                </div>
                <div class="m-top5 ">
                    <div class="flex flex-center3">
                        <img src="@/assets/images/icon/content.png" style="vertical-align: top;"
                            class="small_img m-right7">
                        <div class="van-multi-ellipsis--l2">{{ detail.content }}</div>
                    </div>
                </div>
            </div>

            <div class="card m-top12" style="padding: 5px;">
                <van-cell title="服务类型" :value="sourceName" />
                <van-cell :title="source === 4 ?'需求分类':'服务类别'" :value="detail.categoryName" />
                <van-cell title="上报人" :value="detail.serviceTargetName + detail.serviceTargetMobile"
                    v-if="selfObj.source == 4" />
                <van-cell title="上报时间" :value="detail.reportTime" v-if="selfObj.source == 4" />
                <van-cell title="实际服务时间" :value="`${detail.serviceStartTime} 至 ${detail.serviceEndTime}`"
                    v-if="selfObj.source == 4" />
                <van-cell title="评分"  v-if="selfObj.source == 4" >
                    <template #default>
                        <van-rate v-model="detail.score" readonly color="#ffd21e"/>
                    </template>
                </van-cell>
                <van-cell title="创建时间" :value="detail.createdTime"
                    v-if="selfObj.source != 4 && selfObj.processStatus === 10" />
                <van-cell title="指派时间" :value="detail.assignTime"
                    v-if="selfObj.source != 4 && (selfObj.processStatus === 30 || selfObj.processStatus === 20)" />
                <van-cell title="完成时间" :value="detail.actualCompletedTime?detail.actualCompletedTime:'--'"
                    v-if="selfObj.source != 4 && selfObj.processStatus === 30" />
            </div>
        </section>
        <div class="bto_btn flex flex-center" style="justify-content: end;">
            <!-- source: 0:公共服务 1:共性需求 2:政策找人 3:服务找人 4:个性需求 5:温暖找人 6:技能找人 7:岗位找人 -->
            <!--processStatus: 10待接单/待指派；20待处理；30已完成 -->

            <van-button size="small" type="info" class="m-left12 rounded-corner m-top5-bottom"
                v-if="selfObj.processStatus === 10 && selfObj.source !== 4" @click="showScope = true">接单</van-button>
            <van-button size="small" type="info" class="m-left12 rounded-corner m-top5-bottom"
                v-if="selfObj.processStatus === 20 && selfObj.source !== 4 && selfObj.confirmedFlag === 1"
                @click="handelClickComplete">完成服务</van-button>

            <van-button size="small" type="info" class="m-left12 rounded-corner m-top5-bottom"
                v-if="selfObj.processStatus === 10 && selfObj.source === 4" @click="showRole = true">接单</van-button>
            <a :href='`tel:${selfObj.serviceTargetMobile}`'
                v-if="selfObj.processStatus === 20 && selfObj.source === 4">联系需求人</a>
            <van-button size="small" type="info" class="m-left12 rounded-corner m-top5-bottom"
                v-if="selfObj.processStatus === 20 && selfObj.confirmedFlag !== 1"
                @click="confirmService">确认服务</van-button>
            <van-button size="small" type="info" class="m-left12 rounded-corner m-top5-bottom"
                v-if="selfObj.processStatus === 20 && selfObj.source === 4 && selfObj.confirmedFlag === 1"
                @click="showComplete = true">完成服务</van-button>
        </div>
        <van-dialog v-model="showRole" title="请选择接单身份" show-cancel-button @confirm="receiveService">
            <van-radio-group v-model="serviceOrgType">
                <van-radio :name="item.serviceOrgType" v-for="(item) in roleList" :key="item.id"
                    @click="handelChangeRole(item.serviceOrgId)">{{ item.serviceOrgName
                    }}</van-radio>
            </van-radio-group>
        </van-dialog>
        <!-- 个性需求完成弹框 -->
        <van-dialog v-model="showComplete" title="我已完成需求人的需求" show-cancel-button :before-close="onBeforeClose">
            <p class="required">服务开始时间</p>
            <span @click="showStart = true, showPopup = true" class="font-size13">{{ actualServiceStartTime || '服务开始时间'
                }}</span><span class="tag-date">至</span><span @click="showEnd = true, showPopup = true"
                class="font-size13">{{ actualServiceEndTime || '服务结束时间' }}</span>
            <p class="required">完成情况</p>
            <van-radio-group v-model="rdFinishResult">
                <van-radio name="resolved">已解决</van-radio>
                <van-radio name="unresolved">未解决</van-radio>
            </van-radio-group>
            <p>上传图片</p>
            <div class="block">
                <template>
                    <van-uploader v-model="fileList" :after-read="afterRead" :max-count="3"
                        :max-size="10 * 1024 * 1024" />
                </template>
            </div>
            <p class="required">评价</p>
            <van-rate v-model="rdScore" :size="25" color="#ffd21e" void-icon="star" void-color="#eee" />
            <p>备注</p>
            <van-field v-model="rdFinishDesc" rows="2" autosize type="textarea" placeholder="请输入备注" />

        </van-dialog>
        <van-popup v-model="showPopup" position="bottom">
            <van-datetime-picker v-if="showStart" v-model="serviceTimeStart" type="datetime" title="开始时间"
                @confirm="handelCLickConfirmStart" @cancel="showPopup = false" :min-date="minDate" />
            <van-datetime-picker v-if="showEnd" v-model="serviceTimeEnd" @confirm="handelCLickConfirmEnd"
                @cancel="showPopup = false" type="datetime" title="结束时间" :min-date="minDate" />
            <van-cascader v-if="showTree" v-model="cascaderValue" title="请选择范围" :options="treeOptions"
                @close="showTree = false, showPopup = false" @finish="onFinish"
                :field-names="{ text: 'objectName', value: 'objectId' }" />
        </van-popup>
    </div>
</template>

<script>
import { receiveService, getListMyIdentities, getServiceScopeTree, serviceComplete, serviceConfirm } from '@/api/service'
import { uploadvariedfile } from '@/api/basic'
import { Dialog } from 'vant';
export default {
    data() {
        return {
            detail: null,
            typeList: ['公共服务', '共性需求', '政策找人', '服务找人', '个性需求', '温暖找人', '技能找人', '岗位找人'],
            id: null,
            showPopup: false,
            showStart: false,
            showEnd: false,
            showTree: false,
            showScope: false,
            minDate: new Date(),
            treeOptions: null,
            cascaderValue: null,
            serviceScopeName: null,
            serviceTimeStart: null,
            serviceTimeEnd: null,
            roleList: [],
            serviceOrgType: null,
            serviceOrgId: null,
            showRole: false,
            actualServiceStartTime: null,//实际完成时间
            actualServiceEndTime: null,//实际完成时间
            showComplete: false,//完成弹框
            rdFinishResult: null,//是否解决
            rdScore: 5,//评分
            fileList: [],//图片上传
            rdFinishDesc: null,//备注
        };
    },
    created() {
        this.getListMyIdentities()
        this.getServiceScopeTree()
    },
    mounted() {
        this.detail = this.$route.params.detail;
        this.selfObj = this.$route.params.selfObj;
        this.source = this.selfObj.source;
        this.id = this.selfObj.id;
        this.sourceName = this.typeList[this.source]
    },
    methods: {
        afterRead(file) {
            file.status = 'uploading'
            file.message = '上传中...'
            uploadvariedfile(file.file)
                .then(res => {
                    file.status = ''
                    file.message = '上传成功'
                    file.url = res.data.url
                    console.log(this.fileList)
                })
                .catch(() => {
                    file.status = 'failed'
                    file.message = '上传失败'
                })
        },
        async confirmService() {
            let { data, code, msg } = await serviceConfirm({ id: this.id })
            if (code === 0) {
                this.selfObj.confirmedFlag = 1
            }
        },
        onBeforeClose(action, done) {
            if (action === "confirm") {
                if (this.selfObj.source === 4) {
                    if (!this.actualServiceStartTime) {
                        this.$tips.warning('请选择服务开始时间')
                        return done(false)
                    }
                    if (!this.actualServiceEndTime) {
                        this.$tips.warning('请选择服务结束时间')
                        return done(false)
                    }
                    if (!this.rdScore) {
                        this.$tips.warning('请进行评价')
                        return done(false)
                    }
                    if (!this.rdFinishResult) {
                        this.$tips.warning('请选择完成情况')
                        return done(false)
                    }
                    let parm = {
                        source: this.selfObj.source,
                        id: this.selfObj.id,
                        actualServiceStartTime: this.actualServiceStartTime,
                        actualServiceEndTime: this.actualServiceEndTime,
                        rdScore: this.rdScore,
                        rdFinishResult: this.rdFinishResult,
                        rdFinishAttachments: this.fileList.map(item => ({ originFileName: item.file.name, type: item.file.type, format: 'image', url: item.url })),
                        rdFinishDesc: this.rdFinishDesc
                    }
                    this.serviceComplete(parm)
                    done(true)
                }
            }
            // 点击了取消按钮
            else {
                done(true);
            }
        },

        handelClickComplete() {
            if (this.selfObj.source != 4) {
                Dialog.confirm({
                    message: `确定已完成“${this.detail.title}”服务吗？`,
                }).then(() => {
                    this.serviceComplete(this.selfObj)
                }).catch(() => {
                });
            }
        },
        async serviceComplete(parm) {
            let { code } = await serviceComplete(parm)
            if (code === 0) {
                this.$tips.success('服务完成')
                this.$router.go(-1)
            }
        },
        handelChangeRole(val) {
            this.serviceOrgId = val;
        },
        onFinish(value) {
            this.showTree = false;
            this.showPopup = false;
            this.serviceScopeList = value.selectedOptions.map(item => ({ objectType: item.objectType, objectId: item.objectId, objectName: item.objectName }))
            this.serviceScopeName = value.selectedOptions.map(item => item.objectName).join('-')
        },
        //提交接单
        async receiveService() {
            let parm = {
                ...this.selfObj,
                id: this.id,
            }
            if (this.showScope) {
                parm.serviceScopeList = this.serviceScopeList;
                parm.serviceTimeStart = this.serviceTimeStart;
                parm.serviceTimeEnd = this.serviceTimeEnd;
                parm.serviceOrgType = this.serviceOrgType;
                parm.serviceOrgId = this.serviceOrgId;
            } else if (this.showRole) {
                parm.serviceOrgType = this.serviceOrgType;
                parm.serviceOrgId = this.serviceOrgId;
            }
            console.log(parm);
            let { data, code, msg } = await receiveService(parm)
            if (code === 0) {
                this.$tips.success('接单成功')
                this.showRole = false;
                this.showScope = false;
                this.$router.back()
            }
        },
        handelCLickConfirmStart(val) {
            if (this.selfObj.processStatus === 20) {
                this.actualServiceStartTime = this.$dayjs(val).format('YYYY-MM-DD HH:mm:ss');
            } else {
                this.serviceTimeStart = this.$dayjs(val).format('YYYY-MM-DD HH:mm:ss');
            }
            this.showPopup = false;
            this.showStart = false;
        },
        handelCLickConfirmEnd(val) {
            if (this.selfObj.processStatus === 20) {
                this.actualServiceEndTime = this.$dayjs(val).format('YYYY-MM-DD HH:mm:ss');
            } else {
                this.serviceTimeEnd = this.$dayjs(val).format('YYYY-MM-DD HH:mm:ss');
            }
            this.showPopup = false;
            this.showEnd = false;
        },
        async getListMyIdentities() {
            let { data, code, msg } = await getListMyIdentities()
            if (code === 0) {
                this.roleList = data;
            }
        },
        async getServiceScopeTree() {
            let { data, code, msg } = await getServiceScopeTree({ id: this.serverId })
            if (code === 0) {
                this.treeOptions = [data];
            }
        },
    },
    components: {},
    computed: {},
    watch: {},
}
</script>

<style lang='less' scoped>
.pages {
    padding: 0 10px;
    box-sizing: border-box;
}

:deep(.van-cell__value) {
    text-align: left;
}

:deep(.van-cell__title) {
    max-width: 80px;
}

:deep(.van-button--small) {
    padding: 12px 30px;
}

a {
    border: 1px solid #ebedf0;
    color: #333333;
    padding: 0 10px;
    border-radius: 15px;
    height: 26px;
    line-height: 26px;
    display: inline-block;
    margin-left: 10px;
    font-size: 12px;
}
</style>
