<template>
    <view class="container">
        <uni-section class="mb-10" title="基本信息" type="line"></uni-section>
        <uni-list :border="true">
            <uni-list-item title="创建日期" :rightText="detail.contract?.created_at" />
            <uni-list-item title="合同名称" :rightText="detail.contract?.name">
                <template #footer>
                    <view style="width:100%">
                        <EditorListItem style="width:100%" v-model="modifyParams.name" placeholder="项目名称"
                            :old-value="detail.contract?.name" :not-allow-null="true"
                            :components-type="ComponentsType.STRINGINPUT" @modify="modifyContractInfo" />
                    </view>
                </template>
            </uni-list-item>
            <uni-list-item title="合同编号" :rightText="detail.contract?.id" />
            <uni-list-item title="签订人">
                <template #footer>
                    <view style="width:100%">
                        <EditorListItem style="width:100%" v-model="modifyParams.handler_id" placeholder="项目负责人"
                            :options="accountList" :old-value="detail.contract?.handler_id"
                            :components-type="ComponentsType.SELECT" @modify="modifyContractInfo"
                            :not-allow-null="true" />
                    </view>
                </template>
            </uni-list-item>
            <uni-list-item title="合同金额">
                <template #footer>
                    <view style="width:100%">
                        <EditorListItem style="width:100%" v-model.number="modifyParams.amount" placeholder="合同金额"
                            :old-value="detail.contract?.amount" :components-type="ComponentsType.DIGIT"
                            inputSuffix="万元" @modify="modifyContractInfo" />
                    </view>
                </template>
                <!-- <template #footer>
                    <text style="color: #5d5959;font-size: 13px;">{{ detail.contract?.amount }} 万元</text>
                </template> -->
            </uni-list-item>
            <uni-list-item title="客户信息">
                <template #footer>
                    <view style="width:100%">
                        <EditorListItem style="width:100%" v-model="modifyParams.customer_id" placeholder="客户信息"
                            :options="customerList" :old-value="detail.contract?.customer_id"
                            :components-type="ComponentsType.SELECT" @modify="modifyContractInfo" />
                    </view>
                </template>
            </uni-list-item>
            <uni-list-item title="客户编号"
                :rightText="customerList?.find(item => item.id === modifyParams.customer_id)?.id || detail.contract?.customer_id">
            </uni-list-item>
            <uni-list-item title="签订日期" :rightText="detail.contract?.signed_at">
                <template #footer>
                    <view style="width:100%">
                        <EditorListItem style="width:100%" v-model="modifyParams.signed_at" placeholder="签订日期"
                            :old-value="detail.contract?.signed_at" :components-type="ComponentsType.DATEPICKER"
                            @modify="modifyContractInfo" :not-allow-null="true" />
                    </view>
                </template>
            </uni-list-item>
            <uni-list-item title="起始日期">
                <template #footer>
                    <view style="width:100%">
                        <EditorListItem style="width:100%" v-model="modifyParams.begin_at" placeholder="起始日期"
                            :old-value="detail.contract?.begin_at" :components-type="ComponentsType.DATEPICKER"
                            @modify="modifyContractInfo" :not-allow-null="true" />
                    </view>
                </template>
            </uni-list-item>
            <uni-list-item title="终止日期" :rightText="detail.contract?.end_at">
                <template #footer>
                    <view style="width:100%">
                        <EditorListItem style="width:100%" v-model="modifyParams.end_at" placeholder="终止日期"
                            :old-value="detail.contract?.end_at" :components-type="ComponentsType.DATEPICKER"
                            @modify="modifyContractInfo" :not-allow-null="false" />
                    </view>
                </template>
            </uni-list-item>
            <uni-list-item title="项目名称" :rightText="detail.contract?.prj_name || '-'">
            </uni-list-item>
            <uni-list-item title="项目编码" :rightText="detail.contract?.prj_id || '-'">
            </uni-list-item>
            <uni-list-item title="合同摘要" ellipsis="2" :note="detail.contract?.comment">
                <template #footer>
                    <view style="width:100%">
                        <EditorListItem style="width:100%" v-model="modifyParams.comment" placeholder="合同摘要"
                            :old-value="detail.contract?.comment" :components-type="ComponentsType.TEXTAREA"
                            @modify="modifyContractInfo" />
                    </view>
                </template>
            </uni-list-item>
        </uni-list>
        <uni-section title="收款约定" type="line" class="payment-section">
            <template v-slot:right>
                <view style="color: #007aff;display: flex;align-items: center;"
                    @click="redirectAddContractPaymentPage()">
                    <uni-icons :size="14" color="#007aff" type="plusempty"></uni-icons>
                    <text>添加</text>
                </view>
            </template>
        </uni-section>
        <uni-swipe-action ref="payment_swiper_action">
            <uni-swipe-action-item :right-options="payment_options" class="swipe-action-item" :threshold="20"
                v-for="(item, index) in detail.contract?.payments" :key="index"
                @click="(e: any) => handlerPaymentSwipeAction(e, item, index)">
                <uni-card margin="0" padding="0px" :title="item.condition" :extra="`${item.percent}%`" spacing="5px"
                    :is-shadow="false" :border="true" :sub-title="item.memo"
                    thumbnail="./../../../../../static/images/payment.png">
                    <view>
                        <view class="card-actions">
                            <text class="subtitle font-size-base">收款金额：<text class="font-size-base"
                                    style="color: #007aff;">{{
                                        Math.round(
                                            (detail.contract?.amount || 0) *
                                            item.percent *
                                            100
                                        ) / 10000
                                    }} 万元</text></text>
                            <text class="subtitle font-size-base">收款日期：<text class="paragraph font-size-sm">{{
                                item.expect_pay_date
                                    }}</text></text>

                        </view>
                    </view>
                </uni-card>
            </uni-swipe-action-item>
        </uni-swipe-action>
        <uni-section title="合同文档" type="line">
        </uni-section>
        <uni-list :border="true">
            <uni-swipe-action threshold="20" ref="swiper_action">
                <uni-swipe-action-item :right-options="options" @click="handlerRemoveFile(ContractTypeItem.DOC)"
                    :disabled="!detail.contract?.doc_uploaded">
                    <uni-list-item>
                        <template v-slot:body>
                            <view class="slot-box">
                                <i class="my my-doc" style="width: 40px;height: 40px;"></i>
                            </view>
                        </template>
                        <template v-slot:footer>
                            <view class="slot-content">
                                <view class="slot-panel"
                                    v-if="fileProgress.doc.showProgress || !detail.contract?.doc_uploaded">
                                    <view class="slot-title">打印件
                                    </view>
                                </view>
                                <view style="margin-left: auto;"
                                    v-if="!detail.contract?.doc_uploaded && !fileProgress.doc.showProgress">
                                    <uni-file-picker file-mediatype="all" :auto-upload="false" :limit="1"
                                        :file-extname="['doc', 'docx']" mode="list" :list-styles="{ display: 'none' }"
                                        @select="(e: any) => handlerSelectFileUpload(e, ContractTypeItem.DOC)"
                                        :del-icon="false">
                                        <button size="mini"
                                            style="color:#ffffff;background-color:#007aff;border-color:#007aff"
                                            hover-class="is-hover">上传</button>
                                    </uni-file-picker>
                                </view>
                                <view style="margin-left: auto;" v-if="fileProgress.doc.showProgress">
                                    <custom-progress v-model:value="fileProgress.doc.progress" :stroke-width="16"
                                        min-width="150px"></custom-progress>
                                </view>
                                <view v-if="!fileProgress.doc.showProgress && detail.contract?.doc_uploaded"
                                    style="font-size: 13px;display: flex;align-items: center;height: 100%;width:100%;justify-content: space-between;">
                                    <view>
                                        <view>
                                            {{ detail.contract?.doc_name }}
                                        </view>
                                    </view>
                                    <view
                                        style="margin-left: auto;display: flex; align-items: center;padding-left: 5px;">
                                        <uni-icons :size="30" color="#007aff" type="download"
                                            @click="startDownloadContractFile(ContractTypeItem.DOC, detail.contract?.doc_name)"
                                            style="color:#007aff;"></uni-icons>
                                    </view>
                                </view>
                            </view>
                        </template>
                    </uni-list-item>
                </uni-swipe-action-item>
                <uni-swipe-action-item :right-options="options" @click="handlerRemoveFile(ContractTypeItem.PDF)"
                    :disabled="!detail.contract?.pdf_uploaded">
                    <uni-list-item>
                        <template v-slot:body>
                            <view class="slot-box">
                                <i class="my my-pdf" style="width: 40px;height: 40px;"></i>
                            </view>
                        </template>
                        <template v-slot:footer>
                            <view class="slot-content">
                                <view class="slot-panel"
                                    v-if="fileProgress.pdf.showProgress || !detail.contract?.pdf_uploaded">
                                    <view class="slot-title">盖章扫描件
                                    </view>
                                </view>
                                <view style="margin-left: auto;"
                                    v-if="!detail.contract?.pdf_uploaded && !fileProgress.pdf.showProgress">
                                    <uni-file-picker file-mediatype="all" :auto-upload="false" :limit="1"
                                        :file-extname="['pdf']" mode="list" :list-styles="{ display: 'none' }"
                                        @select="(e: any) => handlerSelectFileUpload(e, ContractTypeItem.PDF)"
                                        :del-icon="false">
                                        <button size="mini"
                                            style="color:#ffffff;background-color:#007aff;border-color:#007aff"
                                            hover-class="is-hover">上传</button>
                                    </uni-file-picker>
                                </view>
                                <view style="margin-left: auto;" v-if="fileProgress.pdf.showProgress">
                                    <custom-progress v-model:value="fileProgress.pdf.progress" :stroke-width="16"
                                        min-width="150px"></custom-progress>
                                </view>
                                <view v-if="!fileProgress.pdf.showProgress && detail.contract?.pdf_uploaded"
                                    style="font-size: 13px;display: flex;align-items: center;height: 100%;width:100%;justify-content: space-between;">
                                    <view>
                                        <view>
                                            {{ detail.contract?.pdf_name }}
                                        </view>
                                    </view>
                                    <view
                                        style="margin-left: auto;display: flex; align-items: center;padding-left: 5px;">
                                        <uni-icons :size="30" color="#007aff" type="download"
                                            @click="startDownloadContractFile(ContractTypeItem.PDF, detail.contract?.pdf_name)"
                                            style="color:#007aff;"></uni-icons>
                                    </view>
                                </view>
                            </view>
                        </template>
                    </uni-list-item>
                </uni-swipe-action-item>
            </uni-swipe-action>
        </uni-list>

    </view>
</template>
<script setup lang="ts">

import EditorListItem from '@/components/editor-list-item/editor-list-item.vue'
import { ComponentsType, ContractTypeItem } from '@/enums/api'
import { ContractDetailResParams, ModifyContractReqParams, Payment } from '@/types/contract';
import { getContractDetail, getDownloadContractFileUrl, getUploadContractFileUrl, modifyContract, removeContractFile } from '@/api/project-center/contract';
import { useEmitt } from '@/logics/mitt/useEmitt';
import { Customer } from '@/types/customer';
import customProgress from '@/components/cu-progress/index.vue'

import { downloadFile, saveFile, uploadFile } from '@/api/base/client';

// const fileProgress = ref<{ type: ContractTypeItem; progress: number, showProgress: boolean }[]>(
//   [{
//     type: ContractTypeItem.DOC,
//     progress: 0,
//     showProgress: false
//   }]
// )
const swiper_action = ref()
const payment_swiper_action = ref()
const fileProgress = reactive<{

    [key: string]: {
        type: ContractTypeItem,
        progress: number,
        showProgress: boolean
    }
}>(
    {

        doc: {
            type: ContractTypeItem.DOC,
            progress: 0,
            showProgress: false
        },
        pdf: {
            type: ContractTypeItem.PDF,
            progress: 0,
            showProgress: false
        },
    }
)
// const clearFiles =
const props = defineProps({
    contract_id: {
        type: String,
        required: true
    },
    accountList: {
        type: Array as PropType<{ id: string; name: string }[]>,
    },
    customerList: {
        type: Array as PropType<Customer[]>,
    }
})


const { emitter } = useEmitt()

const modifyParams = ref<ModifyContractReqParams>({
    id: props.contract_id!
})

const detail = reactive<{ contract?: ContractDetailResParams }>({
    contract: undefined
}) // 合同详情

function calculateRemainingAmount(payments: Payment[], excludeIndex?: number): number {
    const totalPaidPercentage = payments.reduce((total, payment, index) => {
        // 如果当前的下标等于要排除的下标，则不累加其percent值
        if (index === excludeIndex) {
            return total;
        }
        return total + payment.percent;
    }, 0);
    console.log(100 - Math.round(totalPaidPercentage * 100) / 100)
    const percent = 100 - totalPaidPercentage
    return Math.round(percent * 100) / 100
}

//跳转添加收款约定页面
const redirectAddContractPaymentPage = () => {
    if ([undefined, null, '', 0].includes(detail.contract?.amount)) {
        uni.showToast({
            icon: 'error',
            title: '合同金额不足'
        })
        return
    }
    const amount = Number(detail.contract?.amount)
    const remainingPercentage = calculateRemainingAmount(detail.contract?.payments || [])
    if (remainingPercentage === 0) {
        uni.showToast({
            icon: 'none',
            title: '收款比例已用完'
        })
        return
    }
    uni.navigateTo({
        url: `/pages/profile/contract/add-payment?total_amount=${amount}&remaining_percentage=${remainingPercentage}`
    })
}

// swipe action操作。修改约定或删除收款约定
const handlerPaymentSwipeAction = async (e: { index: number }, payment: Payment, pIndex: number) => {
    payment_swiper_action.value?.closeAll()
    const { index } = e;
    const isEdit = index === 0;
    const isRemove = index === 1;
    if (isRemove) {
        detail.contract?.payments?.splice(pIndex, 1)
        await modifyContract({
            id: modifyParams.value.id,
            payments: detail.contract?.payments
        })
        uni.showToast(({
            icon: 'success',
            title: '修改成功'
        }))
        return
    }
    if (isEdit) {  // 跳转修改收款约定页面
        const amount = Number(detail.contract?.amount)
        const remainingPercentage = calculateRemainingAmount(detail.contract?.payments || [], pIndex)
        uni.navigateTo({
            url: `/pages/profile/contract/edit-payment?total_amount=${amount}&remaining_percentage=${remainingPercentage}`,
            success: () => {
                emitter.emit('editor_payment_item', {
                    index: pIndex,
                    payment: payment
                })
            }
        })
    }
}

// 获取项目合同详情
const getDetail = async () => {
    const contractDetail = await getContractDetail(props.contract_id)
    nextTick(() => {
        detail.contract = contractDetail
        modifyParams.value.name = contractDetail.name;
        modifyParams.value.amount = contractDetail.amount
        modifyParams.value.customer_id = contractDetail.customer_id
        modifyParams.value.comment = contractDetail.comment;
        modifyParams.value.payments = contractDetail.payments;
        modifyParams.value.begin_at = contractDetail.begin_at;
        modifyParams.value.end_at = contractDetail.end_at;
        modifyParams.value.handler_id = contractDetail.handler_id;
        modifyParams.value.signed_at = contractDetail.signed_at;
    })
}

watch(
    () => modifyParams.value.amount,
    () => {
        if (modifyParams.value.amount) {
            // modifyParams.value.amount = String(modifyParams.value.amount).replace(/[^\d]/g,'')
        }

    }
)

// 修改详情
const modifyContractInfo = async () => {
    const params = modifyParams.value
    console.log('modifyContractInfo')
    console.info(params)
    params.amount = Math.round(Number(params.amount) * 10000) / 10000
    try {
        await modifyContract(params)
        uni.showToast(({
            icon: 'success',
            title: '修改成功'
        }))
        emitter.emit('get_contract_list')
    } catch (e) {
        getDetail()
    }
}

// 获取上传进度信息
const onProgressResult = (e: UniApp.OnProgressUpdateResult | UniApp.OnProgressDownloadResult, type: ContractTypeItem) => {
    if (type === ContractTypeItem.DOC) {
        fileProgress.doc.showProgress = true
        fileProgress.doc.progress = e.progress
    } else {
        fileProgress.pdf.showProgress = true
        fileProgress.pdf.progress = e.progress
    }


}


const payment_options = [
    {
        text: '修改',
        style: {
            backgroundColor: '#4cd964',
            margin: "5px 0"
        }
    },
    {
        text: '删除',
        style: {
            backgroundColor: '#dd524d',
            margin: "5px 0"
        }
    }
]


const options = [
    {
        text: '删除',
        style: {
            backgroundColor: '#dd524d',
            margin: "5px 0"
        }
    }
]

// 选择合同上传文件，并上传
const handlerSelectFileUpload = async (e: {
    tempFilePaths: string[], tempFiles: {
        name: string
        extname: string
        url: string
    }[]
}, type: ContractTypeItem) => {
    try {
        const { tempFiles, tempFilePaths } = e
        if (tempFilePaths.length > 0) {
            const { url, form_data, headers, object_name } = await getUploadContractFileUrl({
                id: props.contract_id,
                type_id: type,
                filename: tempFiles[0].name
            })
            await uploadFile({ url, object_name, headers, formData: form_data, filePath: tempFilePaths[0], uploadProgress: onProgressResult, otherParams: type })
            uni.showToast({
                icon: 'success',
                title: '上传成功'
            })
            if (type === ContractTypeItem.DOC) {
                fileProgress.doc.showProgress = false
                fileProgress.doc.progress = 0
            } else {
                fileProgress.pdf.showProgress = false
                fileProgress.doc.progress = 0
            }
            getDetail()
        }
    } catch (_e) {
        if (type === ContractTypeItem.DOC) {
            fileProgress.doc.showProgress = false
            fileProgress.doc.progress = 0
        } else {
            fileProgress.pdf.showProgress = false
            fileProgress.doc.progress = 0
        }
    }

}

const startDownloadContractFile = async (type: ContractTypeItem, filename?: string) => {
    uni.showActionSheet({
        itemList: ['分享到好友', '添加到收藏'],
        success: async (res: UniApp.ShowActionSheetRes) => {
            await handlerDownloadContractFile(type, filename, res.tapIndex)
        }
    });

}




// 下载合同文件
const handlerDownloadContractFile = async (type: ContractTypeItem, filename?: string, sheetIndex?: number) => {
    try {
        const { url } = await getDownloadContractFileUrl({
            id: props.contract_id,
            type_id: type
        })
        const { savedFilePath } = await downloadFile({ url, downloadProgress: onProgressResult, otherParams: type, filename })
        await saveFile(savedFilePath, filename, sheetIndex)
        if (type === ContractTypeItem.DOC) {
            fileProgress.doc.showProgress = false
            fileProgress.doc.progress = 0
        } else {
            fileProgress.pdf.showProgress = false
            fileProgress.doc.progress = 0
        }
        getDetail()
    } catch (_e) {
        if (type === ContractTypeItem.DOC) {
            fileProgress.doc.showProgress = false
            fileProgress.doc.progress = 0
        } else {
            fileProgress.pdf.showProgress = false
            fileProgress.doc.progress = 0
        }
    }
}


/**
 * 删除合同文件
 * @param type 
 */
const handlerRemoveFile = async (type: ContractTypeItem) => {
    uni.showModal({
        title: '删除合同文件',
        content: `确认删除${type === ContractTypeItem.DOC ? '打印件' : '盖章扫描件'}？`,
        success: async (res: { confirm: boolean }) => {
            const { confirm } = res;
            if (confirm) {
                await removeContractFile({
                    id: props.contract_id,
                    type_id: type
                })
                uni.showToast({
                    icon: 'success',
                    title: '删除成功'
                })
                getDetail()
                swiper_action.value?.closeAll()
            }
        }
    })
}

onMounted(async () => {
    getDetail()
})

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
    name: 'add_payment',
    callback: async (payment: Payment) => {
        const payments = detail.contract?.payments || []
        payments.push(payment)
        try {
            await modifyContract({
                id: modifyParams.value.id,
                payments: payments
            })
            uni.showToast(({
                icon: 'success',
                title: '修改成功'
            }))
        } catch (e) {
            getDetail()
        }
    }
})


useEmitt({
    name: 'modify_payment',
    callback: async (e: { index: number, payment: Payment }) => {
        const { index, payment } = e;
        const payments = detail.contract?.payments || []
        payments.splice(index, 1, payment)
        try {
            await modifyContract({
                id: modifyParams.value.id,
                payments: payments
            })
            uni.showToast(({
                icon: 'success',
                title: '修改成功'
            }))
        } catch (e) {
            getDetail()
        }
    }
})

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

}
</script>
<style scoped>
.container {
    padding: 0 5px 40px 5px;
}

:deep(.uni-list-item__content) {
    flex-direction: row;
    align-items: center;
    flex: 0 0 80px;
}

:deep(.uni-list-item__content-title) {
    font-size: 13px;
    color: #3b4144a8;
}

:deep(.uni-list-item__extra) {
    flex: 1 1 auto;
}

:deep(.uni-list-item__extra-text) {
    color: #5d5959;
    font-size: 13px;
    width: 200px;
    text-overflow: ellipsis;
    text-align: right;
    text-wrap: wrap;
    overflow-wrap: anywhere;
    white-space-collapse: collapse;
}

:deep(.ayi-progress) {
    width: 200px;
    margin-left: auto;
}

:deep(.ayi-progress__text) {
    text-align: right !important;
    width: 50rpx !important;
}

:deep(.uni-section) {
    margin-top: 5px;
}

:deep(.payment-section .uni-section) {
    margin-top: 5px;
    border-bottom: 1px solid #EBEEF5;

}

.slot-box {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    align-items: center;
    width: 45px;
    /* background-color: rgb(201, 205, 212); */
    border-radius: 4px;
    margin-right: 10px;
    height: 45px;
}


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

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

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

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

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

}

:deep(.is-text-box) {
    display: none;
}

:deep(.uni-ellipsis) {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}

:deep(.uni-card__header-extra-text) {
    font-size: 16px !important;
    color: #3a3a3a !important;
    font-weight: bold !important;
}


.card-actions {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    height: 25px;
    line-height: 25px;
    font-size: 24rpx;
    padding: 5px 10px 0 10px;
}

.progress-actions {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
    height: 25px;
    line-height: 25px;
    font-size: 24rpx;
    padding: 5px 10px 0 10px;
}

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

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

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

.subtitle {
    color: #b2a9a6;
}
</style>