<template>
    <el-dialog class="client-data-dialog" :title="title" width="60%" :visible.sync="visible"
               :before-close="handleClose">

        <el-form :model="loanRecordData" ref="loanRecordForm" :label-width="'100px'">
            <el-input type="hidden" v-model="clientNo"></el-input>
            <el-input type="hidden" v-model="loanType"></el-input>
            <el-input type="hidden" v-model="loanNo"></el-input>

            <table style="width: 100%">
                <tr>
                    <th>客户姓名</th>
                    <td style="width: 35%">
                        <el-input v-model="clientName" :disabled="true"></el-input>
                    </td>
                    <th>身份证</th>
                    <td style="width: 35%">
                        <el-input v-model="certNo" :disabled="true"></el-input>
                    </td>
                </tr>
                <tr>
                    <th>最高额度</th>
                    <td>{{client.topAmt}}
                    </td>
                    <th>借款利率</th>
                    <td>{{client.rate}}
                    </td>
                </tr>
                <tr>
                    <th>借款金额</th>
                    <td colspan="3">
                        <el-input placeholder="合同金额" v-model="loanAmt" style="width: 20%" @change="moneyCalculate"/>
                        <el-input placeholder="到账金额" v-model="backAmt" style="width: 20%" @change="moneyChange"/>
                        <el-input placeholder="利息" v-model="rateAmt" style="width: 20%" @change="moneyChange"/>
                        <el-input placeholder="服务费" v-model="serviceAmt" style="width: 20%" @change="moneyChange"/>
                    </td>
                </tr>
                <tr>
                    <th>借款日期</th>
                    <td colspan="3">
                        <div style="display: inline-block">
                            <el-date-picker type="date" placeholder="借款日期" v-model="startDate" style="width: 30%"
                                            @change="dateChange"/>
                            <el-input placeholder="还款日期" :disabled="true" v-model="endDate" style="width: 30%"/>
                            <el-select v-model="loanLife" placeholder="借款期限" style="width: 30%" @change="dateChange">
                                <el-option v-for="item in loanLifeOpts" :key="item.value" :label="item.name"
                                           :value="item.value"></el-option>
                            </el-select>
                        </div>
                    </td>
                </tr>

                <tr>
                    <th>业务组</th>
                    <td>
                        <el-autocomplete style="width: 80%"
                                         v-model="bizGroup"
                                         :fetch-suggestions="querySearchBiz"
                                         placeholder="请选择"
                                         @select="handleSelectBiz"
                        ></el-autocomplete>
                    </td>
                    <th>所属BD</th>
                    <td style="width: 35%">
                        <el-input v-model="loginName" :disabled="true"></el-input>
                    </td>
                </tr>

                <tr>
                    <th>出借人</th>
                    <td>
                        <el-input placeholder="出借人" :disabled="true" v-model="lendCard"/>
                        <el-input type="hidden" v-model="lendCardId"></el-input>
                    </td>
                </tr>
                <tr>
                    <th>银行名称</th>
                    <td v-if="!isCardSign">
                        <el-input placeholder="银行名称（客户）" v-model="openBankName"/>
                    </td>
                    <td v-if="isCardSign">
                        {{openBankName}}
                    </td>

                    <th>银行卡号</th>
                    <td v-if="!isCardSign">
                        <el-input placeholder="银行卡号（客户）" v-model="bankAccount"/>
                    </td>
                    <td v-if="isCardSign">
                        {{bankAccount}}
                    </td>
                </tr>

                <tr>
                    <th>开户行</th>
                    <td v-if="!isCardSign">
                        <el-input placeholder="开户行（客户）" v-model="openSubBankName"/>
                    </td>
                    <td v-if="isCardSign">
                        {{openSubBankName}}
                    </td>
                    <th>是否签约</th>
                    <td>
          <span v-if="isCardSign" style="font-weight: bold;color: #ffa23b;font-size: 20px;">
             签约成功
            </span>
                        <span v-if="!isCardSign" style="font-weight: bold;color: #ff150c;font-size: 20px;">
              未签约
            </span>
                    </td>
                </tr>

                <tr>
                    <th>违约责任</th>
                    <td colspan="3">
                        <el-input placeholder="违约责任" v-model="dutyDesc"/>
                    </td>
                </tr>
                <tr>
                    <th>操作意见</th>
                    <td colspan="3">
                        <el-input placeholder="操作意见" v-model="memo"/>
                    </td>
                </tr>
                <tr>
                    <th>备注</th>
                    <td colspan="3">
                        {{client.memo}}
                    </td>
                </tr>

                <tr>
                    <th>客户资料</th>
                    <td colspan="5">
                        <el-upload v-if="openUserImg"
                                   list-type="picture-card"
                                   :multiple="true"
                                   :action="oss.action"
                                   :data="oss.data"
                                   :before-upload="handleBeforeUpload"
                                   :on-success="handleUserSuccess"
                                   accept=".jpeg,.jpg,.png"
                                   :on-remove="handleUserRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>


                        <template v-for="userAttach in userAttachs">
                            <a :href="userAttach.attachUrl" target="_blank">
                                <img :src="userAttach.attachUrl" style="padding-right: 2px;" width="150px"
                                     height="200px"/>
                            </a>
                        </template>

                    </td>
                </tr>

                <tr>
                    <th>借款资料</th>
                    <td colspan="5">
                        <el-upload
                                list-type="picture-card"
                                :multiple="true"
                                :action="oss.action"
                                :data="oss.data"
                                accept=".jpeg,.jpg,.png"
                                :before-upload="handleBeforeApplyUpload"
                                :on-success="handleLoanApplySuccess"
                                :on-remove="handleLoanApplyRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </td>
                </tr>
            </table>
        </el-form>

        <div slot="footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button v-if="type === 'ADD'" type="primary" @click="createClick" :loading="ui.submitLoading">新增借条</el-button>
            <el-button v-if="type === 'EDIT'" type="primary" @click="editClick" :loading="ui.submitLoading">编辑借条</el-button>
            <el-button type="primary" @click="submitClick" :loading="ui.submitLoading">提交审核</el-button>
        </div>
    </el-dialog>
</template>

<script type="text/ecmascript-6">

    import * as moment from "moment";


    export default {
        name: 'LoanInfoDialog',
        props: {
            dialogVisible: {
                type: Boolean,
                required: true
            },
            type: {
                type: String,
                required: true
            },
            client: {
                type: Object,
                required: true,
            },
            loanType: {
                type: String,
                required: true
            },
            loanRecord: {
                type: Object
            }
        },
        data() {
            return {
                openUserImg: true,
                userUrl: '',
                loanApplyUrl: '',
                userImgs: [],
                loanApplyImgs: [],
                userAttachs: [],
                loanNo: '',
                clientNo: '',
                clientName: '',
                isCardSign: '',
                certNo: '',
                loanAmt: '',
                backAmt: '',
                rateAmt: '',
                serviceAmt: '',
                startDate: '',
                endDate: '',
                loanLife:'',
                loanLifeOpts: [{value: 28, name: 28},{value: 23, name: 23},{value: 20, name: 20},{value: 18, name: 18},{value: 15, name: 15}, {value: 10, name: 10}, {value: 7, name: 7}],
                saler: '',
                salerKey: '',
                salers: [],
                lendCard: '',
                lendCardId: '',
                openBankName: '',
                bankAccount: '',
                openSubBankName: '',
                dutyDesc: '如到期当日未还款，将按日收取逾期客户管理费。',
                memo: '',
                visible: this.$props.dialogVisible,
                value: '',
                bizGroup: '',
                bizGroups: [{value: '', lable: '', dataName: '', dataId: ''}],
                loanRecordData: {},
                ui: {
                    submitLoading: false
                },
                loginName: '',
                allUser: [],
                oss: {
                    action: '',
                    data: {},
                },
            }
        },

        created: function () {




            //初始化业务组
            this.$$get(`/card/lendList`)
                .then(res => {
                    if (res.data.code < 1)
                        throw res.data.msg;
                    var array = []
                    res.data.data.forEach((item, index) => {
                        array[index] = {
                            value: item.relationNo,
                            lable: item.relationNo,
                            dataName: item.ownerName,
                            dataId: item.id
                        }
                    })
                    this.bizGroups = array;
                })
                .catch(err => this.$$msg.err(err))

            /** 初始化数据 */
            this.clientName = this.client.clientName;
            this.certNo = this.client.certNo;
            this.clientNo = this.client.clientNo;
            this.loanLife=this.client.life;

            if (this.client.cardBean != null) {
                this.openBankName = this.client.cardBean.openBankName;
                this.bankAccount = this.client.cardBean.bankAccount;
                this.openSubBankName = this.client.cardBean.openSubBankName;
            }


            this.$$get(`/client/isCardSign/` + this.clientNo)
                .then(res => {
                    if (res.data.code < 1)
                        throw res.data.msg;
                    this.isCardSign = res.data.data;
                })
                .catch(err => this.$$msg.err(err))

            if (this.type === 'EDIT') {
                this.$$get(`/loanRecord/getInfo/${this.loanRecord.loanNo}`)
                    .then(res => {
                        if (res.data.code < 1)
                            throw res.data.msg;
                        this.loanNo = res.data.data.loanNo;
                        this.loanAmt = res.data.data.loanAmt;
                        this.backAmt = res.data.data.backAmt;
                        this.rateAmt = res.data.data.rateAmt;
                        this.serviceAmt = res.data.data.serviceAmt;
                        this.startDate = res.data.data.startDate;
                        this.endDate = moment(res.data.data.endDate, 'YYYY-MM-DD').format('YYYY-MM-DD');
                        this.loanLife = res.data.data.loanLife;
                        this.bizGroup = res.data.data.bizGroup;
                        this.bizGroups.forEach((item, index) => {
                            if (item.lable === this.bizGroup) {
                                this.lendCard = item.dataName
                                this.lendCardId = item.dataId
                            }
                        })
                        if (res.data.data.cardBean != null) {
                            this.openBankName = res.data.data.cardBean.openBankName;
                            this.bankAccount = res.data.data.cardBean.bankAccount;
                            this.openSubBankName = res.data.data.cardBean.openSubBankName;
                        }
                        this.dutyDesc = res.data.data.loanExtBean.dutyDesc;
                        this.memo = res.data.data.memo;
                        this.saler = res.data.data.saler;
                        var userAttachTemp = res.data.data.userAttachList;
                        for (var i in  userAttachTemp) {
                            this.userAttachs[this.userAttachs.length] = {attachUrl: userAttachTemp[i].attachUrl}
                            this.openUserImg = false
                        }
                    })
                    .catch(err => this.$$msg.err(err))
            }
        },
        computed: {
            title() {
                if (this.type === 'ADD') return '借条新增';
                else if (this.type === 'EDIT') return '借条修改'
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.createUrl();
            })

            /** 初始化用户数据 **/
            this.$$get(`/user/select`)
                .then(res => {
                    if (res.data.code < 1)
                        throw res.data.msg;
                    var array = []
                    res.data.data.forEach((item, index) => {
                        array[index] = {value: item.userName, lable: item.loginName,}
                    })
                    this.allUser = array;
                })
                .catch(err => this.$$msg.err(err))
            this.saler = localStorage.getItem("loginName");
            this.loginName = localStorage.getItem("userName")
        },

        methods: {
            querySearchAsync(queryString, cb) {
                var allUser = this.allUser;
                var results = queryString ? allUser.filter(this.createStateFilter(queryString)) : allUser;
                cb(results);
            },
            handleSelect(item) {
                this.salerKey = item.lable;
            },
            createStateFilter(queryString) {
                return (state) => {
                    return (state.value.toLowerCase().search(queryString.toLowerCase()) >= 0);
                };
            },

            querySearchBiz(queryString, cb) {
                var allUser = this.bizGroups;
                var results = queryString ? allUser.filter(this.createStateFilter(queryString)) : allUser;
                cb(results);
            },
            handleSelectBiz(item) {
                this.bizGroup = item.lable;
                this.bizGroups.forEach((item, index) => {
                    if (item.lable === this.bizGroup) {
                        this.lendCard = item.dataName
                        this.lendCardId = item.dataId
                    }
                })
            },
            createUrl() {
                let http = window.location.protocol;
                let host = window.location.host;
                this.userUrl = `${http}//${host}/api/upload/loanUser`
                this.loanApplyUrl = `${http}//${host}/api/upload/loanApply`
            },


            handleBeforeUpload(file) {
                var attachType = 'LOAN_USER'
                return this.$$get(`/oss/signature/` + attachType + "/" + file.name).then(res => {
                    if (res.data.code < 1) {
                        this.$message.error(res.data.msg);
                        return
                    }
                    const result = res.data.data;
                    const data = {};
                    const tempOss = {};
                    data.OSSAccessKeyId = result.accessId;
                    data.policy = result.policy;
                    data.Signature = result.signature;
                    data.key = result.dir;
                    tempOss.action = result.host;
                    tempOss.data = data;
                    this.oss = tempOss;
                    this.userImgs[this.userImgs.length] = {attachPath: result.dir, attachName: file.name}
                });
            },
            handleUserSuccess(res, file, fileList) {
                this.$notify({title: '成功', message: file.name + ",上传成功", type: 'success'});
            },
            handleUserRemove(res, file, fileList) {
                var array = []
                var num = 0;
                for (var userImgNum in this.userImgs) {
                    if (this.userImgs[userImgNum].attachName != res.name) {
                        array[num] = this.userImgs[userImgNum]
                        num = num + 1
                    }
                }
                this.userImgs = array
            },


            handleBeforeApplyUpload(file) {
                var attachType = 'LOAN_APPLY'
                return this.$$get(`/oss/signature/` + attachType + "/" + file.name).then(res => {
                    if (res.data.code < 1) {
                        this.$message.error(res.data.msg);
                        return
                    }
                    const result = res.data.data;
                    const data = {};
                    const tempOss = {};
                    data.OSSAccessKeyId = result.accessId;
                    data.policy = result.policy;
                    data.Signature = result.signature;
                    data.key = result.dir;
                    tempOss.action = result.host;
                    tempOss.data = data;
                    this.oss = tempOss;
                    this.loanApplyImgs[this.loanApplyImgs.length] = {attachPath: result.dir, attachName: file.name}
                });
            },

            handleLoanApplySuccess(res, file, fileList) {
                this.$notify({title: '成功', message: file.name + ",上传成功", type: 'success'});
            },

            handleLoanApplyRemove(res, file, fileList) {
                var array = []
                var num = 0;
                for (var imgNum in this.loanApplyImgs) {
                    if (this.loanApplyImgs[imgNum] != res.response.data) {
                        array[num] = this.loanApplyImgs[imgNum]
                        num = num + 1
                    }
                }
                this.loanApplyImgs = array
            },

            moneyCalculate() {
                this.$$get(`/loanRecord/getAmtInfo/` + this.client.clientNo + `/` + this.loanAmt + `/` + this.loanLife)
                    .then(res => {
                        if (res.data.code < 1)
                            throw res.data.msg;
                        this.loanAmt = res.data.data.loanAmt;
                        this.backAmt = res.data.data.backAmt;
                        this.rateAmt = res.data.data.rateAmt;
                        this.serviceAmt = res.data.data.serviceAmt;
                    })
                    .catch(err => this.$$msg.err(err))
            },
            dateChange() {
                var date = this.startDate;
                var endDate = moment(date, 'YYYY-MM-DD').add(this.loanLife - 1, 'days').format('YYYY-MM-DD');
                this.endDate = endDate;
                if (this.loanAmt != null && this.loanAmt != '' && this.loanAmt > 0) {
                    this.$$get(`/loanRecord/getAmtInfo/` + this.client.clientNo + `/` + this.loanAmt + `/` + this.loanLife)
                        .then(res => {
                            if (res.data.code < 1)
                                throw res.data.msg;
                            this.loanAmt = res.data.data.loanAmt;
                            this.backAmt = res.data.data.backAmt;
                            this.rateAmt = res.data.data.rateAmt;
                            this.serviceAmt = res.data.data.serviceAmt;
                        })
                        .catch(err => this.$$msg.err(err))
                }
            },
            /** 提交点击 */
            createClick() {
                this.$$post('/loanRecord/create', this.buildPostParam()).then(res => {
                    if (res.data.code < 1) {
                        this.$message.error(res.data.msg);
                        return
                    }
                    this.$message({message: '操作成功', type: 'success'});
                    this.handleClose()
                    window.location.reload()
                })

            },

            //编辑借条
            editClick(){
                this.saler = localStorage.getItem("loginName")
                if (this.bizGroup == null || this.bizGroup == '') {
                    this.$message.error("业务组不能为空");
                    return
                }
                this.$$post('/loanRecord/update', this.buildPostParam()).then(res => {
                    if (res.data.code < 1) {
                        this.$message.error(res.data.msg);
                        return
                    }
                    this.$message({message: '编辑成功', type: 'success'});
                    this.handleClose();
                    window.location.reload()
                })
            },

            /** 提交借款信息 */
            submitClick() {
                this.saler = localStorage.getItem("loginName")
                if (this.bizGroup == null || this.bizGroup == '') {
                    this.$message.error("业务组不能为空");
                    return
                }

                this.$$post('/loanRecord/submit', this.buildPostParam()).then(res => {
                    if (res.data.code < 1) {
                        this.$message.error(res.data.msg);
                        return
                    }
                    this.$message({message: '操作成功', type: 'success'});
                    this.handleClose();
                    window.location.reload()
                })
            },
            buildPostParam() {

                return {
                    loanNo: this.loanRecord.loanNo,
                    clientNo: this.clientNo,
                    loanType: this.loanType,
                    startDate: moment(this.startDate, 'YYYY-MM-DD').format('YYYY-MM-DD'),
                    endDate: this.endDate,
                    loanLife: this.loanLife,
                    loanAmt: this.loanAmt,
                    backAmt: this.backAmt,
                    serviceAmt: this.serviceAmt,
                    rateAmt: this.rateAmt,
                    lendCard: this.lendCardId,
                    bizGroup: this.bizGroup,
                    saler: this.saler,
                    dutyDesc: this.dutyDesc,
                    openBankName: this.openBankName,
                    openSubBankName: this.openSubBankName,
                    bankAccount: this.bankAccount,
                    memo: this.memo,
                    userAttachList: this.userImgs,
                    loanAttachList: this.loanApplyImgs,
                }
            },
            moneyChange() {

                this.loanAmt = this.loanAmt + ""
                this.backAmt = this.backAmt + ""
                this.rateAmt = this.rateAmt + ""
                this.serviceAmt = this.serviceAmt + ""

                this.loanAmt = this.loanAmt.replace(/[^\d.]/g, '')
                this.backAmt = this.backAmt.replace(/[^\d.]/g, '')
                this.rateAmt = this.rateAmt.replace(/[^\d.]/g, '')
                this.serviceAmt = this.serviceAmt.replace(/[^\d.]/g, '')

                var num = 0;
                if (this.loanAmt == null || this.loanAmt == '') {
                    num = num + 1
                }
                if (this.backAmt == null || this.backAmt == '') {
                    num = num + 1
                }
                if (this.rateAmt == null || this.rateAmt == '') {
                    num = num + 1
                }
                if (this.serviceAmt == null || this.serviceAmt == '') {
                    num = num + 1
                }

                if (num > 1) {
                    return
                }

                if (this.loanAmt == null || this.loanAmt == '') {
                    this.loanAmt = parseInt(this.backAmt) + parseInt(this.rateAmt) + parseInt(this.serviceAmt)
                }
                if (this.backAmt == null || this.backAmt == '') {
                    this.backAmt = this.loanAmt - this.rateAmt - this.serviceAmt
                }
                if (this.rateAmt == null || this.rateAmt == '') {
                    this.rateAmt = this.loanAmt - this.backAmt - this.serviceAmt
                }
                if (this.serviceAmt == null || this.serviceAmt == '') {
                    this.serviceAmt = this.loanAmt - this.rateAmt - this.backAmt
                }
            },
            /** 关闭处理 */
            handleClose() {
                this.visible = false;
                setTimeout(() => {
                    this.$emit('update:dialogVisible', false)
                }, 300);
            },


        }
    }
</script>

<style lang="stylus" rel="stylesheet/stylus">
    .client-data-dialog {

        th {
            text-align right
            padding-right: 10px
        }

        .el-input {
            width 80%
        }

    }
</style>
