<template>
    <div class="main">
        <div class="container">
            <el-form :model="formData" ref="form" label-width="120px" :rules="rules"
                class="petty-form contract-description-form">
                <el-form-item label="借款缘由" prop="pettyReason">
                    <el-input placeholder="请输入借款缘由" v-model="formData.pettyReason"></el-input>
                </el-form-item>
                <el-form-item label="借款详情" prop="pettyDetails">
                    <el-input placeholder="请输入借款详情" v-model="formData.pettyDetails"></el-input>
                </el-form-item>
                <el-form-item label="借款金额" prop="pettyMoney">
                    <el-input placeholder="请输入借款金额" type="number" v-model="formData.pettyMoney"></el-input>
                </el-form-item>
                <el-form-item label="借款时间" prop="pettyTime">
                    <el-date-picker v-model="formData.pettyTime" align="right" type="datetime" placeholder="请输入借款时间"
                        format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="备注" prop="pettyRemarks">
                    <el-input placeholder="请输入备注" v-model="formData.pettyRemarks"></el-input>
                </el-form-item>
                <el-form-item label="申请附件">
                    <div  v-if="isEdit && filename" class="file-list" :style="{padding: '8px'}">
                        <div class="avator"><i class="el-icon-document"></i></div>
                        <div class="file-content" :title="filename">{{ filename }}</div>
                        <div class="file-operate">
                            <span class="" @click="handleDownload()">
                                <i class="el-icon-download"></i>
                            </span>
                        </div>
                    </div>
                    <div v-else-if="isEdit && !filename">无</div>
                    <el-upload v-else ref="uploadPettyFile" list-type="picture-card" :action="action" :file-list="fileList"
                        :on-change="uploadOnchange" :data="fileParams" :auto-upload="false" multiple
                        :limit="1" class='el-contract-upload'>
                        <i slot="default" class="el-icon-plus"></i>
                        <div slot="file" slot-scope="{file}" class="file-list">
                            <div class="avator"><i class="el-icon-document"></i></div>
                            <div class="file-content" :title="file.name">{{ file.name }}</div>
                            <div class="file-operate">
                                <span class="" @click="handleRemove(file)">
                                    <i class="el-icon-delete"></i>
                                </span>
                            </div>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addPettyMoneyRecord">{{isEdit ? '确认修改' : '确认申请'}}</el-button>
                    <el-button @click="back" v-if="isEdit">返回</el-button>
                </el-form-item>
            </el-form>

        </div>
    </div>
</template>
<script>
import { insertPettyMoneyRecord, selctByPettyId, updatePettyMoneyRecord } from '@/api/pettyMoney'
// import { deepClone } from '@/utils'
// import { contractNatures } from '../contractStaticData'
import { mapGetters } from 'vuex'
import { previewPDF } from '@/utils/download'
import { addRecordRules as rules, staticParams } from './pettyMoneyStaticData'
import { backPage } from '@/utils'
export default {
    // props: ['drawerVisible'],
    computed: {
        ...mapGetters([
            'companyId',
            'urId'
        ]),
        filename: function () {
            const { pettyEnclosure } = this.formData
            return pettyEnclosure.slice(pettyEnclosure.lastIndexOf('/') + 1, pettyEnclosure.length)
        }
    },
    data() {
        return {
            rules: rules,
            formData: {
                ...staticParams,
                userId: this.urId, //谁借的
                companyId: this.companyId, //公司id
                pettyState: 2,//状态0待还款1已还清2无需偿还
                pettyApproval: 0, //0待审批1通过2驳回
            },
            fileList: [],
            fileParams: {},
            action: '',
            uploadChange: false,
            isEdit: false,
            deleteFiles: []
        }
    },
    created() {
        this.action = process.env.VUE_APP_BASE_API + '/file/updataPettyFile'
    },
    mounted() {
        const { pettyId } = this.$route.query
        // 编辑
        if (this.$route.path.indexOf('/editPetty') >= 0 && pettyId) {
            this.isEdit = true;
            this.getPettytDetail(pettyId)
            // this.getPettyFiles(pettyId)  //获取合同文件
            // 添加
        } else if (this.$route.path.indexOf('/addPettyMoneyRecord') >= 0) {
            this.isEdit = false;
        } else {
            this.$router.back()
        }
        // console.log(1)
    },
    methods: {
        // back(){
        //     this.$store.dispatch("tagsView/delView", this.$route);
        //     this.$router.back();
            
        // },
        addPettyMoneyRecord() {
            
            this.$refs.form.validate(valida => {
                if (valida) {
                    const params = {
                        ...this.formData,
                        userId: this.urId,
                        companyId: this.companyId,
                        pettySurplus: this.formData.pettyMoney
                    }
                    // [pettyMoney为空, userId为空, companyId为空, pettyApproval为空, pettyState为空]
                    if (this.isEdit) {
                        updatePettyMoneyRecord(params).then(res => {
                            if (res.success) {
                                //this.addPettyFile(params.pettyId)
                                this.$message.success("修改成功")
                                setTimeout(() => {
                                    backPage.call(this)
                                }, 500);
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    } else {
                        insertPettyMoneyRecord(params).then(res => {
                            if (res.success) {

                                this.addPettyFile(res.data)
                                this.$message.success("申请成功")
                                setTimeout(() => {
                                    backPage.call(this)
                                }, 500);
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    }
                }
            })
        },
        uploadOnchange(file, fileList) {
            const index = this.fileList.findIndex(item => item.uid === file.uid)
            if (index >= 0) {
                this.fileList.splice(index, 1)
            } else {
                this.fileList.push(file)
            }
        },
        addPettyFile(pettyId) {
            this.fileParams.Id = pettyId
            this.fileParams.companyId = this.companyId
            this.$refs.uploadPettyFile.submit()
        },
        handleDownload() {
            let { pettyEnclosure: filePath } = this.formData
            previewPDF(filePath)
        },

        handleRemove(file) {
            const index = this.fileList.findIndex(item => item.uid === file.uid)
            if (index >= 0) {
                const deleteFile = this.fileList.splice(index, 1)
                if (deleteFile.length) {
                    this.deleteFiles.push(deleteFile[0])
                }
            }
        },
        getPettytDetail(pettyId) {
            if (pettyId) {
                const params = {
                    pettyId,
                    userId: this.urId
                }
                selctByPettyId(params).then(res => {
                    if (res.success) {
                        this.formData = Object.assign({}, this.formData, res.data)
                        const { pettyEnclosure } = res.data
                        pettyEnclosure && (this.fileList = [{
                            name: pettyEnclosure.slice(pettyEnclosure.lastIndexOf('/') + 1, pettyEnclosure.length),
                            filePath: pettyEnclosure
                        }])
                    } else {
                        this.$message.warning("获取备用金详情失败")
                    }
                })
                // get()
            }
        },
        getPettyFiles(pettyId) {
            const params = {
                pettyId
            }
            // selectContractFiles(params).then(res => {
            //     if (res.success) {
            //         this.fileList = res.data.map(item => {
            //             item.name = item.filePath.slice(item.filePath.lastIndexOf('/') + 1, item.filePath.length)
            //             return item
            //         })
            //     } else {
            //         this.fileList = []
            //     }
            // })
        },
    }
}
</script>
<style scoped lang="scss">
.main {
    .header {
        padding: 25px 15px;
    }

    .container {
        padding: 15px 0;

        .petty-form {
            width: 50%;
        }

    }
}



.file-list {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 250px;
    padding: 0 5px;
    border: 1px solid #e6ebf5;
    border-radius: 5px;

    .avator {
        width: 10%;
        font-size: 32px;
        color: #d75b5b;
    }

    .file-content {
        width: 80%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding-left: 10px;
    }

    .file-operate {
        width: 15%;
        font-size: 16px;
        display: flex;
        justify-content: space-around;
        align-items: center;

        span {
            cursor: pointer;
        }

    }

}
</style>