<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="申请附件">
                    <el-upload ref="uploadPettyFile" list-type="picture-card" :action="action" :file-list="fileList"
                        :on-change="uploadOnchange" :data="fileParams" :auto-upload="false" multiple accept='.pdf'
                        :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="handleDownload(file)">
                                    <i class="el-icon-download"></i>
                                </span>
                            </div>
                        </div>
                        <!-- <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传pdf文件，且不超过500kb</div> -->
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addPettyMoneyRecord">{{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 { downloadPDFFile } from '@/utils/download'
import { addRecordRules as rules, staticParams } from './pettyMoneyStaticData'
export default {
    // props: ['drawerVisible'],
    computed: {
        ...mapGetters([
            'companyId',
            'urId'
        ]),
    },
    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
        }
    },
    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: {
        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(() => {
                                    this.$router.push('/pettyMoneyRecord')
                                }, 500);
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    } else {
                        insertPettyMoneyRecord(params).then(res => {
                            if (res.success) {
                                this.addPettyFile(res.data)
                                this.$message.success("申请成功")
                                setTimeout(() => {
                                    this.$router.push('/pettyMoneyRecord')
                                }, 500);
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    }
                }
            })
        },
        uploadOnchange(file, fileList) {
            this.uploadChange = true
        },
        addPettyFile(pettyId) {
            this.fileParams.Id = pettyId
            this.uploadChange && this.$refs.uploadPettyFile.submit()
        },
        handleDownload(file) {
            let { name, filePath } = file
            let url = process.env.VUE_APP_BASE_API + filePath;
            downloadPDFFile(url, name)
        },
        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;

    .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>