<template>
  <div class="app-container">
    <el-card>
      <!-- 商品信息 -->
      <div class="card-header-custom">
        <div class="card-header-title">
          <span class="blue-block blue-block-goods-title"></span>账号资产
        </div>
        <div class="card-header-handle">
          <el-button plain type="primary" size="small" @click="explainWithdrawal">提现说明</el-button>
          <el-button plain type="primary" size="small" @click="goToWithdrawlog">提现记录</el-button>
        </div>
      </div>
      <div class="row-flex-center">
        <div class="current-balance">
          <dl class="balance-dl">
            <dt>当前余额（元）</dt>
            <dd>￥{{ currentBalance }}</dd>
          </dl>
          <p class="in-details-balance" @click="goToBalance">收支明细</p>
        </div>
        <div class="withdrawal-balance">
          <dl class=" balance-dl dl-border">
            <dt>可提现余额（元）</dt>
            <dd>￥{{ withdrawalBalance }}</dd>
          </dl>
        </div>
        <div class="withdrawal-progress">
          <dl class=" balance-dl">
            <dt>提现中的金额（元）</dt>
            <dd>￥{{ withdrawalProgress }}</dd>
          </dl>
        </div>
      </div>
      <div class="row-flex-center">
        <el-button type="primary" size="small" style="padding: 10px 30px; margin: 20px 0 40px;" @click="handleWithdraw">提 现</el-button>
      </div>

      <!-- 账号管理 -->
      <div class="card-header-custom">
        <div class="card-header-title">
          <span class="blue-block blue-block-goods-title"></span>账户管理
        </div>
      </div>

      <div class="row-flex-space-around">
        <div class="card-con" v-for="(item,index) in bankcardList" :key="index">
          <div class="card-info-con">
            <div class="card-name">{{ item.bank_name }}</div>
            <div class="bank-detail">
              <p>对公账户名称：{{ item.corporate_account_name }}</p>
              <p>银行名称：{{ item.bank_name }}</p>
              <p>对公银行账号：{{ item.bank_account_sn }}</p>
              <p>开户行（支行）：{{ item.bank_branch_name }}</p>
            </div>
          </div>
          <div class="card-info-handle">
            <el-button plain type="primary" size="mini" style="padding: 10px 30px; margin: 20px 40px 40px 0;" @click="editBankcard(item.id)">编 辑</el-button>
            <el-button plain type="primary" size="mini" style="padding: 10px 30px; margin: 20px 0 40px;" @click="delBankcard(item.id)">删 除</el-button>
          </div>
        </div>

        <div v-if="bankcardList.length < 3" class="hh-card-con" :class="{ 'only-add-con' : bankcardList.length == 0 ? true: false }">
          <div class="add-card-con">
            <div class="add-card-btn" @click="addBankcard">+</div>
          </div>
        </div>
      </div>

<!--      <div class="row-flex-center">-->
<!--        <el-button type="primary" size="small" style="padding: 10px 30px; margin: 20px 40px 40px 0;">编 辑</el-button>-->
<!--        <el-button type="primary" size="small" style="padding: 10px 30px; margin: 20px 0 40px;">删 除</el-button>-->
<!--      </div>-->
    </el-card>

    <!-- 添加、编辑 银行卡 信息 -->
    <el-dialog
      :title="bankcardTitle"
      :visible.sync="addBankcardInfoDialog"
      :before-close="cancelSubmitBankcard"
      center
    >
        <el-form ref="bankcardForm" :model="bankcardForm" :rules="bankcardRule" size="small" label-width="180px">
          <el-form-item label="账号类型：">
            <el-input type="text" placeholder="银行对公账户" :disabled="true" style="width: 70%;"></el-input>
            <p class="withdraw-tip">
              根据要求，提现仅支持公对公账户
            </p>
          </el-form-item>

          <el-form-item label="银行名称：" prop="bank_name" >
            <el-select v-model="bankcardForm.bank_name" placeholder="请选择" style="width: 70%;">
              <el-option
                v-for="item in bankOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="对公账户名称：" style="width:100%" prop="bankAccountName">
            <el-input v-model="bankcardForm.bankAccountName" placeholder="对公账户名称，不能输入和修改" :disabled="true" style="width: 70%"></el-input>
            <p class="withdraw-tip">
              银行卡必须为对公账户，且与提交的公司名称相一致，不允许修改
            </p>
          </el-form-item>

          <el-form-item label="开户行（支行）：" prop="bank_branch_name">
            <el-input v-model="bankcardForm.bank_branch_name" placeholder="请输入开户行" style="width: 70%"></el-input>
          </el-form-item>

          <el-form-item label="对公银行账号：" prop="bank_account_sn">
            <el-input v-model="bankcardForm.bank_account_sn" placeholder="请输入快递单号" style="width: 70%"></el-input>
          </el-form-item>

          <el-form-item>
            <span class="withdraw-tip">温馨提示：所有项均为必填项，请正确填写相关信息，信息填写错将导致提现无法成功</span>
          </el-form-item>

        </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitBankcard">确 定</el-button>
        <el-button size="small" @click="cancelSubmitBankcard">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getMyAssetListData,getOrganizationData, getBankDetailsData,getBankcardListData, addBankcardData,editBankcardData ,delBankcardData } from '@/api/module/bankcard'
  export default {
    name: "Index",
    data() {
      return {
        seller_id: '',
        currentBalance: 0,
        withdrawalBalance: 0,
        withdrawalProgress: 0,
        bankcardList: [],
        addBankcardInfoDialog: false,
        bankcardTitle: '',
        bankAccountName: '', // 主体信息 公司名称
        bankcardForm: {
          bank_name: '',
          bankAccountName: '',
          bank_branch_name: '',
          bank_account_sn: '',
        },
        bankcardRule: {
          bank_name: [{required: true,message: '银行名称不能为空',trigger: 'change'}],
          bankAccountName: [{required: true,message: '对公账户不能为空',trigger: 'change'}],
          bank_branch_name: [{required: true,message: '开户行支行不能为空',trigger: 'blur'}],
          bank_account_sn: [{ required: true,message: '银行账号不能为空',trigger: 'blur'}]
        },
        bankOptions: [], // 银行卡列表
        indexId: 0,
      } // return end
    },// data end
    created() {
      /** 获取 seller_id*/
      this.seller_id = this.$store.state.user.sellerid;
      /** 我的资产 所有数据 */
      this.getMyAssetList()
      /** 获取 银行卡列表 */
      this.getBankcardList()
      /** 获取主体信息 */
      this.getOrganization();
    },
    methods: {
      /** 我的资产 所有数据 */
      getMyAssetList() {
        getMyAssetListData( {seller_id:this.seller_id} ).then(res=> {
          if(res.code == 1 && res.data) {
            // 账号资产
            if(res.data.account_info ) {
              this.withdrawalBalance = Number(res.data.account_info.new_balance) / 100;
              this.withdrawalProgress = Number(res.data.account_info.new_frozen_money) / 100;
              this.currentBalance = this.add(this.withdrawalBalance,this.withdrawalProgress);
            }
            // 账户管理
            if(res.data.bank_list) {
              this.bankcardList = res.data.bank_list;
            }
          }else {
            let msg = res.message ? res.message : '获取用户列表失败'
            this.$message({type:'error',message: msg});
          }
        });
      },

      /** 获取主体信息 */
      getOrganization() {
        getOrganizationData().then(res=> {
          if(res.code == 1 && res.data) {
            this.bankAccountName = res.data.organization_name;
          }
        });
      },

      /** 编辑 银行卡信息 */
      editBankcard(id) {
        this.bankcardTitle = '编辑账户'
        this.indexId = id;
        getBankDetailsData({ id: id }).then(res=> {
          if(res.code == 1 && res.data) {
            this.addBankcardInfoDialog = true;
            this.bankcardForm.bank_name = res.data.bank_name;
            this.bankcardForm.bankAccountName = res.data.corporate_account_name;
            this.bankcardForm.bank_branch_name = res.data.bank_branch_name;
            this.bankcardForm.bank_account_sn = res.data.bank_account_sn;
          }else {
            let msg = res.message ? res.message : '获取银行卡信息失败'
            this.$message({type:'error',message: msg});
          }
        });
      },

      /** 删除 银行卡信息 */
      delBankcard(id) {
        const indexId = id;
        this.$confirm('确定要删除该账户信息吗？','警告',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async ()=> {
          let delResult = await delBankcardData({id: indexId});
          console.log('删除结果',delResult);
          if (delResult.code == 1) {
            this.$message({type:'success',message:'删除成功'});
            this.getMyAssetList();
          }
          if (delResult.code == 0) {
            let msg = delResult.message ? delResult.message : '删除失败'
            this.$message({type:'error',message: msg });
          }
        }).catch(()=> {});
      },

      /** 添加 银行卡信息 */
      addBankcard() {
        this.bankcardTitle = '添加账户'
        this.addBankcardInfoDialog = true;
        this.indexId = 0;
      },

      /** 提交 添加银行卡信息 */
      submitBankcard() {
        let params = {
          bank_name: '',
          bank_branch_name: this.bankcardForm.bank_branch_name,
          bank_account_sn: this.bankcardForm.bank_account_sn
        }

        for (let i = 0; i < this.bankOptions.length; i++) {
          if (this.bankcardForm.bank_name == this.bankOptions[i].code) {
            params.bank_name = this.bankOptions[i].name
            break
          }
        }

        this.$refs.bankcardForm.validate((valid)=> {
          if (valid) {
            // 新增
            if (this.indexId == 0) {
              params['seller_id'] = this.seller_id;
              addBankcardData(params).then(res=> {
                if(res.code == 1) {
                  this.$message({type:'success',message: '新增成功'});
                  this.addBankcardInfoDialog = false;
                  this.resetAddBankcardForm();
                  this.getMyAssetList(); // 更新数据
                }else {
                  this.$message({type:'error',message:  res.message ? res.message : '新增失败' });
                }
              });
            }else {
              params['id'] = this.indexId
              editBankcardData(params).then(res=> {
                if(res.code == 1) {
                  this.$message({type:'success',message: '修改成功'});
                  this.addBankcardInfoDialog = false;
                  this.resetAddBankcardForm();
                  this.getMyAssetList(); // 更新数据
                }else {
                  this.$message({type:'error',message:  res.message ? res.message : '修改失败' });
                }
              });
            }
          } // valid end
        });

      },

      /** 取消 提交 添加银行卡信息*/
      cancelSubmitBankcard() {
        this.resetAddBankcardForm();
        this.addBankcardInfoDialog = false;
      },

      /** 初始化 添加 银行卡 数据 */
      resetAddBankcardForm() {
        this.$refs['bankcardForm'].resetFields();
        //this.bankcardForm.bankAccountName = this.bankAccountName
      },

      /** 提现 操作 */
      handleWithdraw() {
        this.$router.push({ path: "/system/asset/withdraw" });
      },

      /** 收支明细 跳转 */
      goToBalance() {
        this.$router.push({ path: "/system/asset/balance" });
      },

      /** 提现记录*/
      goToWithdrawlog() {
        this.$router.push({ path: "/system/asset/withdrawlog" });
      },

      /** 提现说明 */
      explainWithdrawal() {
        this.$router.push({ path: "/system/asset/explain" });
      },

      /** 获取 银行列表 */
      getBankcardList() {
        getBankcardListData().then(res=> {
          if(res.code == 1 && res.data) {
            this.bankOptions = res.data
          }else {
            let msg = res.message ? res.message : '获取银行列表失败'
            this.$message({type:'error',message: msg});
          }
        });
      },
      // 自定义高精度浮点数运算
      // 加法
      add(arg1, arg2) {
        let r1, r2, m, result;
        try {
          //取小数位长度
          r1 = arg1.toString().split(".")[1].length;
          r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
          r1 = 0;
          r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));		//计算因子
        result = (arg1 * m + arg2 * m) / m;
        result = result.toFixed(2);
        return result;
      },
      // 减法
      minus(arg1, arg2) {
        return this.add(arg1, -arg2);
      },
    } // methods end
  }
</script>

<style scoped>
  .app-container {
    overflow: auto;
  }
  /* el-card title hxz 样式统一 start */
  .card-header-custom {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #F6F6F8;
    padding-bottom: 15px;
  }
  .card-header-title {
    line-height: 24px;
    font-size: 18px;
    color: #000;
    font-weight: bold;
  }

  .blue-block {
    display: inline-block;
    width: 5px;
    height: 24px;
    background: #3A84FF;
    margin: 0 9px 0 0;
    border-radius: 2px;
    vertical-align: bottom;
  }

  .current-balance,.withdrawal-balance,.withdrawal-progress {
    flex: 1;
    margin: 30px 0;
    background-color: #F8FBFD;
  }
  .current-balance {
    position: relative;
  }

  .balance-dl {
    padding: 20px 0;
    margin: 20px 0;
  }

  .dl-border {
    border-right: 2px solid #E8E7E7;
    border-left: 2px solid #E8E7E7;
  }

  .balance-dl > dt,.balance-dl > dd {
    text-align: center;
    margin: 20px 0;
    padding: 0;
  }
  .balance-dl > dt {
    height: 36px;
    font-size: 16px;
    font-weight: bold;
    color: #333333;
    line-height: 36px;
    padding-left: 16px;
  }
  .balance-dl > dd {
    height: 36px;
    font-size: 34px;
    font-weight: bold;
    color: #40A3FC;
    line-height: 36px;
  }

  .in-details-balance {
    position: absolute;
    height: 20px;
    line-height: 20px;
    font-size: 14px;
    font-weight: 400;
    color: #40A3FC;
    cursor: pointer;
    bottom: 6px;
    left: calc(50% - 26px);
  }

  /* el-card title hxz 样式统一 end */
  .row-flex-center {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }

  .row-flex-space-around {
    display: flex;
    flex-direction: row;
    justify-content: start;
    align-items: center;
    flex-wrap: wrap;
  }

  .mp20 {
    margin: 30px;
    padding: 10px 20px;
  }

  .card-con {

  }

  .card-info-con {
    width: 468px;
    height: 274px;
    margin: 20px;
    box-shadow :0 2px 10px 0 rgba(0,0,0,0.05);
  }

  .hh-card-con {
    width: 468px;
    height: 366px;
  }

  .only-add-con {
    margin: 20px 0;
  }

  .add-card-con {
    width: 468px;
    height: 274px;
    box-shadow :0 2px 10px 0 rgba(0,0,0,0.05);
  }

  /*.card-con:hover {*/
  /*  box-shadow :0 2px 10px 0 rgba(0,0,0,0.1);*/
  /*}*/

  /* 点击效果 */
  .checked-bankcard {

  }

  .card-name {
    height: 60px;
    line-height: 60px;
    text-align: center;
    color: #fff;
    border-radius: 5px 5px 0px 0px;
    background: #40A3FC;
  }

  .bank-detail {
    padding: 10px 20px;
    font-size: 14px;
    font-weight: 400;
    color: #333333;
    line-height: 30px;
  }

  .add-card-con {
    background: #F8FBFD;
    border: 1px dashed #D7D7D8;
    border-radius: 5px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }

  .add-card-btn {
    padding: 50px;
    line-height: 30px;
    text-align: center;
    font-size: 24px;
    cursor: pointer;
    color: #666;
  }

  .card-info-handle {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }

  .withdraw-tip {
    font-size:12px;
    color: #999;
    margin: 5px;
    line-height: 26px;
  }

</style>
