<template>
    <div class="case-repayment-certificate">
        <div class="mb-16 flex-row justify-content-between">
            <span class="f-weight500 f18">还款凭证</span>
            <span class="cursor-pointer" @click="AddFlag = true;repaymentObj = {mediaPath:[]}"><i class="el-icon-plus"></i> 添加还款凭证</span>
        </div>
        <div v-if="AddFlag" class="case-detail-des flex-column mb-16 p-16 border-radius-8">
            <div class="flex-column justify-content-between">
                <el-form ref="ruleFormRepayment"
                    :model="repaymentObj" 
                    :rules="rulesClientRepayment" 
                    label-width="130px">
                    <el-form-item label="凭证金额" prop="amount">
                        <el-input class="inputpaddingtop2" 
                            size="small"
                            placeholder="请输入凭证金额"
                            v-model="repaymentObj.amount">
                            <template slot="append">元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="还款日期" prop="paybackTime">
                        <el-date-picker class="width100" size="small"
                            v-model="repaymentObj.paybackTime"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="备注说明" prop="remark">
                        <el-input 
                            size="small"
                            clearable
                            placeholder="请输入备注说明"
                            v-model="repaymentObj.remark">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="凭证" prop="mediaPath">
                        <upload-file :file-list="fileList" :max-count="1"
                                    :show-file-name="false"
                                    uploadName="支持图片大小不超过10M"
                                    accept=".jpg,.png,.jpeg"
                                    :span="6"
                                    :fileSize="10"
                                    @handleUploadFile="handleUploadFile">
                        </upload-file>
                    </el-form-item>
                    <el-form-item label="">
                        <el-button @click="AddFlag = false;fileList=[]" size="small">取消</el-button>
                        <el-button type="primary" @click="handleSubmitRepayment()" size="small">保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <div class="case-detail-des flex-column mb-16 p-16 border-radius-8" v-for="(proofitem,index) in ProofList" :key="index">
            <div class="flex-column justify-content-between">
                <el-form v-if="updateRow != index" label-width="130px">
                    <div class="flex-column justify-content-between m-8">
                        <div class="flex-column">
                            <div class="flex-row certImagecont">
                                <span class="color-86909C certImage">
                                    <el-image 
                                        :src="proofitem.previewUrl" 
                                        :preview-src-list="[proofitem.previewUrl]">
                                    </el-image>
                                </span>
                                <div class="flex-column ml-16">
                                    <span class="color-86909C">上传者：{{ proofitem.uploaderName }}<a></a></span>
                                    <span class="color-86909C mt-8">上传时间：<a>{{ proofitem.createAt }}</a></span>
                                </div>
                            </div>
                            <span class="color-86909C mt-8 pt12-pb10">凭证金额：<a>{{ (proofitem.amount == 0 ?'' : proofitem.amount) }}</a>{{ (proofitem.amount != null&&proofitem.amount != 0) ? '元' : '' }}</span>
                            <span class="color-86909C mt-8 pt12-pb10 bgColor-F7F8FA">还款日期：<a>{{ proofitem.paybackTime | formaDate('yyyy-MM-dd hh:mm:ss') }}</a></span>
                            <span class="color-86909C mt-8 pt12-pb10">备注说明：<a>{{ proofitem.remark }}</a></span>
                        </div>
                        <div class="mt-8">
                            <el-popover v-if="proofitem.status.code == 1"
                                placement="left"
                                width="400"
                                title="凭证效验"
                                trigger="click"
                                v-model="proofitem.visible">
                                <el-form class="mt-8" :ref="`ruleFormEffect${index}`"
                                    :model="proofitem" 
                                    :rules="rulesClientRepayment" 
                                    label-width="130px">
                                    <el-form-item label="凭证金额" prop="amount" style="margin-bottom: 10px;">
                                        <el-input class="inputpaddingtop2" 
                                            size="small"
                                            placeholder="请输入凭证金额"
                                            v-model="proofitem.amount">
                                            <template slot="append">元</template>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item label="还款日期" prop="paybackTime" style="margin-bottom: 10px;">
                                        <el-date-picker class="width100" size="small"
                                            v-model="proofitem.paybackTime"
                                            type="date"
                                            placeholder="选择日期"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            format="yyyy-MM-dd">
                                        </el-date-picker>
                                    </el-form-item>
                                    <el-form-item label="备注说明" prop="remark" style="margin-bottom: 10px;">
                                        <el-input 
                                            size="small"
                                            clearable
                                            placeholder="请输入备注说明"
                                            v-model="proofitem.remark">
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item label="">
                                        <el-button type="primary" @click="handleSubmitEffect(proofitem,('ruleFormEffect'+index),index)" size="small">保存</el-button>
                                        <el-button type="primary" @click="proofitem.visible = false" size="small">取消</el-button>
                                    </el-form-item>
                                </el-form>
                                <span slot="reference" class="color-86909C cursor-pointer"><i class="el-icon-medal"></i>&nbsp;效验</span>
                            </el-popover>
                            <span class="color-86909C ml-16 cursor-pointer" v-if="proofitem.status.code == 1" @click="handEffectCancel(proofitem)"><i class="el-icon-warning-outline"></i>&nbsp;取消</span>
                            <span class="color-86909C ml-16 cursor-pointer" v-if="proofitem.status.code != 1" @click="updateClick(index,proofitem)"><i class="el-icon-edit"></i>&nbsp;编辑</span>
                            <span class="color-86909C ml-16 cursor-pointer" v-if="proofitem.status.code != 1" @click="DeleteClick(proofitem)"><i class="el-icon-delete"></i>&nbsp;删除</span>
                        </div>
                    </div>
                </el-form>
                <el-form v-if="updateRow > -1 && index == updateRow" ref="ruleFormRepaymentUpdate"
                    :model="repaymentObj" 
                    :rules="rulesClientRepayment" 
                    label-width="130px">
                    <el-form-item label="凭证金额" prop="amount">
                        <el-input class="inputpaddingtop2" 
                            size="small"
                            placeholder="请输入凭证金额"
                            v-model="repaymentObj.amount">
                            <template slot="append">元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="还款日期" prop="paybackTime">
                        <el-date-picker class="width100" size="small" 
                            v-model="repaymentObj.paybackTime"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="备注说明" prop="remark">
                        <el-input 
                            size="small"
                            clearable
                            placeholder="请输入备注说明"
                            v-model="repaymentObj.remark">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="凭证" prop="mediaPath">
                        <upload-file :file-list="fileList" :max-count="1"
                                    :show-file-name="false"
                                    uploadName="支持图片大小不超过10M"
                                    accept=".jpg,.png,.jpeg"
                                    :span="6"
                                    :fileSize="10"
                                    @handleUploadFile="handleUploadFile">
                        </upload-file>
                    </el-form-item>
                    <el-form-item label="" v-if="updateRow > -1 && index == updateRow">
                        <el-button @click="updateRow = -1" size="small">取消</el-button>
                        <el-button type="primary" @click="handleSubmitUpdate()" size="small">保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        
    </div>
</template>
<script>
import api from "@/services/caseManagement";
    export default {
        components: {
            uploadFile: () => import('@/components/uploadFile.vue'),//上传
        },
        props: {
            eventDialog: {
                type: Object,
                default: () => {
                    return {}
                },
            },
        },
        data() {
            return {
                AddFlag:false,
                updateRow:-1,
                repaymentObj:{
                    mediaPath:[]
                },
                rulesClientRepayment:{
                    amount: [
                        { required: true, message: '请输入还款金额', trigger: 'change',},
                        { pattern: /^[1-9]\d*(,\d{3})*(\.\d{1,2})?$|^0.\d{1,2}$/, message: '请输入大于0且最多2位小数金额', trigger: ['blur', 'change']}
                    ], 
                    paybackTime: [
                        { required: true, message: '请选择还款日期', trigger: 'change',},
                    ], 
                    mediaPath: [
                        { required: true, message: '请上传文件', trigger: 'change',},
                    ], 

                    
                },
                ProofList:[],
                fileList:[],

            };
        },
        mounted () {
            this.getProofList()
        },
        methods: {
            
            handleSubmitRepayment(){
                this.$refs.ruleFormRepayment.validate((valid) => {
                    if (valid){
                        this.repaymentObj.caseId = this.eventDialog.caseId
                        this.repaymentObj.proofUrl = this.repaymentObj.mediaPath[0]
                        
                        api.gettraceProof_create(this.repaymentObj).then(res => {
                            if(!res.code){
                                this.AddFlag = false
                                this.updateRow = -1
                                this.fileList = []
                                this.getProofList()
                            }
                        })
                    }
                })
            },
            getProofList(){
                api.gettraceProof_list({caseId:this.eventDialog.caseId}).then(async res => {
                     if(!res.code){
                        await this.getpreviewfull(res)
                     }
                })
            },
            async getpreviewfull(fileList) {
                this.ProofList = []
                for (const item of fileList) {
                    try {
                        item.previewUrl = await this.$fetchApi.viewFullFile({path: item.proofUrl})
                        item.mediaPath = [item.proofUrl]
                        item.visible = false
                        this.ProofList.push(item);
                    } catch (error) {
                    console.error(`调用接口失败，错误:`, error);
                    // 可以在这里添加重试逻辑
                    }
                }
            },
            
            async getProofFile(url){
                let previewUrl = await this.$fetchApi.viewFullFile({path: url})
                return previewUrl
            },

            updateClick(index,proofitem){
                this.updateRow = index;
                this.repaymentObj = JSON.parse(JSON.stringify(proofitem))
                this.repaymentObj.mediaPath = [proofitem.proofUrl]
                this.fileList = [{url: proofitem.proofUrl,fileName:'上传'}]
            },
            // 效验
            handleSubmitEffect(proofitem,formName,indexnum){
                this.$refs[formName][0].validate((valid) => {
                    if (valid){
                        proofitem.createAt =undefined
                        proofitem.createBy =undefined
                        proofitem.delFlag =undefined
                        proofitem.planId =undefined
                        // proofitem.status =undefined
                        proofitem.updateAt =undefined
                        proofitem.updateBy =undefined
                        proofitem.uploaderName =undefined
                        proofitem.caseId =undefined
                        proofitem.proofUrl =undefined
                        api.gettraceProof_valid(proofitem).then(res => {
                            if(!res.code){

                                this.ProofList.forEach((item,index) =>{
                                    if(index == indexnum){item.visible = false}
                                })
                                this.getProofList()
                            }
                        })
                    }
                })
            },
            // 取消效验
            handEffectCancel(proofitem){
                this.$confirm("请确定是否取消效验这些数据?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    if(!this.$clickThrottle()) { return }//防止重复点击
                    let data = {
                        id:proofitem.id
                    }
                    api.gettraceProof_cancel(data).then((res) => {
                        this.$message.success("取消成功");
                        this.getProofList()
                    });
                }).catch(() => {});
            },
            // 删除
            DeleteClick(proofitem){

                this.$confirm("请确定是否删除这些数据?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    if(!this.$clickThrottle()) { return }//防止重复点击
                    let data = {
                        id:proofitem.id
                    }
                    api.gettraceProof_delete(data).then((res) => {
                        this.$message.success("删除成功");
                        this.getProofList(1)
                       
                    });
                }).catch(() => {});
            },
            handleSubmitUpdate(){
                this.$refs.ruleFormRepaymentUpdate[0].validate((valid) => {
                    if (valid){
                        this.repaymentObj.createAt =undefined
                        this.repaymentObj.createBy =undefined
                        this.repaymentObj.delFlag =undefined
                        this.repaymentObj.planId =undefined
                        this.repaymentObj.status =undefined
                        this.repaymentObj.updateAt =undefined
                        this.repaymentObj.updateBy =undefined
                        this.repaymentObj.uploaderName =undefined
                        this.repaymentObj.proofUrl = this.repaymentObj.mediaPath[0]
                        api.gettraceProof_edit(this.repaymentObj).then(res => {
                            if(!res.code){
                                this.updateRow = -1
                                this.fileList = []
                                this.getProofList()
                            }
                        })
                    }
                })
            },
            
            handleUploadFile(fileList){
                // console.log('获取上传文件信息',fileList)
                fileList = JSON.parse(JSON.stringify(fileList))
                this.fileList = fileList.map((item,i) => {
                    return {
                        url: item.url,
                        fileName:'上传',
                        previewUrl:item.previewUrl
                    }
                })
                this.repaymentObj.mediaPath = this.fileList.map((item) => item.url);
            },


            //  
            handleClose() {
                this.$emit('update:eventTraDialog', null)
            },
        }
    };
</script>
<style scoped lang="scss">
.case-repayment-certificate{
    .case-detail-des{
        border:solid 1px #E5E6EB;
        .el-form-item{margin-bottom: 13px;}
        .inputpaddingtop2{padding-top:3px}
        .certImagecont{
            padding: 10px;
            border-radius: 8px;
            background-color: #F2F3F5;
        }
        .bgColor-F7F8FA{
              background-color: #F7F8FA;
            }
            .pt12-pb10{
                padding: 12px 10px;
            }
            

        // span:nth-child(even) {
        //     background-color: #F7F8FA;
        //   }
        .certImage{
            width: 60px; height: 60px; text-align: center;line-height: 60px;
            .el-image{
                max-width: 100%;
                max-height: 100%;
            }
        }
    }
}
</style>
<style  lang="scss">
.case-repayment-certificate{
    .case-detail-des{
        .el-image__inner{
            max-width: 60px;
            max-height: 60px;
        }
    }
}
</style>
