<template>
    <div class="main">
        <div class="header">
            <el-form :inline="true" :model="pettyMoneyQuery">
                <!-- 合同名称，合同编号，合同类型，合同性质 -->
                <!-- <el-form-item>
                    <el-input v-model="pettyMoneyQuery.contractName" placeholder="请选择备用金名称" />
                </el-form-item> -->
                <el-form-item>
                    <el-select v-model="pettyMoneyQuery.pettyApproval" placeholder="请选择审批状态">
                        <el-option v-for="(item, index) in approveResult" :key="index" :value="index"
                            :label="item.text"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="pettyMoneyQuery.pettyState" placeholder="请选择还款状态">
                        <el-option v-for="(item, index) in pettyStates" :key="index" :value="index"
                            :label="item.text"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="getPettyMoneyList(true)">查询</el-button>
                    <el-button type="primary" icon="el-icon-refresh-right" @click="pettyMoneyQuery = {}; getPettyMoneyList(false)">重置</el-button>
                    <!-- <el-button type="success" icon="el-icon-circle-plus-outline" @click="dialogTableVisible = true">添加合同</el-button> -->
                </el-form-item>
            </el-form>
        </div>
        <div class="container">
            <el-table :data="pettyMoneyList" style="width: 100%;text-align: center;" border>
                <el-table-column label="编号" width="50px">
                    <template slot-scope="scope">
                        {{ (pettyMoneyPageQuery.pageNum - 1) * pettyMoneyPageQuery.pageSize + scope.$index + 1 }}
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="companyName" label="状态"/> -->
                <el-table-column prop="pettyName" label="备用金名称" width="120px">
                    <template slot-scope="scope">
                        {{ parseInt(scope.row.pettyApproval) === 1 ? scope.row.pettyName : '暂未通过' }}
                    </template>
                </el-table-column>
                <el-table-column prop="pettyReason" label="借款缘由" />
                <el-table-column prop="pettyMoney" label="借款金额" width="120px" />
                <el-table-column prop="pettySurplus" label="待还金额" width="120px" />
                <el-table-column prop="pettyTime" label="借款日期" width="180px" />
                <el-table-column prop="pettyApproval" label="审批状态" width="100px">
                    <template slot-scope="scope">
                        <el-tag size="mini" :type="approveResult[scope.row.pettyApproval].type">
                            {{ approveResult[scope.row.pettyApproval].text }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="pettyState" label="还款状态" width="100px">
                    <template slot-scope="scope">
                        <el-tag size="mini" :type="pettyStates[scope.row.pettyState].type">
                            {{ pettyStates[scope.row.pettyState].text }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button-group>
                            <el-button type="success" size="mini" v-if="parseInt(scope.row.pettyApproval) === 1"
                                @click="controlDialogDrawerVisible('agree', scope.row)" :disabled="parseInt(scope.row.pettySurplus) === 0">{{parseInt(scope.row.pettySurplus) === 0 ? '已还清':'还款'}}
                            </el-button>
                            <el-button type="primary" size="mini" v-if="parseInt(scope.row.pettyApproval) === 0"
                                @click="$router.push({ path: '/editPetty', query: { pettyId: String(scope.row.pettyId) } })">
                                编辑</el-button>
                            <el-button size="mini" :style="{background: '#5782df',color: '#fff',border: '1px solid #5782df'}"
                                @click="controlDialogDrawerVisible('drawerVisible', scope.row)">
                                详情</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="footer">
            <el-pagination @current-change="getPettyMoneyList()" :current-page.sync="pettyMoneyPageQuery.pageNum"
                :page-size="pettyMoneyPageQuery.pageSize" layout="total, prev, pager, next"
                :total="pettyMoneyPageQuery.total">
            </el-pagination>
        </div>
        <el-dialog title="还款金额" :visible="Boolean(dialogVisible)" width="40%" :show-close="false">
            <el-form label-position="left" :model="checkedRow" label-width="100px" ref="dialogForm">
                <el-form-item label="还款金额" :rules="{ validator: checkRepayMoney, trigger: 'change' }"
                    prop="repaymentMoney">
                    <el-input v-model="checkedRow.repaymentMoney" placeholder="请选择备用金名称" type="number" :min="1"/>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="controlDialogDrawerVisible('')">取 消</el-button>
                <el-button type="primary" @click="repay">确 定</el-button>
            </span>
        </el-dialog>

        <el-drawer :visible.sync="drawerVisible" size="50%" :with-header="false">
            <applicate-detail :checkedRow="checkedRow" :repayDetailList="repayDetailList"></applicate-detail>
        </el-drawer>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { selectSelfPettyRecord, repayMoney, repayRecordsByPettyId } from '@/api/pettyMoney'
import { approveResult, pettyStates } from './pettyMoneyStaticData'
import { parseTime } from '@/utils'
import applicateDetail from './components/applicateDetail'
export default {
    computed: {
        ...mapGetters([
            'companyId',
            'urId'
        ]),
    },
    components: {
        applicateDetail
    },
    data() {
        return {
            pettyMoneyQuery: {},
            isConditionSelect: false,
            pettyMoneyPageQuery: {
                pageSize: 10,
                pageNum: 1,
                total: 0
            },
            pettyMoneyList: [],
            approveResult,
            pettyStates,
            checkedRow: {},
            dialogVisible: '',
            drawerVisible: false,
            repayDetailList: []

        }
    },
    mounted() {
        this.getPettyMoneyList(false)
    },
    methods: {
        checkRepayMoney(rule, value, callback) {
            // console.log(1)
            if ( value === null || value === undefined || value === '') {
                callback(new Error('还款金额不能为空'));
            }else if(parseFloat(value) <= 0){
                callback(new Error('请输入大于0的金额'));
            }else if (value > this.checkedRow.pettySurplus) {
                callback(new Error('超出应还款金额'));
            } else {
                callback();
            }
        },
        getPettyMoneyList(isConditionSelect) {
            const params = {
                ...this.pettyMoneyPageQuery,
                companyId: this.companyId,
                userId: this.urId
            }
            //不能确定是不是条件查询，则根据上一个查询方式进行条件查询或者一般查询，=== 切换分页时候
            if(isConditionSelect === undefined || isConditionSelect === ''){
                this.isConditionSelect && Object.assign(params, this.pettyMoneyQuery)
                Object.assign(params, this.pettyMoneyPageQuery)
            //确定是某种查询方式，则更新标记，作为下一次查询的标准
            }else{
                this.isConditionSelect = isConditionSelect
                isConditionSelect && Object.assign(params, this.pettyMoneyQuery)
                params.pageNum = 1
                this.pettyMoneyPageQuery.pageNum = 1
            }
            selectSelfPettyRecord(params).then(res => {
                if (res.success) {
                    this.pettyMoneyPageQuery.total = res.data.total
                    this.pettyMoneyList = res.data.list
                } else {
                    this.$message.error("获取数据失败")
                }
            })
        },

        controlDialogDrawerVisible(dialogVisible, data) {
            if (dialogVisible) {
                this.checkedRow = { ...data }
            } else {
                this.checkedRow = {}
            }
            if (dialogVisible === 'drawerVisible') {
                this.drawerVisible = true
                parseInt(data.pettyApproval) === 1 && this.getRepayDetailList()
                return
            }
            this.dialogVisible = dialogVisible
            this.$refs['dialogForm'].resetFields();
        },
        getRepayDetailList() {
            const params = {
                pettyId: this.checkedRow.pettyId
            }
            repayRecordsByPettyId(params).then(res => {
                if (res.success) {
                    this.repayDetailList = res.data
                } else {
                    this.$message.error("获取还款记录失败")
                }
            })
        },
        repay() {
            this.$refs.dialogForm.validate((valida) => {
                if (valida) {
                    const { pettyId, repaymentMoney } = this.checkedRow
                    const params = {
                        // companyId: this.companyId,
                        operationId: this.urId,
                        pettyId,
                        repaymentMoney,
                        repaymentApproval: 0,
                        repaymentTime: parseTime(new Date()),
                        repaymentReason: ''
                    }
                    repayMoney(params).then(res => {
                        if (res.success) {
                            this.$message.success("还款成功")
                            this.getPettyMoneyList()
                            this.controlDialogDrawerVisible('')
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            })

        }
    }
}
</script>
<style scoped lang="scss">
.main {
    padding: 15px;

}

.footer {
    text-align: right;
}
</style>