<template>
<div class="app-container zap-main">
    <header-bar :list="headerList"></header-bar>
    <el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="auto">
        <div class="zap-title zap-margin-top">基本信息</div>
        <el-row class="zap-form">
            <el-form-item label="融资产品名称:" prop="zfpName" size="large">
                <el-input v-model="form.zfpName" placeholder="请输入融资产品名称" maxlength="20" clearable :disabled="disabled" />
            </el-form-item>
            <el-form-item label="资金方:" prop="zfpManagementId" size="large">
                <el-select v-model="form.zfpManagementId" placeholder="请选择资金方" clearable :disabled="disabled" @change="change">
                    <el-option v-for="(item,index) in companyList" :key="index" :label="item.scyName" :value="item.scyId" />
                </el-select>
            </el-form-item>
            <el-form-item label="是否可拆转融:" size="large">
                <el-radio-group v-model="form.zfpSplit">
                    <el-radio-button label="0" :disabled="disabled">否</el-radio-button>
                    <el-radio-button label="1" :disabled="disabled">是</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="产品类型:" size="large">
                <el-radio-group v-model="form.zfpType">
                    <el-radio-button label="0" :disabled="disabled">正向</el-radio-button>
                    <el-radio-button label="1" :disabled="disabled">反向</el-radio-button>
                </el-radio-group>
            </el-form-item>
        </el-row>
        <div class="zap-title zap-margin-top">平台参数</div>
        <el-row class="zap-form">
            <el-form-item label="最小融资金额(元):" prop="zfpMinimumAmount" size="lage">
                <el-input v-model="form.zfpMinimumAmount" placeholder="请输入最小融资金额" @input.native="changeRate($event,form.zfpMinimumAmount)" clearable maxlength="10" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="最短融资账期:" prop="zfpShortestPeriod" size="lage">
                <el-input v-model="form.zfpShortestPeriod" placeholder="最短14天" maxlength="2" clearable :disabled="disabled" />
            </el-form-item>
            <el-form-item label="服务费是否可退:" size="lage">
                <el-radio-group v-model="form.zfpType">
                    <el-radio-button v-model="form.zfpCharge" label="0" :disabled="disabled">否</el-radio-button>
                    <el-radio-button v-model="form.zfpCharge" label="1" :disabled="disabled">是</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否有追索权:" size="lage">
                <el-radio-group v-model="form.zfpType">
                    <el-radio-button v-model="form.zfpRecourse" label="0" :disabled="disabled">否</el-radio-button>
                    <el-radio-button v-model="form.zfpRecourse" label="1" :disabled="disabled">是</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="电子凭证类型:" prop="zfpVoucherType" size="lage">
                <el-select v-model="form.zfpVoucherType" placeholder="请选择电子凭证类型" clearable :disabled="disabled">
                    <el-option v-for="dict in voucherTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
            </el-form-item>
        </el-row>
        <el-divider content-position="left"></el-divider>
        <div class="zap-title zap-margin-top">资方参数</div>
        <el-row class="zap-form">
            <el-form-item label="是否需核心企业开户:" size="large">
                <el-radio-group v-model="form.zfpCoreAccount">
                    <el-radio-button label="0">否</el-radio-button>
                    <el-radio-button label="1">是</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否需融资企业开户:" size="large">
                <el-radio-group v-model="form.zfpSupplierAccount">
                    <el-radio-button label="0">否</el-radio-button>
                    <el-radio-button label="1">是</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="记账簿托管方式:" prop="zfpBookkeeping" size="large">
                <el-select v-model="form.zfpBookkeeping" placeholder="请选择记账簿托管方式" clearable>
                    <el-option v-for="dict in bookkeepingOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="是否支持部分融资:" size="large">
                <el-radio-group v-model="form.zfpPart">
                    <el-radio-button label="0">否</el-radio-button>
                    <el-radio-button label="1">是</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="资方融资费率(%):" prop="zfpRate" size="large">
                <el-input v-model="form.zfpRate" @input.native="inputRate($event,form.zfpRate)" clearable placeholder="请输入资方融资费率" maxlength="5" />
            </el-form-item>
            <el-form-item label="融资到期方式:" prop="zfpExpire" size="large">
                <el-select v-model="form.zfpExpire" placeholder="请选择融资到期方式" clearable>
                    <el-option v-for="dict in expireOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="资方是否支持返佣:" size="large">
                <el-radio-group v-model="form.zfpProfit">
                    <el-radio-button label="0" @change="changeProfit">否</el-radio-button>
                    <el-radio-button label="1" @change="changeProfit">是</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="资方返佣方式:" prop="zfpProfitType" v-if="form.zfpProfit== '1' " size="large">
                <el-select v-model="form.zfpProfitType" placeholder="请选择资方返佣方式" clearable>
                    <el-option v-for="dict in profitTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="资方返佣费率(%):" prop="zfpProfitRate" v-if="form.zfpProfit== '1' " size="large">
                <el-input v-model="form.zfpProfitRate" @input.native="inputRates($event,form.zfpProfitRate)" clearable placeholder="请输入资方返佣费率" maxlength="5" />
            </el-form-item>
            <el-form-item label="是否需平台审批:" size="large">
                <el-radio-group v-model="form.zfpPlatform">
                    <el-radio-button label="0">否</el-radio-button>
                    <el-radio-button label="1">是</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="签署意愿类型:" prop="zfpAuthType" size="large">
                <el-select v-model="form.zfpAuthType" placeholder="请选择签署意愿类型" clearable>
                    <el-option v-for="dict in authTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                </el-select>
            </el-form-item>
        </el-row>
        <div class="zap-title zap-margin-top">关联合同</div>
        <el-row class="zap-form">
            <el-form-item class="zap-table" prop="zfcId" style="width: 100%;">
                <el-button size="mini" type="primary" v-if="this.form.zfpStatus=='00'" @click="openTicket">选择合同</el-button>
                <el-button size="mini" v-if="this.form.zfpStatus=='00'" @click="deleteTicekt">清空全部</el-button>
                <el-table :data="contractList1" style="width: 100%;" stripe border>
                    <el-table-column label="序号" type="index" width="50" align="center">
                        <template slot-scope="scope">
                            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="合同模板编号" align="center" prop="zfcId" v-if="false" />
                    <el-table-column label="合同模板名称" align="center" prop="zfcName" />
                    <el-table-column label="签署节点" align="center" prop="zfcNode" :formatter="nodeFormat" />
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
                        <template slot-scope="scope">
                            <el-button v-if="form.zfpStatus=='00'" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.$index, contractList1)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-row>
    </el-form>
    <!-- 合同信息 -->
    <el-dialog :title="title" :visible.sync="open" width="1120px" append-to-body>
        <el-form :model="queryParams" ref="formQuery" :inline="true" label-width="68px" style="margin-bottom: -21px">
            <el-form-item label="合同模板名称" prop="zfcName">
                <el-input v-model="queryParams.zfcName" placeholder="请输入模板名称" clearable size="small" maxlength="20" />
            </el-form-item>
            <el-form-item>
                <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuerys">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuerys">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="contractList" ref="tableContract" class="single-select-table" @selection-change="handleSelectionChange" :row-key="rowkey" stripe border>
            <el-table-column type="selection" :reserve-selection="true" width="50" align="center" />
            <el-table-column label="序号" type="index" width="50" align="center">
                <template slot-scope="scope">
                    <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                </template>
            </el-table-column>
            <el-table-column label="资金方" align="center" prop="scyName" :show-overflow-tooltip="true" />
            <el-table-column label="合同模板名称" align="center" prop="zfcName" :show-overflow-tooltip="true" />
            <el-table-column label="合同模板状态" align="center" prop="zfcStatus" :formatter="statusFormat" :show-overflow-tooltip="true" />
            <el-table-column label="签署节点" align="center" prop="zfcNode" :formatter="nodeFormat" :show-overflow-tooltip="true" />
            <!-- <el-table-column label="签署方" align="center" prop="zfcSubject" :formatter="subjectFormat" :show-overflow-tooltip="true"/> -->
            <el-table-column label="创建人" align="center" prop="nickName" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" />
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getContractList" />
        <!-- <el-button type="primary" @click="submitData()">关闭</el-button> -->
        <span slot="footer" class="dialog-footer">
            <el-button size="mini" @click="cancelTicket">取消</el-button>
            <el-button size="mini" type="primary" @click="closeTicket">确认</el-button>
            <!-- <el-button @click="cancelSelection">取 消</el-button>
        <el-button type="primary" @click="changeInvoice">确 定</el-button> -->
        </span>
    </el-dialog>
    <!-- 保存 -->
    <el-row type="flex" justify="center" align="middle" style="height: 82px;">
        <el-button type="primary" plain @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
    </el-row>
</div>
</template>

<script>
import {
    getFinanceProduct,
    updateFinanceProduct
} from "@/api/service/financeProduct/financeProduct";
import {
    listCompany
} from "@/api/common/company";
import {
    listContract
} from "@/api/common/contract";
export default {
    name: "editFinanceProduct",
    components: {},
    data() {
        return {
            disabled: false,
            //查询合同的表格数据
            contractList: [],
            //选中合同的表格数据
            contractList1: [],
            //选中发票数据
            chooseTicket: [],
            // 日期范围
            dateRange: [],
            pafCustomerId: "",
            activeName: "1",
            // 选中数组
            ids: [],
            // 弹出层标题
            title: "",
            // 总条数
            total: 0,
            //创建人
            userName: null,
            // 是否显示弹出层
            open: false,
            // 资方列表
            companyList: [],
            //余额
            multipleSelection: [],
            content: [],
            //数据字典
            voucherTypeOptions: [],
            bookkeepingOptions: [],
            expireOptions: [],
            profitTypeOptions: [],
            authTypeOptions: [],
            // 表单参数
            form: {},
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                zfcName: null,
                zfcManagementId: null,
            },
            options: [],
            value: [],
            loading: false,
            // 表单校验
            rules: {
                zfpName: [{
                    required: true,
                    message: "产品名称不能为空",
                    trigger: ["blur", "change"],
                }, ],
                zfpManagementId: [{
                    required: true,
                    message: "资金方不能为空",
                    trigger: ["blur", "change"],
                }, ],
                zfpMinimumAmount: [{
                    required: true,
                    pattern: /^[0-9][0-9]{0,9}$|^[1-9][0-9]{0,9}[.]\d{1,2}$/,
                    message: "请输入正确的付款金额",
                    trigger: ["blur", "change"],
                }, ],
                zfpShortestPeriod: [{
                    required: true,
                    pattern: /^\d+$/,
                    message: "请输入正确的最短融资账期",
                    trigger: ["blur", "change"],
                }, ],
                zfpVoucherType: [{
                    required: true,
                    message: "电子凭证类型不能为空",
                    trigger: ["blur", "change"],
                }, ],
                zfpAuthType: [{
                    required: true,
                    message: "签署意愿类型不能为空",
                    trigger: ["blur", "change"],
                }, ],
                zfpRate: [{
                    pattern: /^100$|^(\d|[1-9]\d)(\.\d{1,2})*$/,
                    message: "资方融资费率在0-100之内",
                    trigger: ["blur", "change"],
                }, ],
                zfpProfitRate: [{
                    pattern: /^100$|^(\d|[1-9]\d)(\.\d{1,2})*$/,
                    message: "资方返佣费率在0-100之内",
                    trigger: ["blur", "change"],
                }, ],
            },
        };
    },
    computed: {
        headerList() {
            return [{
                    icon: require('../../../assets/images/components/headerBar/icon_creater.png'),
                    label: '创建人：',
                    value: this.userName
                },
                {
                    icon: require('../../../assets/images/components/headerBar/icon_calendar.png'),
                    label: '创建日期：',
                    value: this.parseTime(new Date(this.form.createTime))
                },
                {
                    icon: require('../../../assets/images/components/headerBar/icon_list.png'),
                    label: '编号：',
                    value: this.form.zfpNumber
                },
            ]
        }
    },
    created() {
        const zfpId = this.$route.params && this.$route.params.zfpId;
        this.reset();
        this.getDicts("zc_zfp_voucher_type").then((response) => {
            this.voucherTypeOptions = response.data;
        });
        this.getDicts("zc_zfp_bookkeeping").then((response) => {
            this.bookkeepingOptions = response.data;
        });
        this.getDicts("zc_zfp_expire").then((response) => {
            this.expireOptions = response.data;
        });
        this.getDicts("zc_zfp_profit_type").then((response) => {
            this.profitTypeOptions = response.data;
        });
        this.getDicts("zc_zfp_auth_type").then((response) => {
            this.authTypeOptions = response.data;
        });
        this.getDicts("zc_zfc_status").then((response) => {
            this.statusOptions = response.data;
        });
        this.getDicts("zc_zfc_node").then((response) => {
            this.nodeOptions = response.data;
        });
        this.getDicts("zc_zfc_subject").then((response) => {
            this.subjectOptions = response.data;
        });

        getFinanceProduct(zfpId).then((response) => {
            this.form = response.data.zcFinanceProduct;
            this.contractList1 = response.data.contractList1;
            this.form.createTime = this.parseTime(new Date(response.data.zcFinanceProduct.createTime), '{y}-{m}-{d} {h}:{m}:{s}');
            this.userName = response.data.nickName;
            var state = this.form.zfpStatus;
            if (state == '01') {
                this.disabled = true;
            }
            const type = "03";
            const zfpManagementId = this.form.zfpManagementId;
            listCompany(type, zfpManagementId).then(response => {
                this.companyList = response.data;
            })
        });
    },
    activated() {
        this.reset();
    },
    methods: {
        /** 查询资方 */
        getCompanyList() {
            const type = "03";
            listCompany(type).then(response => {
                this.companyList = response.data;
            })
        },
        //合同模板状态字典反显
        statusFormat(row, column) {
            return this.selectDictLabel(this.statusOptions, row.zfcStatus);
        },
        //签署节点字典反显
        nodeFormat(row, column) {
            var zfcNodes = row.zfcNode.split(",");
            var zfcNodeList = '';
            for (var i = 0; i < zfcNodes.length; i++) {
                zfcNodeList += this.selectDictLabel(this.nodeOptions, zfcNodes[i]);
                if (i < zfcNodes.length - 1) {
                    zfcNodeList += ",";
                }
            }
            return zfcNodeList;
        },
        //签署方字典反显
        subjectFormat(row, column) {
            return this.selectDictLabel(this.subjectOptions, row.zfcSubject);
        },
        // change(val){
        //   if(val<=14){
        //     this.$set(this.form, "zfpShortestPeriod", "14");
        //   }
        //   return ;
        // },
        getContractList() {
            this.queryParams.zfcManagementId = this.form.zfpManagementId;
            listContract(this.queryParams).then((response) => {
                this.contractList = response.data.records;
                this.selectChecked();
                this.total = response.data.total;
            });
        },
        //打开合同选择列表
        openTicket() {
            this.resetQuerys();
            // this.resetForm("formQuery");
            // this.getContractList();
            this.open = true;
            this.title = "合同信息";
        },
        selectChecked() {
            this.contractList1.forEach((item) => {
                this.contractList.forEach((row) => {
                    if (row.zfcId == item.zfcId) {
                        this.$nextTick(() => {
                            this.$refs.tableContract &&
                                this.$refs.tableContract.toggleRowSelection(row, true);
                        });
                    }
                });
            });
        },
        changeProfit() {
            this.form.zfpProfitType = null
            this.form.zfpProfitRate = null
        },
        /* 多选框跨页 */
        rowkey(row) {
            return row.zfcId;
        },
        // 多选框选中数据
        handleSelectionChange(val) {
            this.chooseTicket = val
        },
        // 确认选择
        closeTicket() {
            if (this.chooseTicket.length > 0) {
                this.contractList1 = this.chooseTicket
                this.open = false
            } else {
                this.$message({
                    message: '请选择合同',
                    type: 'warning'
                });
            }
        },
        //取消选择按钮
        cancelTicket() {
            if (this.contractList1.length > 0) {
                this.open = false;
            } else {
                this.contractList1 = [];
                if (this.$refs.tableContract) {
                    this.$refs.tableContract.clearSelection()
                }
                this.open = false;
            }
        },
        /** 清空选择发票信息 */
        deleteTicekt() {
            this.contractList1 = [];
            if (this.$refs.tableContract) {
                this.$refs.tableContract.clearSelection()
            }
        },
        /* 删除按钮 */
        handleDelete(index, rows) {
            rows.splice(index, 1);
            if (this.$refs.tableContract) {
                this.$refs.tableContract.clearSelection()
            }
            this.selectChecked();
        },
        onSelectAll() {
            if (this.$refs.tableContract) {
                this.$refs.tableContract.clearSelection()
            }
        },
        handleQuerys() {
            this.queryParams.pageNum = 1;
            this.getContractList();
        },
        resetQuerys() {
            this.resetForm("formQuery");
            this.handleQuerys();
        },
        /* ---------------------------------------------------------------------- */
        // 多选框选中数据
        handleCurrentChange(val) {
            // this.currentRow = val;
            // this.open = false;
        },
        /* 清空 */
        change() {
            this.contractList1 = [];
            if (this.$refs.tableContract) {
                this.$refs.tableContract.clearSelection()
            }
        },
        reset() {
            this.form = {
                zfpId: null,
                zfpNumber: null,
                zfpName: null,
                zfpManagementId: null,
                zfpSplit: "0",
                zfpType: "1",
                zfpTransfer: "0",
                zfpRecourse: "0",
                zfpVoucherType: null,
                zfpCoreAccount: "0",
                zfpSupplierAccount: "0",
                zfpCharge: "0",
                zfpStatus: "0",
                zfpMinimumAmount: null,
                zfpShortestPeriod: null,
                zfpBookkeeping: null,
                zfpPart: "0",
                zfpExpire: null,
                zfpRate: null,
                zfpProfit: "0",
                zfpProfitType: null,
                zfpProfitRate: null,
                zfpPlatform: "0",
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null
            };
            this.resetForm("form");
        },
        /* ---------------------------------------------------------------------- */
        // 取消按钮
        cancel() {
            this.reset();
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.go(-1);
            this.open = false;
        },
        changeVal(val) {
            if (val > 100) {
                this.val = "";
                this.$message({
                    message: '请输入正确的费率',
                    type: 'warning'
                });
            }
        },
        changeRate(e, input) {
            e.target.value = (e.target.value.match(/^\d*(\.?\d{0,2})/g)[0]) || null
            this.input = e.target.value
            this.form.zfpMinimumAmount = this.input
        },
        inputRate(e, input) {
            e.target.value = (e.target.value.match(/^\d*(\.?\d{0,2})/g)[0]) || null
            this.input = e.target.value
            this.form.zfpRate = this.input
        },
        inputRates(e, input) {
            e.target.value = (e.target.value.match(/^\d*(\.?\d{0,2})/g)[0]) || null
            this.input = e.target.value
            this.form.zfpProfitRate = this.input
        },
        /** 保存按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                this.form.contractList1 = this.contractList1;
                console.log(this.form)
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: "Loading",
                        spinner: "el-icon-loading",
                        background: "rgba(0, 0, 0, 0.7)",
                    });
                    updateFinanceProduct(this.form)
                        .then((response) => {
                            loading.close();
                            this.msgSuccess("修改成功");
                            this.$store.dispatch("tagsView/delView", this.$route);
                            this.$router.go(-1);
                        })
                        .catch((response) => {
                            loading.close();
                        });
                }
            });
        },
        // submitData() {
        //   this.open = false;
        // },
        /* //  将数字金额转换为大写金额 */
    },
};
</script>

<style>
.single-select-table thead .el-table-column--selection .cell {
    display: none;
}
</style><style lang="scss" scoped>
.zap-No {
    padding: 14px 25px;
    background-color: #ffffff;

    .icon {
        width: 18px;
        margin-right: 10px;
    }

    .label {
        white-space: nowrap;
        margin-right: 8px;
        font-size: 14px;
        color: #999999;
    }

    .value {
        font-size: 14px;
        color: #333333;
    }
}

.zap-title {
    padding: 25px;
    font-size: 16px;
    color: #333333;
    background-color: #ffffff;
}

::v-deep .el-radio-button__inner {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 35px;
    padding: 0;
    border: 1px solid #e0e0e0;
}

::v-deep .el-radio-button:first-child .el-radio-button__inner {
    margin-right: 20px;
    border-radius: 17px;
}

::v-deep .el-radio-button:last-child .el-radio-button__inner {
    border-radius: 17px;
}

::v-deep .el-radio-button__orig-radio:checked+.el-radio-button__inner {
    color: #4280f2;
    background: #ecf2fe;
    border-color: #b3ccfa;
    box-shadow: none;
}

.zap-form {
    padding: 0 25px;
    background-color: #ffffff;
}

.zap-table ::v-deep .el-form-item__content {
    width: 100%;
}
</style>
