<template>
    <div class="page">
      <topBar
        v-if="topList.length > 0"
        :topList="topList"
        :moren="moren"
      ></topBar>
      <div v-if="topList[0].changed==true">
        <div class="main">
          <el-form ref="form" :model="form" label-width="100px">
            <el-form-item :label="'操作类型'">
              <el-select clearable :placeholder="'请选择'" v-model="form.czlx">
                <el-option
                  v-for="item in cztypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <template v-if="form.czlx == 1">
              <el-form-item :label="'会员编号'">
                <el-input
                  clearable
                  style="width: 200px"
                  v-model="form.memberCode"
                  @blur="checkName"
                ></el-input>
              </el-form-item>
              <el-form-item :label="'会员姓名'">
                <el-input
                  clearable
                  style="width: 200px"
                  v-model="form.memberName"
                  disabled
                ></el-input>
              </el-form-item>
            </template>
            <template v-if="form.czlx == 2">
              <div class="mainbtn">
                <el-button size="small" class="thebtn1" @click="handleImport"
                > {{ '导入' }}</el-button
                >
                <el-button size="small" class="thebtn2" @click="importTemplate"
                > {{ '下载模板' }}</el-button
                >
              </div>
              <div class="tableBox" style="padding: 0; margin-bottom: 10px">
                <el-table
                  :data="changeMemberTable"
                  style="width: 100%"
                  :header-cell-style="{ background: '#EEEEEE' }"
                >
                  <el-table-column
                    align="center"
                    prop="memberCode"
                    :label="'会员编号'"
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="memberName"
                    :label="'会员姓名'"
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="account2"
                    :label="`${'现金余额'}(${getUser.currency.symbol})`"
                    :formatter="stateFormat"
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="account4"
                    :label="`${'奖金余额'}(${getUser.currency.symbol})`"
                    :formatter="stateFormat"
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="account1"
                    :label="`${'消费余额'}(${getUser.currency.symbol})`"
                    :formatter="stateFormat"
                  >
                  </el-table-column>
                  <el-table-column align="center" prop="balance" :label="'操作'">
                    <template slot-scope="scope">
                      <el-button type="text" size="small" style="color: #c73030"
                      > {{ '删除' }}</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
            <el-form-item :label="'钱包类型'">
              <el-checkbox-group v-model="theaccountType">
                <el-checkbox
                  @change="changeAccountType"
                  v-for="item in enumsAccountList"
                  :key="item.pkId"
                  :label="item.pkId"
                >{{ item.accountName }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
            <el-form-item :label="'交款方式'">
              <el-checkbox-group v-model="form.paymentMethod">
                <el-checkbox
                  @change="changePaymentType"
                  v-for="item in paymentTypeList"
                  :key="item.value"
                  :label="item.value"
                >{{ item.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
            <div class="tableBox">
              <el-form-item :label="'充值方式'">
                <el-radio-group v-model="form.rechargeMethod">
                  <el-radio
                    :label="item.value"
                    v-for="(item, index) in czWayList"
                    :key="index"
                  >{{ item.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <el-table
                :span-method="objectSpanMethod"
                :data="tableData"
                style="width: 100%"
                :header-cell-style="{ background: '#EEEEEE' }"
              >
                <el-table-column
                  align="center"
                  prop="accountTypeVal"
                  :label="'钱包类型'"
                >
                </el-table-column>

                <el-table-column
                  v-for="(item, index) in thejkList"
                  :key="index"
                  align="center"
                  :prop="`${item.paymentAmount + index}`"
                  :label="item.label + `变更余额(${getUser.currency.symbol})`"
                >
                  <template slot-scope="scope">
                    <el-input
                      clearable
                      v-model="scope.row[`paymentAmount${item.value}`]"
                    >
                    </el-input>
                  </template>
                </el-table-column>

                <template v-if="form.czlx == 1">
                  <el-table-column
                    align="center"
                    prop="balance"
                    :label="`${'当前余额'}(${getUser.currency.symbol})`"
                    :formatter="stateFormat"
                  >
                  </el-table-column>

                </template>


                <el-table-column align="center" prop="remarks" :label="'备注'">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remarks"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form>
        </div>
        <div class="footer">
          <div style="margin: 0 auto">
            <el-button type="primary" class="thebtn" @click="saveDate('form')"
                       v-has-buttons="['ChongzhiConfirm']"
            > {{ '确认' }}</el-button
            >
          </div>
        </div>
      </div>
      <el-dialog
        :title="upload.title"
        :close-on-click-modal="false"
        :visible.sync="upload.open"
        width="600px"
        append-to-body
      >
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-exceed="handleExceed"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
             {{'将文件拖到此处，或'}}
            <em>{{'点击上传'}}</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            <el-link type="info" style="font-size: 12px" @click="importTemplate"
              > {{ '下载模板' }}</el-link
            >
          </div>
          <div class="el-upload__tip" style="color: red" slot="tip">
            {{'提示：仅允许导入“xls”或“xlsx”格式文件！'}}
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">{{'确认'}}</el-button>
          <el-button @click="upload.open = false">{{'取消'}}</el-button>
        </div>
      </el-dialog>
    </div>
  </template>

  <script>
  import FileUpload from "@/components/FileUpload";
  import topBar from "@/components/topBarRole";
  import { getToken } from "@/utils/auth";
  import { mapGetters } from "vuex";
  import {
    getRechargeOperationType,
    getenumsAccount,
    getpaymentType,
    getrechargeMethod,
    changeAccountType,
    saveShowPetition,
    getMemberName,
    changePlAccountType,
  } from "@/api/financial";
  import { stateFormat } from "@/utils/numberToCurrency";
  import {getRouters} from "@/api/settle";
  export default {
    name: "Chongzhi",
    components: {
      topBar,
      FileUpload,
    },

    computed: {
      ...mapGetters(["getUser"]),


    },
    data() {
      return {
        moren: "chongzhi",
        topList: [
          {
            name: '充值',
            path: "chongzhi",
            url: "Chongzhi",
            changed: false,
          },
          {
            name: '冻结',
            path: "dongjie",
            url: "Dongjie",
            changed: false,
          },
        ],
        tableData: [],
        form: {
          memberCode: 'CN30720201', //会员编号
          memberName: null, //会员姓名
          rechargeMethod: "", //充值方式
          memberRechargeAccountParams: [],
          paymentMethod: [], //交款方式
        },
        theaccountType: [],
        cztypeList: [], //操作类型下拉选
        enumsAccountList: [], //币种类型
        paymentTypeList: [], //交款方式
        czWayList: [], //充值方式
        thejkList: [{ value: "", label: "", paymentAmount: "" }], //缴款方式表头
        upload: {
          // 是否显示弹出层（物流导入）
          open: false,
          // 弹出层标题（物流导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的物流数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url:
            process.env.VUE_APP_BASE_API +
            "/member/manager/recharge/import-member-code",
        },
        changeMemberTable: [],
      };
    },
    created() {
      //操作类型
      this.getRechargeOperationType();
      //币种类型
      this.getenumsAccount();
      //交款方式
      this.getpaymentType();
      //充值方式
      this.getrechargeMethod();

      this.getUserRoute()
    },
    methods: {
      stateFormat,
      //下载模板
      importTemplate() {
        this.download(
          "/member/manager/recharge/download-template",
          {},
          `${'模板'}${new Date().getTime()}.xlsx`
        );
      },
      getUserRoute() {
        getRouters().then((res)=>{
          res.data.forEach((item)=>{
            this.topList.forEach((items)=>{
              if (item.routeName == items.url){
                items.changed = true
              }
            })
          })
        })
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = '翻译导入';
        this.upload.open = true;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        var fileName = response.fileName;
        if (fileName != undefined && fileName != "") {
        }
        if (response.code == 200) {
          this.changeMemberTable = response.data;
        }

        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true });
        // this.getList();
      },
      // 上传文件数量超出后的动作
      handleExceed() {
        this.upload.isUploading = false;
        this.msgInfo('仅可上传一个文件哦');
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      //根据会员编号查询会员姓名
      checkName() {
        getMemberName({ memberCode: this.form.memberCode }).then((res) => {
          this.form.memberName = res.memberName;
        });
      },
      //充值
      saveDate(formName) {
        if (!this.form.rechargeMethod) {
          this.$message({
            message: '请先选择充值方式',
            type: "warning",
          });
          return;
        } else {
          var dataList = [];
          this.tableData.forEach((item) => {
            var dataTmp = {};
            var a = this.form.paymentMethod;
            a.forEach((tmp) => {
              dataTmp[tmp] = item["paymentAmount" + tmp];
            });

            var dataItem = {
              rechargeDetailMap: dataTmp,
              accountType: item.pkAccount,
              balance: item.balance,
              remarks: item.remarks,
            };
            dataList.push(dataItem);
            this.form.memberRechargeAccountParams = dataList;
          });

          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.form.czlx == 1) {
                this.form.memberCode = this.form.memberCode.split();
                this.form.memberName = this.form.memberName.split();
              } else if (this.form.czlx == 2) {
                this.form.memberCode = [];
                this.form.memberName = [];
                this.changeMemberTable.forEach((ele) => {
                  this.form.memberCode.push(ele.memberCode);
                  this.form.memberName.push(ele.memberName);
                });
              }
              saveShowPetition(this.form).then((res) => {
                if (res.code == 200) {
                  this.$router.push({
                    path: "/information/business/czzxqc",
                    query: {
                      data: JSON.stringify(res.data),
                      rechargeData: JSON.stringify(this.form),
                      czlx: this.form.czlx,
                    },
                  });
                }
              });
            }
          });
        }
      },
      //合并列方法
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {

      },
      //点击钱包类型 刷新table
      changeAccountType() {
        if (!this.form.czlx) {
          this.$message({
            message: '请先选择操作类型',
            type: "warning",
          });
          this.theaccountType = [];
          return;
        }
        if (this.form.czlx == 1) {
          changeAccountType({
            memberCode: this.form.memberCode,
            accountTypes: this.theaccountType,
          }).then((res) => {
            this.tableData = res.data;
          });
        } else if (this.form.czlx == 2) {
          changePlAccountType({
            accountTypes: this.theaccountType,
          }).then((res) => {
            this.tableData = res.data;
          });
        }
      },
      //点击交款方式
      changePaymentType() {
        const jk = [];
        if (this.form.paymentMethod.length > 0) {
          this.form.paymentMethod.forEach((element) => {
            this.paymentTypeList.forEach((item) => {
              if (element == item.value) {
                jk.push({ value: element, label: item.label, paymentAmount: "" });
                this.thejkList = jk;
                console.log("🌈", this.form.paymentMethod);
              }
            });
          });
          //  this.form.a = this.form.paymentMethod
        } else {
          this.thejkList = [];
        }
      },
      getrechargeMethod() {
        getrechargeMethod().then((res) => {
          this.czWayList = res.data;
        });
      },
      getRechargeOperationType() {
        getRechargeOperationType().then((res) => {
          this.cztypeList = res.data;
        });
      },
      getpaymentType() {
        getpaymentType().then((res) => {
          this.paymentTypeList = res.data;
        });
      },
      getenumsAccount() {
        getenumsAccount().then((res) => {
          this.enumsAccountList = res.rows;
        });
      },
    },
  };
  </script>

  <style lang="scss" scoped>
  ::v-deep .el-table thead {
    color: #000000;
  }
  ::v-deep .el-table .warning-row {
    background: #f9f9f9;
  }

  .page {
    padding: 20px;
    background: #f9f9f9;
    font-size: 14px;
    .mainbtn {
      margin-bottom: 20px;
      .thebtn1 {
        background: rgba(255, 103, 35, 1);
        color: #ffffff;
      }
      .thebtn2 {
        background: rgba(0, 155, 88, 1);
        color: #ffffff;
      }
    }
    .main {
      padding: 10px 0;
      background: #ffffff;
      border-radius: 8px;
      box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);
      .tableBox {
        border-radius: 8px;
        border: 1px solid rgba(204, 204, 204, 1);
        padding: 20px 0;
      }
    }
    .footer {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 15px 0;
      .thebtn {
        width: 120px;
        height: 38px;
      }
    }
  }
  </style>
