<template>
    <uni-section title="交付物清单" type="line">
        <template v-slot:right>
            <button size="default" class="mini-btn"
                hover-class="is-hover" @click="redirectAddOutcomePage()">添加</button>
        </template>
    </uni-section>
    <view style="background: #fff;padding:1px 5px 5px 5px;">
        <uni-collapse accordion>
            <uni-collapse-item title-border="none" style="border:1px #ebeef5 solid;margin-bottom:5px;"
                v-for="(outcome, index) in outcomeList" :key="outcome.id" :class="getRibbonInfo(outcome.change_marker)?.subClass && !!draft ? getRibbonInfo(outcome.change_marker)?.subClass : ''
                    ">
                <template v-slot:title>
                    <view style="display: flex;position: relative;">
                        <view v-if="draft && getRibbonInfo(outcome.change_marker)" class="ribbon-wrapper">
                            <view :class="'ribbon ' + getRibbonInfo(outcome.change_marker)?.class">
                                {{ getRibbonInfo(outcome.change_marker)?.label }}
                            </view>
                        </view>
                        <view class="card-header">
                            <view class="header-box">

                                <view class="header-box-title">{{ outcome.name }}</view>
                            </view>
                            <view>
                                <uni-tag :text="outcomeStatus(outcome.status!)?.label" :inverted="true" style=""
                                    :custom-style='"padding:2px 4px;font-size:10px;font-weight:bolder;border: 1px solid transparent;background:" + tagColor(outcomeStatus(outcome.status!)!.color).bg + ";color:" + tagColor(outcomeStatus(outcome.status!)!.color).color'>
                                </uni-tag>
                            </view>
                        </view>
                    </view>
                </template>

                <view class="font-size-sm collapse-content">
                    <text class="subtitle font-size-base">计划交付时间：<text class="paragraph font-size-sm">{{
                        outcome.plan_time }}</text></text>
                </view>
                <view class="font-size-sm collapse-content">
                    <text class="subtitle font-size-base">完成交付时间：<text class="paragraph font-size-sm">{{
                        outcome.completed_at || '-' }}</text></text>

                </view>
                <view class="font-size-sm collapse-content" v-if="outcome.showProgress">
                    <text class="subtitle font-size-base">
                        {{ outcome.uploaded ? '文件下载中：' : '文件上传中：' }}
                    </text>
                    <custom-progress :value="outcome.progress" style="min-width: 250px"
                        :stroke-width="16"></custom-progress>
                </view>
                <view class="card-actions">
                    <view class="card-actions-item" @click="redirectModifyOutcomePage(outcome)">
                        <uni-icons type="compose" size="18" color="#4cd964"></uni-icons>
                        <text class="card-actions-item-text">修改</text>
                    </view>
                    <view class="card-actions-item" v-if="!props.draft">
                        <view v-if="!outcome.uploaded">
                            <uni-file-picker file-mediatype="all" :auto-upload="false" mode="list" limit="1"
                                @select="(e: any) => handlerSelectFileUpload(e, outcome)">
                                <view style=" display: flex; align-items: center;"><uni-icons type="upload" size="18"
                                        color="#007aff"></uni-icons>
                                    <text class="card-actions-item-text">上传附件</text>
                                </view>
                            </uni-file-picker>
                        </view>
                        <view v-else style="display: flex; align-items: center;"
                            @click="startDownloadFileItem(outcome)">
                            <uni-icons type="download" size="18" color="#007aff"></uni-icons>
                            <text class="card-actions-item-text">下载附件</text>
                        </view>

                    </view>
                    <!-- <view class="card-actions-item" @click="" v-if="outcome.uploaded">
                        <uni-icons type="minus" size="18" color="#dd524d"></uni-icons>
                        <text class="card-actions-item-text">删除附件</text>
                    </view> -->
                    <view class="card-actions-item" @click="redirectOutcomeDetailPage(outcome.id)">
                        <uni-icons type="info" size="18" color="#007aff"></uni-icons>
                        <text class="card-actions-item-text">详情</text>
                    </view>
                    <view class="card-actions-item" @click="hanlderRemoveOutcome(outcome, index)">
                        <uni-icons type="trash" size="18" color="#dd524d"></uni-icons>
                        <text class="card-actions-item-text">删除</text>
                    </view>
                </view>
            </uni-collapse-item>
        </uni-collapse>
        <!-- <uni-card margin="2px" padding="2px" :is-shadow="false"
            v-for="outcome in outcomeList" :key="outcome.id">
            <template #title>
                <view class="card-header">
                    <view class="header-box">
                        <view class="header-box-title">{{ outcome.name }}</view>
                    </view>
                </view>
            </template>
            <view class="font-size-sm progress-actions ">
                <text class="subtitle font-size-base">状态: </text>
           
            </view>
      
        </uni-card> -->
    </view>
</template>
<script lang="ts" setup>
import { getDownloadOutcomeUrl, getOutcomeList, getUploadOutcomeUrl, removeOutcome } from '@/api/project-center/outcome';
import { ChangeMarkerList, OutcomeStatusList } from '@/enums/api';
import customProgress from '@/components/cu-progress/index.vue'
import { useEmitt } from '@/logics/mitt/useEmitt';
import { Outcome } from '@/types/outcome';
import { tagColor } from '@/utils'
import { downloadFile, saveFile, uploadFile } from '@/api/base/client';


const upload_picker = ref()
const { emitter } = useEmitt();
const outcomeList = ref<Outcome[]>([])
const props = defineProps({
    draft: {
        type: Boolean,
        required: true,
        default: () => {
            return false
        }
    },
    task_id: {
        type: String
    },
    accountList: {
        type: Array as PropType<{ id: string; name: string }[]>
    }
})

const getRibbonInfo = (mark?: number) => {
    return ChangeMarkerList.find(item => item.value === mark)
}


// 根据交付物状态获取对应样式标签
const outcomeStatus = (status: number) => {
    return OutcomeStatusList.find(item => item.status === status)
}


// 跳转添加交付界面
const redirectAddOutcomePage = () => {
    uni.navigateTo({ url: `/pages/project/plan-task-detail/add-outcome?task_id=${props.task_id}&draft=${props.draft}` })
}


// 跳转修改交付界面
const redirectModifyOutcomePage = (outcome: Outcome) => {
    uni.navigateTo({ url: `/pages/project/plan-task-detail/edit-outcome?outcome_id=${outcome.id}&draft=${props.draft}` })
}

/**
 * 跳转到交付物详情
 * @param outcomeId
 */
const redirectOutcomeDetailPage = (outcomeId: string) => {
    emitter.emit('redirectOutcomeDetailPage', outcomeId)
}


// 删除交付物
const hanlderRemoveOutcome = async (outcome: Outcome, index: number) => {
    uni.showModal({
        title: '删除交付物',
        content: `确认删除交付物：${outcome.name}吗？`,
        success: async (res: { confirm: boolean }) => {
            const { confirm } = res;
            if (confirm) {
                await removeOutcome({ id: outcome.id, draft: props.draft })
                getOutcomes()
                uni.showToast({
                    icon: 'success',
                    title: '删除成功'
                })
                if (props.draft) {
                    emitter.emit('get_task_list')
                }
            }
        }
    })
}

const getOutcomes = async () => {
    const { list } = await getOutcomeList({
        draft: props.draft,
        task_id: props.task_id!
    })
    outcomeList.value = list

}

// 监听进度条
const onProgressResult = (e: UniApp.OnProgressDownloadResult | UniApp.OnProgressUpdateResult, outcome: Outcome) => {
    outcome.showProgress = true
    outcome.progress = e.progress
}

// 选择上传文件，并上传
const handlerSelectFileUpload = async (e: {
    tempFilePaths: string[], tempFiles: {
        name: string
        extname: string
        url: string
    }[]
}, outcome: Outcome) => {
    try {
        const { tempFiles, tempFilePaths } = e
        if (tempFilePaths.length > 0) {
            const {
                url,
                form_data,
                headers,
                object_name
            } = await getUploadOutcomeUrl({
                id: outcome.id,
                filename: tempFiles[0].name
            })

            await uploadFile({ url, object_name, headers, formData: form_data, filePath: tempFilePaths[0], uploadProgress: onProgressResult, otherParams: outcome })
            emitter.emit('get_outcome_list')
            uni.showToast({ title: '上传成功' })
            outcome.uploaded = true;
            outcome.showProgress = false
            outcome.progress = 0
        }

    } catch (_e) {
        outcome.showProgress = false
        outcome.progress = 0

    }
}


const startDownloadFileItem = async (outcome: Outcome) => {
    uni.showActionSheet({
        itemList: ['分享到好友', '添加到收藏'],
        success: async (res: UniApp.ShowActionSheetRes) => {
            await downloadFileItem(outcome, res.tapIndex)
        }
    });

}

// 下载文件
const downloadFileItem = async (outcome: Outcome, sheetIndex: number) => {
    try {
        const { url } = await getDownloadOutcomeUrl({
            id: outcome.id,
        })
        const { savedFilePath } = await downloadFile({ url, downloadProgress: onProgressResult, otherParams: outcome })
        await saveFile(savedFilePath, outcome.filename, sheetIndex)
        outcome.showProgress = false
        outcome.progress = 0
    } catch (_e) {
        outcome.showProgress = false
        outcome.progress = 0
    }
}


onMounted(() => {
    getOutcomes()
})

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
    name: 'get_outcome_list',
    callback: () => {
        getOutcomes()
    }
})

</script>
<script lang="ts">
export default {
    options: {
        styleIsolation: 'apply-shared', //解除样式隔离
    }

}
</script>
<style lang="less" scoped>
:deep(.is-text-box) {
    display: none;
}

:deep(.uni-file-picker__lists-box){
    display: none
}

.slot-check-box {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    align-items: center;
    width: 45px;
    margin-right: 10px;
}


.slot-check-content {
    display: flex;
    justify-content: space-between;
    flex-direction: row;
    width: 100%;
    align-items: center;
    /* height: 45px; */
}

.slot-check-panel {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
}

.slot-check-title {
    display: flex;
    font-size: 14px;
    color: #3b4144;
}

.slot-check-subtitle {
    display: flex;
    padding-top: 6px;
    font-size: 12px;
    color: #999
}

.slot-check-desc {
    color: #999;
    font-size: 12px;
    //   width: 200px;
    text-overflow: ellipsis;
    text-align: right;
    text-wrap: wrap;
    overflow-wrap: anywhere;
    white-space-collapse: collapse;

}

.tag-container {
    max-width: 210px;
    display: flex;
    flex-wrap: wrap;
}

.tag-container__item {
    padding: 0 6px 6px 0;
    white-space: nowrap;

}

.card-actions {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    height: 35px;
    border-top: 1px #EBEEF5 solid;
}

.card-actions-item {
    display: flex;
    flex-direction: row;
    align-items: center;
}

.card-actions-item-text {
    font-size: 12px;
    color: #999;
}

.card-header {
    display: flex;
    flex: 1;
    border-bottom: 1px #ebeef5 solid;
    flex-direction: row;
    align-items: center;
    padding: 10px 10px 10px 25px;
    overflow: hidden;

    .header-box {
        display: flex;
        flex: 1;
        flex-direction: row;
        align-items: center;
        overflow: hidden;

        .header-box-title {
            font-size: 14px;
            color: #3b4144;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    }
}

.collapse-content {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    height: 25px;
    line-height: 25px;
    font-size: 12px;
    padding: 5px 10px;
}

.font-size-base {
    font-size: 24rpx;
}

.paragraph {
    color: #b2a9a6;
    font-weight: 600;
}

.subtitle {
    color: #b2a9a6;
}


.ribbon-wrapper {
    width: 71px;
    height: 51px;
    overflow: hidden;
    position: absolute;
    left: 0
}

.ribbon {
    font: bold 15px Sans-Serif;
    line-height: 10px;
    font-size: 10px;
    text-align: center;
    text-transform: uppercase;
    transform: rotate(-45deg);
    position: relative;
    padding: 3px 0;
    left: -20px;
    top: 5px;
    color: #fff;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    letter-spacing: 0.5px;
    box-shadow: -3px 5px 6px -5px rgba(0, 0, 0, 0.5);
}

.ribbon:before,
.ribbon:after {
    content: '';
    // border-top: 4px solid #4e7c7d;
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    position: absolute;
    bottom: -4px;
}

.ribbon:before {
    content: '';
    position: absolute;
    left: 0px;
    top: 100%;
    // z-index: -1;
    // border-left: 4px solid #4e7c7d;
}

.ribbon:after {
    content: '';
    position: absolute;
    right: 0px;
    top: 100%;
    z-index: -1;
}

.ribbon-add {
    background-color: #4cd964;
}

.ribbon-modify {
    background-color: #f0ad4e;
}

.ribbon-remove {
    background-color: #dd524d;
}

.ribbon-sub-add {
    background-color: #aff0b5;
}

.ribbon-sub-modify {
    background-color: #fff7e8;
}

.ribbon-sub-remove {
    background-color: #ffece8;
}

.mini-btn {
  color: #ffffff !important;
  background-color: #007aff;
  border-color: #007aff !important;
  font-size: 24rpx !important;
  -webkit-tap-highlight-color: transparent;
  border-radius: 5px;
  box-sizing: border-box;
  cursor: pointer;
  display: block;
  line-height: 2.55555556;
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
  padding-left: 28rpx;
  padding-right: 28rpx;
  position: relative;
  text-align: center;
  text-decoration: none;
  height: auto;
}
</style>