<template>
  <div class="app-container">
    <div class="sty" v-show="show">
      <el-page-header @back="goBack"> </el-page-header>
    </div>
    <br />
    <!-- 筛选条件 -->
    <div v-if="show2">
      <el-form ref="searchForm" :model="searchForm" :rules="rulesSearchForm" label-width="100px" size="mini" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="经销商名称" prop="customerId">
              <el-select class="selectStyle" v-model="searchForm.customerId" placeholder="请选择" filterable>
                <el-option v-for="(v, i) in customerList" :key="i" :label="v.name" :value="v.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="18">
            <el-form-item label="" class="fr">
              <el-button size="mini" @click="resetFn">清空</el-button>
              <el-button size="mini" type="primary" @click="searchFn">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 按钮 -->
    <div class="btn-group clearfix">
      <div class="fr">
        <el-button type="primary" size="mini" @click="exportFn">导出</el-button>
      </div>
    </div>
    <el-row>
      <el-col :xs="24" :sm="12" :lg="12">
        <div class="styl">现金钱包</div>
      </el-col>
      <!-- <el-col :xs="24" :sm="12" :lg="12">
        <div class="fr">
          <el-button size="small" type="primary" @click="generateFn"
            >一键生成钱包</el-button
          >
        </div>
      </el-col> -->
    </el-row>
    <el-divider></el-divider>
    <!-- 列表 -->
    <div class="mymain-container">
      <div class="table">
        <el-table v-loading="listLoading" :data="walletList" element-loading-text="Loading" border fit highlight-current-row stripe show-summary :summary-method="$getSummaries">
          <el-table-column align="left" label="经销商名称" prop="customerName" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <CopyButton :copyText="scope.row.customerName" />
              <span>{{scope.row.customerName}}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="钱包" prop="name" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" label="更新时间" prop="updateTime" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="right" label="余额" prop="amount" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.amount | numToFixed }}
            </template>
          </el-table-column>
          <el-table-column align="right" label="可用信用额度" prop="freeCreditAmount" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.freeCreditAmount | numToFixed }}
            </template>
          </el-table-column>
          <el-table-column align="right" label="已用信用额度" prop="usedCreditAmount" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.usedCreditAmount | numToFixed }}
            </template>
          </el-table-column>

        </el-table>
      </div>
    </div>
    <span>返利钱包</span>
    <el-divider></el-divider>
    <!-- 列表 -->
    <div class="mymain-container">
      <div class="table">
        <el-table v-loading="listLoading" :data="rebateList" element-loading-text="Loading" border fit highlight-current-row stripe show-summary :summary-method="$getSummaries">
          <el-table-column align="left" label="经销商名称" prop="customerName" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <CopyButton :copyText="scope.row.customerName" />
              <span>{{scope.row.customerName}}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="返利钱包" prop="name" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" label="更新时间" prop="updateTime" min-width="160" show-overflow-tooltip></el-table-column>

          <el-table-column align="right" label="钱包余额" prop="amount" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.amount | numToFixed }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            align="center"
            label="操作"
            min-width="160"
            show-overflow-tooltip
          >
            <template v-slot="{ row }">
              <el-button
                v-if="$checkBtnRole('edit', $route.meta.roles)"
                type="text"
                class="textColor"
                @click="editFn(row)"
              >
                修改
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog title="配置返利比例" :visible.sync="dialogForm" width="30%" :show-close="false" :close-on-click-modal="false">
      <el-form ref="addForm" :rules="rules" :model="addForm" label-width="100px">
        <el-form-item label="返利比例" prop="rebateRate">
          <el-input v-model.number="addForm.rebateRate" oninput="if(value>100)value=100;if(value<0)value=0"><i class="el-input__icon" slot="suffix">% </i></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button type="primary" @click="determineFn">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 导出弹窗 -->
    <el-dialog title="导出" :visible.sync="dialogExportForm" width="30%" :show-close="false" :close-on-click-modal="false">
      <el-form ref="exportForm" :rules="exportRules" :model="exportForm" label-width="120px">
        <el-form-item label="编码范围" prop="">
          <div class="fanwei">
            <el-input v-model="exportForm.startCustomerId" type="number"></el-input>
            <span>——</span>
            <el-input v-model="exportForm.endCustomerId" type="number"></el-input>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportCancelFn">取 消</el-button>
        <el-button type="primary" @click="exportOKFn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getfinanceInit,
  getWalletRebateRateUpdate,
  getCustomerList,
} from "@/api/finance/wallet";
import { downloadFiles } from "@/utils/util";
import { getWalletCustomerList } from "@/api/finance/change_apply";
export default {
  data() {
    return {
      dialogExportForm: false,
      exportRules: {},
      exportForm: {
        endCustomerId: "",
        startCustomerId: "",
      },
      isShow: JSON.parse(localStorage.getItem("supply_user")).isCustomer,
      show: false,
      show2: true,
      searchForm: {
        customerId: null,
      },
      customerList: [],
      listLoading: false, // 列表加载loading
      walletList: [],
      rebateList: [],
      addForm: {
        rebateRate: null,
      },
      dialogForm: false,
      rulesSearchForm: {
        customerId: [
          {
            required: true,
            message: "请选择经销商",
            trigger: "blur",
          },
        ],
      },
      rules: {
        rebateRate: [
          {
            required: true,
            message: "请输入返利比例",
            trigger: "blur",
          },
        ],
      },
    };
  },
  beforeRouteEnter(to, from, next) {
    // console.log(11112222);
    // console.log(to, from, next, 898);
    next((vm) => {
      // 这个时候组件还没有创建，所以要通过vm来访问
      if (
        from.path == "/finance/details/balance_sum" &&
        to.path == "/finance/details/wallet" &&
        vm.$route.query.id
      ) {
        //只有是从A进到B页面才执行
        // 将要执行的逻辑
        vm.show = true;
        vm.show2 = false;
        vm.getDataWallet({
          customerId: vm.$route.query.id,
          type: "COMMONLY",
        });
        vm.getDataRebate({
          customerId: vm.$route.query.id,
          type: "REBATE",
        });
      } else {
        if (vm.isShow) {
          vm.show2 = false;
          vm.getDataWallet({
            customerId: vm.customerId,
            type: "COMMONLY",
          });
          vm.getDataRebate({
            customerId: vm.customerId,
            type: "REBATE",
          });
        } else {
          vm.show = false;
          vm.show2 = true;
          vm.walletList = [];
          vm.rebateList = [];
          vm.$message("请选择经销商");
          vm.getCustomerDataList();
        }
      }
    });
  },

  created() {
    // console.log(this.$route.query.id, 11, this.customerId);
    // if (this.$route.query.id) {
    //   this.getDataWallet({
    //     customerId: this.$route.query.id,
    //     type: "COMMONLY",
    //   });
    //   this.getDataRebate({
    //     customerId: this.$route.query.id,
    //     type: "REBATE",
    //   });
    // } else {
    //   if (this.isShow) {
    //     this.getDataWallet({
    //       customerId: this.customerId,
    //       type: "COMMONLY",
    //     });
    //     this.getDataRebate({
    //       customerId: this.customerId,
    //       type: "REBATE",
    //     });
    //   } else {
    //     this.$message("请选择经销商");
    //     this.getCustomerDataList();
    //   }
    // }
  },
  computed: {
    ...mapGetters(["customerId"]),
  },
  methods: {
    exportCancelFn() {
      this.exportForm = {
        endCustomerId: "",
        startCustomerId: "",
      };
      this.dialogExportForm = false;
    },
    exportOKFn() {
      downloadFiles("/wallet/count/export", { ...this.exportForm });
      this.exportForm = {
        endCustomerId: "",
        startCustomerId: "",
      };
      this.dialogExportForm = false;
    },
    //导出
    exportFn() {
      this.dialogExportForm = true;
      // downloadFiles("/wallet/count/export");
    },
    //清空
    resetFn() {
      this.$refs.searchForm.resetFields();
    },
    //搜索
    async searchFn() {
      await this.$refs.searchForm.validate();
      this.getDataWallet({
        customerId: this.searchForm.customerId,
        type: "COMMONLY",
      });
      this.getDataRebate({
        customerId: this.searchForm.customerId,
        type: "REBATE",
      });
    },
    //获取经销商列表
    async getCustomerDataList() {
      let res = await getCustomerList({
        pageNum: 1,
        pageSize: -1,
      });
      this.customerList = res.data.records;
    },
    //返回
    goBack() {
      this.$router.go(-1);
      this.$store.dispatch("tagsView/delView", this.$route);
    },
    //取消
    async cancelFn() {
      this.dialogForm = false;
      await this.$refs.addForm.clearValidate();
    },
    //确定
    async determineFn() {
      await this.$refs.addForm.validate();
      const res = this.addForm.rebateRate / 100;
      this.addForm.rebateRate = res;
      await getWalletRebateRateUpdate({ ...this.addForm });
      if (this.$route.query.id) {
        this.getDataRebate({
          customerId: this.$route.query.id,
          type: "REBATE",
        });
      } else {
        this.getDataRebate({
          customerId: this.searchForm.customerId,
          type: "REBATE",
        });
      }
      this.$message.success("修改成功");
      this.dialogForm = false;
    },
    //修改
    editFn(v) {
      this.addForm.customerWalletId = v.customerWalletId;
      this.addForm.rebateRate = v.rebateRate * 100;
      this.dialogForm = true;
    },
    // //一键生成
    // async generateFn() {
    //   await getfinanceInit({ customerId: this.customerId });
    //   this.getDataWallet();
    //   this.getDataRebate();
    //   this.$message.success("已生成");
    // },
    //
    async getDataRebate(data) {
      let res = await getWalletCustomerList(data);
      res.data.forEach((item) => {
        item.sums1 = [];
        item.sums2 = ["amount"];
      });
      this.rebateList = res.data;
    },
    async getDataWallet(data) {
      let res = await getWalletCustomerList(data);
      res.data.forEach((item) => {
        item.sums1 = [];
        item.sums2 = ["amount", "freeCreditAmount", "usedCreditAmount"];
      });
      this.walletList = res.data;
    },
  },
};
</script>

<style lang="scss" scoped>
.fanwei {
  display: flex;
  span {
    margin: 0 20px;
  }
}
.styl {
  padding-top: 14px;
}
.selectStyle {
  width: 100%;
}
</style>
