<template>
  <div class="app-container">
    <div class="bg">

      <div class="rig flex m20" v-hasPermi="['order:rechargeRecord:amountCount']">
        <div>
          在途总金额(元)：<span class="#197CFE">{{ sum.onRouteAmount }}</span>
        </div>
        <div>
          冻结总金额(元)：<span class="#197CFE">{{ sum.freezeAmount }}</span>
        </div>
        <div>
          可提现总金额(元)：<span class="#197CFE">{{ sum.withdrawalAmount }}</span>
        </div>
        <div>
          汇总：<span class="#197CFE">{{ sum.gatherAmount }}</span>
        </div>
      </div>
      <div class="rig flex m20">
        <div>
          当前商户编号：<span class="#197CFE">{{ pkCouponId }}</span>
        </div>
        <div>
          当前商户：<span class="#197CFE">{{ pkCouponStore.storeName }}</span>
        </div>
      </div>
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="86px"
        class="flex form" style="padding:0 20px">
        <el-form-item label="支付渠道" prop="channelType">
          <el-select v-model="queryParams.channelType" placeholder="请选择支付渠道" clearable size="medium">
            <el-option v-for="(item, i) in userLevType" :key="i" :label="item.channelName"
              :value="item.payChannel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付类型" prop="payType">
          <el-select v-model="queryParams.payType" placeholder="请选择支付类型" clearable size="medium">
            <el-option v-for="(item, i) in sortLevType" :key="i" :label="item.typeName" :value="item.payType"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="" size="medium" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table stripe v-loading="loading" :data="infoList">
        <el-table-column label="序号" align="center" prop="id" />
        <el-table-column label="账户编号" align="center" prop="accountNo" min-width="100" />
        <el-table-column label="支付类型" align="center" prop="typeName" />
        <el-table-column label="渠道类型" align="center" prop="channelName" />
        <el-table-column label="账户冻结金额(元)" align="center" prop="frozenCapital" />
        <el-table-column label="账户在途金额(元)" align="center" prop="transitCapital" />
        <el-table-column label="账户可提余额(元)" align="center" prop="useCapital" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="150">
          <template slot-scope="scope">
            <el-button size="small" type="text" style="color: #006EFF;"
              @click="updateBalance(scope.row, 'formUpdate')">修改余额</el-button>
            <el-button size="small" type="text" style="color: #006EFF;"
              @click="handlePrivateTransfer(scope.row, 'formDai')"
              v-hasPermi="['order:rechargeRecord:storePaymentSave']">私户转入</el-button>
            <el-button size="small" type="text" style="color: #006EFF;" @click="handleFrozen(scope.row, 'formFro')"
              v-hasPermi="['order:rechargeRecord:frozenCapitalSave']">资金冻结</el-button>
            <el-button size="small" type="text" style="color: #006EFF;" @click="handleTransfer(scope.row, 'formTrans')"
              v-hasPermi="['order:rechargeRecord:transferCapitalSave']">资金划转</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" />
    </div>


    <!-- 资金冻结 -->
    <el-dialog v-dialogDrag :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false"
      :before-close="cancel">
      <el-form ref="formFro" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="账户编号" prop="accountNo">
          <span style="color:red">{{ detailData.accountNo }}</span>
        </el-form-item>
        <el-form-item label="所属渠道" prop="channelName">
          <span style="color:red">{{ detailData.channelName }}</span>
        </el-form-item>
        <el-form-item label="当前账户余额" prop="useCapital">
          <span style="color:red">{{ detailData.useCapital }}</span>（元）
        </el-form-item>

        <el-form-item label="冻结金额(元)" prop="frozenCapital">
          <el-input v-model="form.frozenCapital" placeholder="请输入冻结金额" />
        </el-form-item>

        <el-form-item label="支付密码" prop="pwd">
          <el-input type="password" v-model="form.pwd" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="谷歌动态验证码" prop="googleCode">
          <el-input v-model="form.googleCode" placeholder="请输入谷歌动态验证码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('frozen', 'formFro')">确 定</el-button>
        <el-button @click="cancel('formFro')">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 资金划转 -->
    <el-dialog v-dialogDrag title="资金划转" :visible.sync="openTransfer" width="600px" append-to-body
      :close-on-click-modal="false" :before-close="cancel">
      <el-form ref="formTrans" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="转出账户编号" prop="accountNo">
          <span style="color:red">{{ detailData.accountNo }}</span>
        </el-form-item>
        <el-form-item label="转出类型" prop="payType">
          <span style="color:red">{{ detailData.payType }}</span>
        </el-form-item>
        <el-form-item label="转出渠道" prop="channelType">
          <span style="color:red">{{ detailData.channelType }}</span>
        </el-form-item>

        <el-form-item label="转入账户" prop="toAccountNo">
          <el-select v-model="form.toAccountNo" placeholder="请选择转入账户" clearable size="medium">
            <el-option v-for="(item, i) in accountCon" :key="i" :label="item.accountNo"
              :value="item.accountNo"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="当前账户余额" prop="useCapital">
          <span style="color:red">{{ detailData.useCapital }}</span>（元）
        </el-form-item>
        <el-form-item label="划转金额(元)" prop="transferCapital">
          <el-input v-model="form.transferCapital" placeholder="请输入划转金额"
            oninput="value=value.replace(/[^\d.]/g,'').replace(/^\./g, '').replace(/\.{2,}/g, '').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').match(/^\d*(\.?\d{0,4})/g)[0] || null" />
        </el-form-item>
        <el-form-item label="支付密码" prop="pwd">
          <el-input type="password" v-model="form.pwd" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="谷歌动态验证码" prop="googleCode">
          <el-input v-model="form.googleCode" placeholder="请输入谷歌动态验证码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('transfer', 'formTrans')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 私户转入 -->
    <el-dialog v-dialogDrag title="代付" :visible.sync="openBank" width="600px" append-to-body :close-on-click-modal="false"
      :before-close="cancel">
      <el-form ref="formDai" :model="form" :rules="rules" label-width="120px">
        <div>
          <span style="font-size:19px">代付银行卡</span>
          <el-divider></el-divider>
        </div>
        <div v-if="isCoin == 'N'">
          <el-form-item label="出金通道" prop="bankId">
            <el-select v-model="form.bankId" placeholder="请选择出金通道" clearable size="medium" @change="getValue">
              <el-option v-for="(item, i) in bankCon" :key="i" :label="item.bankName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="银行卡号" prop="acctId">
            <el-input v-model="form.acctId" placeholder="请输入银行卡号" />
          </el-form-item>
          <el-form-item label="支行名称" prop="bankBranchName">
            <el-input v-model="form.bankBranchName" placeholder="请输入支行名称" />
          </el-form-item>
          <el-form-item label="支行联行号" prop="bankSettleNo">
            <el-input v-model="form.bankSettleNo" placeholder="请输入支行联行号" />
          </el-form-item>
          <el-form-item label="开户人姓名" prop="acctName">
            <el-input v-model="form.acctName" placeholder="请输入开户人姓名" />
          </el-form-item>
          <el-form-item label="用户预留手机号" prop="mobile">
            <el-input v-model="form.mobile" placeholder="请输入用户预留手机号" />
          </el-form-item>
        </div>

        <el-form-item label="钱包收款地址" prop="acctId" v-else>
          <el-input v-model="form.acctId" placeholder="请输入钱包收款地址" />
        </el-form-item>

        <div>
          <span style="font-size:19px">代付金额</span>
          <el-divider></el-divider>
        </div>

        <el-form-item label="可代付金额" prop="useCapital">
          <span>{{ detailData.useCapital }}</span>元
        </el-form-item>
        <el-form-item label="本次代付金额" prop="paymentAmount">
          <el-input v-model="form.paymentAmount" placeholder="请输入本次代付金额"
            oninput="value=value.replace(/[^\d.]/g,'').replace(/^\./g, '').replace(/\.{2,}/g, '').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').match(/^\d*(\.?\d{0,4})/g)[0] || null" />
        </el-form-item>
        <el-form-item label="支付密码" prop="pwd">
          <el-input type="password" v-model="form.pwd" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="谷歌动态验证码" prop="googleCode">
          <el-input v-model="form.googleCode" placeholder="请输入谷歌动态验证码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('private', 'formDai')">确 定</el-button>
        <el-button @click="cancel('formDai')">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 余额修改 -->
    <el-dialog v-dialogDrag title="余额修改" :visible.sync="openBalance" width="600px" append-to-body
      :close-on-click-modal="false" :before-close="cancel">
      <el-form ref="formUpdate" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="账户号">
          {{ detailData.accountNo }}
        </el-form-item>
        <el-form-item label="余额" prop="useCapital">
          <span>{{ detailData.useCapital }}</span>元
        </el-form-item>
        <el-form-item label="类型" prop="isIncome">
          <el-radio-group v-model="form.isIncome" @change="change">
            <el-radio v-for="dict in type" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>



        <el-form-item label="金额（元）" prop="afterAmt">
          <el-input v-model="form.afterAmt" placeholder="请输入金额"
            oninput="value=value.replace(/[^\d.]/g,'').replace(/^\./g, '').replace(/\.{2,}/g, '').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').match(/^\d*(\.?\d{0,4})/g)[0] || null" />
        </el-form-item>
        <el-form-item label="谷歌动态验证码" prop="googleCode">
          <el-input v-model="form.googleCode" placeholder="请输入谷歌动态验证码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="subUpdateBalance('balance', 'formUpdate')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { payMoneyCalcu, common_api } from "@/api/form";
export default {
  name: "pkCouponScopeRangeStoreList",
  props: {
    pkCouponId: {
      type: String,
      default() {
        return "";
      },
    },
    pkCouponStore: {
      type: Object,
      default: {}
    }
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      let reg = /^1[345789]\d{9}$/
      if (!reg.test(value)) {
        callback(new Error('请输入11位手机号'))
      } else {
        callback()
      }
    }
    return {
      isCoin: null,
      type: [
        {
          label: '增加',
          value: 'yes'
        },
        {
          label: '减少',
          value: 'no'
        },
      ],
      // 用户默认的出金通道
      userWithdrawalChannel: {},
      accountCon: [],
      store: {},
      dateRange: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openTransfer: false,
      openBank: false,
      openBalance: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        storeId: null,
        payType: null,
        channelType: null,
      },
      sum: {
        freezeAmount: 0,
        gatherAmount: 0,
        onRouteAmount: 0,
        withdrawalAmount: 0,
      },

      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        afterAmt: [
          { required: true, message: "请输入本次修改金额", trigger: "blur" },
        ],
        paymentAmount: [
          { required: true, message: "请输入本次代付金额", trigger: "blur" },
        ],
        mobile: [
          { required: true, type: 'number', validator: checkPhone, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        acctName: [
          { required: true, message: "请输入开户人姓名", trigger: "blur" },
        ],
        bankSettleNo: [
          { required: true, message: "请输入支行联行号", trigger: "blur" },
        ],
        acctId: [
          { required: true, message: "请输入银行卡号", trigger: "blur" },
        ],
        bankBranchName: [
          { required: true, message: "请输入支行名称", trigger: "blur" },
        ],
        bankId: [
          { required: true, message: "请选择出金通道", trigger: "blur" },
        ],
        toAccountNo: [
          { required: true, message: "请选择划转账户", trigger: "blur" },
        ],
        transferCapital: [
          { required: true, message: "请输入划转金额", trigger: "blur" },
        ],
        pwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        googleCode: [
          { required: true, message: "请输入谷歌动态验证码", trigger: "blur" },
        ],

      },
      userLevType: [],
      sortLevType: [],
      detailData: {},
      bankCon: [],
    };
  },
  created() {
    this.pkCouponId && (this.queryParams.storeId = this.pkCouponId);
    this.getList();
    this.init();
  },
  methods: {
    // 获取银行的所有值
    getValue(e) {
      for (var i = 0; i < this.bankCon.length; i++) {
        if (e == this.bankCon[i].id) {
          this.form.bankSegment = this.bankCon[i].bankSegment
          this.form.bankName = this.bankCon[i].bankName
          this.form.bankCode = this.bankCon[i].bankCode
          this.form.bankEnglishShort = this.bankCon[i].bankEnglishShort
        }
      }
    },
    // 获取用户出金通道
    getUserWithdrawalChannel() {
      payMoneyCalcu.getUserWithdrawalChannel({ acctType: "debit_card", storeId: this.pkCouponStore.storeId })
        .then(res => {
          this.userWithdrawalChannel = res.data?.[0] ?? {};
          if (this.userWithdrawalChannel) {
            this.form = {
              ...this.form,
              acctId: this.userWithdrawalChannel.acctId,
              bankBranchName: this.userWithdrawalChannel.bankBranchName,
              bankSettleNo: this.userWithdrawalChannel.bankSettleNo,
              acctName: this.userWithdrawalChannel.acctName,
              mobile: this.userWithdrawalChannel.mobile,
            }
          }
        })
    },
    // 私户
    handlePrivateTransfer(row, v) {
      this.reset(v);
      this.loading = true;
      this.isCoin = row.isCoin
      // 获取用户出金
      this.getUserWithdrawalChannel();
      payMoneyCalcu.getWithdrawalChannel({
        channelType: row.channelType,
        flagCard: 'private_account'
      })
        .then((response) => {
          this.openBank = true;
          this.bankCon = response.data
          this.loading = false;
          // 获取虚拟资金
          payMoneyCalcu.getUserCapitalAccountDetail({
            accountNo: row.accountNo,
            storeId: this.queryParams.storeId
          })
            .then((response) => {
              this.form.accountNo = row.accountNo
              this.detailData = response.data
            });
        });
    },
    // 资金划转
    handleTransfer(row, v) {
      this.reset(v);
      this.form.storeId = this.pkCouponStore.storeId
      this.loading = true;
      // 获取虚拟资金
      payMoneyCalcu.getUserCapitalAccountDetail({
        accountNo: row.accountNo,
        storeId: this.queryParams.storeId
      })
        .then((response) => {
          this.openTransfer = true;
          this.detailData = response.data
          this.loading = false;
        });
      // 获取转账账户
      payMoneyCalcu.getAllAccountOrder({
        storeId: this.queryParams.storeId
      })
        .then((response) => {
          this.accountCon = response.data.rows
        });

    },
    // 余额修改
    subUpdateBalance(a, v) {
      var googleCode = this.form.googleCode
      this.$refs[v].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: `正在修改`,
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          payMoneyCalcu
            .updateBalance({
              accountNo: this.form.accountNo,
              googleCode: googleCode,
              updateUserId: this.form.updateUserId,
              isIncome: this.form.isIncome,
              tranAmt: this.form.afterAmt,
            })
            .then((response) => {
              loading.close();
              if (response.code == 200) {
                this.$message.success('修改成功')
                this.getList();
              }
              this.openBalance = false
            })
            .catch(() => {
              loading.close();
            });
        }
      });
    },
    /** 提交按钮 */
    submitForm(type, val) {
      if (type == 'private') {
        this.form.storeId = this.pkCouponStore.storeId
        if (this.form.paymentAmount > this.detailData.useCapital) {
          this.$message.error('余额不足')
          return;
        }
        this.$refs[val].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: `正在代付`,
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)",
            });
            if (this.isCoin == 'N') {
              payMoneyCalcu
                .storePaymentSave(this.form)
                .then((response) => {
                  loading.close();
                  if (response.code == 200) {
                    this.$message.success('代付资金提交成功')
                  }
                  this.openBank = false
                  this.getList()
                })
                .catch(() => {
                  loading.close();
                });
            }
            if (this.isCoin == 'Y') {
              payMoneyCalcu
                .storePaymentCurrencySave(this.form)
                .then((response) => {
                  loading.close();
                  if (response.code == 200) {
                    this.$message.success('代付资金提交成功')
                  }
                  this.openBank = false
                  this.getList()
                })
                .catch(() => {
                  loading.close();
                });
            }

          }
        });
      }
      if (type == 'transfer') {
        if (this.form.transferCapital > this.detailData.useCapital) {
          this.$message.error('余额不足')
          return;
        }

        this.$refs[val].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: `正在划转资金`,
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)",
            });
            this.form.accountNo = this.detailData.accountNo
            payMoneyCalcu
              .transferCapitalSave(this.form)
              .then((response) => {
                loading.close();
                if (response.code == 200) {
                  this.$message.success('划转资金提交成功')
                }
                this.openTransfer = false
                this.getList()
              })
              .catch(() => {
                loading.close();
              });
          }
        });
      } else if (type == 'frozen') {
        if (this.form.frozenCapital > this.detailData.useCapital) {
          this.$message.error('余额不足')
          return;
        }
        this.$refs[val].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: `正在冻结资金`,
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)",
            });
            payMoneyCalcu
              .frozenCapital(this.form)
              .then((response) => {
                loading.close();
                if (response.code == 200) {
                  this.$message.success('冻结成功')
                }
                this.open = false
                this.getList()
              })
              .catch(() => {
                loading.close();
              });
          }
        });
      }

    },
    // 手动修改余额
    updateBalance(row, v) {
      this.reset(v);
      this.detailData = row
      this.form.accountNo = row.accountNo
      this.form.updateUserId = row.userId
      this.form.isIncome = 'yes'
      this.openBalance = true;
    },
    // 资金冻结
    handleFrozen(row, v) {
      this.reset(v);
      this.detailData = row
      this.form.storeId = this.pkCouponStore.storeId
      this.form.accountNo = this.detailData.accountNo
      this.form.frozenType = 'frozen'
      this.open = true;
      this.title = '资金冻结';
    },
    /** 查询 */
    getList() {
      this.loading = true;
      payMoneyCalcu.capitalList(this.addSESDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          this.infoList = response.data.rows;
          this.total = Number(response.data.total)
          this.loading = false;
        });
      payMoneyCalcu.amountCount({
        storeId: this.pkCouponStore.storeId,
        channelType: '',
        payType: '',
      })
        .then((response) => {
          this.sum = response.data
        });
    },
    init() {
      common_api.payChannelAll().then((response) => {
        this.userLevType = response.data
      });
      common_api.payTypeAll().then((response) => {
        this.sortLevType = response.data
      });
    },
    // 取消按钮
    cancel(type) {
      this.open = false;
      this.openTransfer = false;
      this.openBank = false
      this.openBalance = false
      this.reset(type);
    },
    // 表单重置
    reset(type) {
      this.form = {};
      this.detailData = {};
      this.resetForm(type);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加适用商家";
    },
    change() {
      this.$forceUpdate()
    },
    selectChange(data) {
      this.$set(this.form, 'storeName', data.storeName)
      this.form.pkStoreId = data.id;
      this.$nextTick(() => {
        this.$refs.pkParkingInfoIdRef.clearValidate();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-divider--horizontal {
  margin: 8px 0;
}

.bg {
  border-radius: 0;
  background: #fff;
  box-shadow: none;
  border-color: rgba(0, 0, 0, 0.05);
  padding: 0px 0;
}

.app-container {
  margin: 0;
  padding: 0;
}

.el-radio {
  line-height: 2;
}
</style>
