<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="90px"
        >
            <el-form-item label="代理商编号" prop="agentIndex">
                <el-input
                    v-model="queryParams.agentIndex"
                    placeholder="请输入代理商编号"
                    clearable
                    size="small"
                    maxlength="30"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="代理商名称" prop="agentName">
                <el-input
                    v-model="queryParams.agentName"
                    placeholder="请输入代理商名称"
                    clearable
                    size="small"
                    maxlength="20"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="联系人" prop="agentContactName">
                <el-input
                    v-model="queryParams.agentContactName"
                    placeholder="请输入联系人"
                    clearable
                    size="small"
                    maxlength="20"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="联系方式" prop="agentContactPhone">
                <el-input
                    v-model="queryParams.agentContactPhone"
                    placeholder="请输入联系方式"
                    clearable
                    size="small"
                    maxlength="13"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['operation']"
                    >新增</el-button
                >
            </el-col>
            <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:agent:edit']"
        >修改</el-button>
      </el-col> -->
            <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:agent:remove']"
        >删除</el-button>
      </el-col> -->
            <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:agent:export']"
        >导出</el-button>
      </el-col> -->
            <right-toolbar
                :showSearch.sync="showSearch"
                @queryTable="getList"
            ></right-toolbar>
        </el-row>

        <el-table
            v-loading="loading"
            :data="agentList"
            @selection-change="handleSelectionChange"
        >
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <!-- <el-table-column label="代理商id" align="center" prop="agentId" /> -->
            <el-table-column
                label="代理商编号"
                align="center"
                prop="agentIndex"
                show-overflow-tooltip
            />
            <el-table-column
                label="代理商名称"
                align="center"
                prop="agentName"
                show-overflow-tooltip
            />
            <el-table-column
                label="联系人"
                align="center"
                prop="agentContactName"
                show-overflow-tooltip
            />
            <el-table-column
                label="联系方式"
                align="center"
                prop="agentContactPhone"
            />
            <el-table-column
                label="分账比例(%)"
                align="center"
                prop="commissionRate"
            />
            <el-table-column
                label="微信商户号"
                align="center"
                prop="wxAccount"
                show-overflow-tooltip
            />
            <el-table-column
                label="支付宝商户号"
                align="center"
                prop="aliAccount"
                show-overflow-tooltip
            />
            <el-table-column
                label="备注"
                align="center"
                prop="remark"
                :show-overflow-tooltip="true"
            />
            <!-- <el-table-column label="预留字段1" align="center" prop="column1" />
      <el-table-column label="预留字段2" align="center" prop="column2" />
      <el-table-column label="预留字段3" align="center" prop="column3" /> -->
            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['operation']"
                        >编辑</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['operation']"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或编辑商户代理商对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            append-to-body
        >
            <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="代理商名称" prop="agentName">
                    <el-input
                        v-model="form.agentName"
                        placeholder="请输入代理商名称"
                        maxlength="30"
                    />
                </el-form-item>
                <el-form-item label="联系人" prop="agentContactName">
                    <el-input
                        v-model="form.agentContactName"
                        placeholder="请输入联系人"
                        maxlength="20"
                    />
                </el-form-item>
                <el-form-item label="联系方式" prop="agentContactPhone">
                    <el-input
                        v-model="form.agentContactPhone"
                        placeholder="请输入联系方式"
                        maxlength="13"
                    />
                </el-form-item>
                <el-form-item label="分账比例(%)" prop="commissionRate">
                    <!-- <el-input
                        v-model="form.commissionRate"
                        placeholder="请输入分账比例"
                        maxlength="3"
                    /> -->
                    <el-input
                        v-model="form.commissionRate"
                        placeholder="请输入分账比例"
                        @input="inputChange(form.commissionRate.trim())"
                        maxlength="3"

                    />
                </el-form-item>
                <el-form-item label="微信商户号" prop="wxAccount">
                    <el-input
                        v-model="form.wxAccount"
                        placeholder="请输入微信商户号"
                        onkeyup="value=value.replace(/[^a-z0-9_]/g,'');"
                        maxlength="40"
                    />
                </el-form-item>
                <el-form-item label="支付宝商户号" prop="aliAccount">
                    <el-input
                        v-model="form.aliAccount"
                        placeholder="请输入支付宝商户号"
                        onkeyup="value=value.replace(/[^a-z0-9_]/g,'');"
                        maxlength="40"
                    />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input
                        v-model="form.remark"
                        type="textarea"
                        maxlength="200"
                        placeholder="请输入内容"
                    />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    listAgent,
    getAgent,
    logicalDelAgent,
    addAgent,
    updateAgent,
    exportAgent,
} from "@/api/agent/adminAgent";

export default {
    name: "adminAgent",
    data() {
        // 校验手机号或座机格式
        var checkPhone = (rule, value, callback) => {
            let regPone = null;
            let mobile = /^((13|14|15|17|18)[0-9]{1}\d{8})$/; // 最新16手机正则
            let tel = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/; // 座机
            if (value !== null && value.charAt(0) === "0") {
                // charAt查找第一个字符方法，用来判断输入的是座机还是手机号
                regPone = tel;
            } else if (value !== null && value.charAt(0) !== "0") {
                regPone = mobile;
            }
            if (regPone === null) {
                return callback(new Error("请输入代理商联系方式"));
            } else if (!regPone.test(value)) {
                return callback(
                    new Error(
                        "请输入正确的联系方式,其中座机格式'区号-座机号码'"
                    )
                );
            } else {
                callback();
            }
        };
        return {
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 商户代理商表格数据
            agentList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                agentIndex: null,
                agentName: null,
                agentContactName: null,
                agentContactPhone: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                agentName: [
                    {
                        required: true,
                        message: "代理商名称不能为空",
                        trigger: "blur",
                    },
                ],
                agentContactPhone: [
                    {
                        required: true,
                        validator: checkPhone,
                        trigger: "blur",
                    },
                ],
                commissionRate: [
                    {
                        required: true,
                        message: "分账比例不能为空",
                        trigger: "blur",
                    },
                ],
            },
        };
    },

    created() {
        this.getList();
    },

    methods: {
        // 查询商户代理商列表
        getList() {
            this.loading = true;
            listAgent(this.queryParams)
                .then((response) => {
                    if (response.code === 200) {
                        this.agentList = response.rows;
                        this.total = response.total;
                        if (this.agentList.length === 0) {
                            this.queryParams.pageNum = 1;
                            this.getList();
                        }
                    } else {
                        this.$message.error(response.msg);
                    }
                })
                .catch((error) => {
                    console.error(error);
                })
                .finally(() => {
                    this.loading = false;
                });
        },

        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },

        // 表单重置
        reset() {
            this.form = {
                agentName: null,
                agentContactName: null,
                agentContactPhone: null,
                commissionRate: null,
                wxOpenId: null,
                aliOpenId: null,
                remark: null,
            };
            this.resetForm("form");
        },

        // 搜索按钮操作
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.agentId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },

        // 新增按钮操作
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加代理商";
        },

        // 编辑按钮操作
        handleUpdate(row) {
            this.reset();
            const agentId = row.agentId || this.ids;
            getAgent(agentId).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "编辑代理商";
            });
        },

        // 提交按钮
        submitForm() {
            if (this.form.agentName && this.form.agentName.length > 50) {
                return this.$message.error("代理商名称长度不得超过50");
            }
            if (
                this.form.agentContactName &&
                this.form.agentContactName.length > 50
            ) {
                return this.$message.error("联系人长度不得超过50");
            }
            if (
                this.form.agentContactPhone &&
                this.form.agentContactPhone.length > 20
            ) {
                return this.$message.error("联系方式长度不得超过20");
            }
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.agentId != null) {
                        updateAgent(this.form).then((response) => {
                            this.$modal.msgSuccess("编辑成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addAgent(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },

        // 删除按钮操作
        handleDelete(row) {
            const agentIds = row.agentId || this.ids;
            this.$modal
                .confirm(
                    '是否确认删除代理商名称为"' + row.agentName + '"的数据项？'
                )
                .then(function () {
                    return logicalDelAgent(agentIds);
                })
                .then(() => {
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                })
                .catch(() => {});
        },

        // 导出按钮操作
        handleExport() {
            const queryParams = this.queryParams;
            this.$modal
                .confirm("是否确认导出所有代理商数据项？")
                .then(() => {
                    this.exportLoading = true;
                    return exportAgent(queryParams);
                })
                .then((response) => {
                    this.$download.name(response.msg);
                    this.exportLoading = false;
                })
                .catch(() => {});
        },
        // 校验分账比例
        inputChange(val) {
            val = val.replace(/(^\s*)|(\s*$)/g, "");
            if (!val) {
                this.form.commissionRate = "";
                return;
            }
            // 只能是数字和小数点，不能是其他输入
            val = val.replace(/[^\d.]/g, "");
            // 保证第一位只能是数字，不能是点
            val = val.replace(/^\./g, "");
            // 小数点只能出现1位
            val = val
                .replace(".", "$#$")
                .replace(/\./g, "")
                .replace("$#$", ".");
            // 小数点后面保留2位
            val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");

            this.form.commissionRate = val;
        },
    },
};
</script>
