<template>
  <div class="page2">
    <div>
      <div class="main">
        <el-form ref="form" :model="form" label-width="100px">
          <template>
            <div class="mainbtn">
              <el-button size="small" class="thebtn1" @click="handleImport">
                {{ '导入' }}</el-button>
              <el-button size="small" class="thebtn2" @click="importTemplate">
                {{ '下载模板' }}</el-button>
            </div>
          </template>

          <div class="tableBox">
            <el-row>
              <el-col :span="5">
                <el-form-item :label="'会员编号'">
                  <el-input
                    v-model="form.memberCode"
                    clearable
                    style="width: 200px"
                    @blur="checkName"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item :label="'会员姓名'">
                  <el-input
                    v-model="form.memberName"
                    clearable
                    style="width: 200px"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-button
                  class="my_search"
                  style="margin-left: 30px"
                  @click="getList"
                >
                  {{ '搜索' }}</el-button>
                <el-button class="my_reset" @click="reset">
                  {{ '重置' }}</el-button>
              </el-col>
            </el-row>
            <el-form-item :label="'充值方式'">
              <el-radio-group v-model="rechargeMethod">
                <el-radio
                  v-for="(item, index) in czWayList"
                  :key="index"
                  :label="item.value"
                >{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-table
              :data="tableData"
              class="thetables"
              height="530px"
              style="width: 100%"
              :header-cell-style="{ background: '#EEEEEE' }"
            >
              <el-table-column
                align="center"
                prop="memberCode"
                :label="'会员编号'"
                min-width="120px"
              />
              <el-table-column
                align="center"
                prop="memberName"
                :label="'会员姓名'"
                min-width="120px"
              />
              <el-table-column
                align="center"
                prop="paymentMethod"
                :label="'交款方式'"
                min-width="120px"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.paymentMethod"
                    clearable
                    :placeholder="'请选择'"
                  >
                    <el-option
                      v-for="item in paymentTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(item, index) in enumsAccountList"
                :key="index"
                min-width="200px"
                align="center"
                :prop="`${item.pkId}`"
                :label="
                  item.pkTransactionKeyVal +
                    `${'变更'}(${getUser.currency.symbol})`
                "
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.rechargeDetailMap[`${item.pkId}`]"
                    clearable
                    :min="0"
                    :controls="false"
                  />
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="memberRemarks"
                :label="'备注(前台)'"
                min-width="120px"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.memberRemarks" />
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                min-width="120px"
                prop="remarks"
                :label="'备注(后台)'"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remarks" />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
      <div class="footer">
        <div style="margin: 0 auto">
          <el-button
            v-has-buttons="['ChongzhiConfirm']"
            type="primary"
            class="thebtn"
            @click="saveDate('form')"
          >
            {{ '确认' }}</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" />
        <div class="el-upload__text">
          {{ '将文件拖到此处，或' }}
          <em>{{ '点击上传' }}</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          <el-link type="info" style="font-size: 12px" @click="importTemplate">
            {{ '下载模板' }}</el-link>
        </div>
        <div slot="tip" class="el-upload__tip" style="color: red">
          {{ '提示：仅允许导入“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 { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import {
  getenumsCzAccount,
  getpaymentType,
  getrechargeMethod,
  changeAccountType,
  getMemberName
} from '@/api/financial'
import { stateFormat } from '@/utils/numberToCurrency'
export default {
  name: 'Chongzhi',
  components: {
    FileUpload
  },

  computed: {
    ...mapGetters(['getUser'])
  },
  data() {
    return {
      tableData: [],
      form: {
        memberCode: '', // 会员编号
        memberName: null, // 会员姓名
        rechargeDetailMap: {},
        paymentMethod: [] // 交款方式
      },
      rechargeMethod: 1, // 充值方式
      enumsAccountList: [], // 币种类型
      paymentTypeList: [], // 交款方式
      czWayList: [], // 充值方式
      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'
      }
    }
  },
  created() {
    // 币种类型
    this.getenumsCzAccount()
    // 交款方式
    this.getpaymentType()
    // 充值方式
    this.getrechargeMethod()
  },
  methods: {
    stateFormat,
    // 下载模板
    importTemplate() {
      this.download(
        '/member/manager/recharge/download-template',
        {},
        `${'模板'}${new Date().getTime()}.xlsx`
      )
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '导入'
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.tableData = []
      if (response.code === 200 && response.data) {
        const rechargeDetailMap = {}
        this.enumsAccountList.forEach((item) => {
          rechargeDetailMap[item.pkId] = ''
        })
        response.data.forEach((item) => {
          if (item.rechargeDetail) {
            item.rechargeDetailMap = { ...JSON.parse(item.rechargeDetail) }
            this.tableData.push(item)
          } else {
            item.rechargeDetailMap = { ...rechargeDetailMap }
            this.tableData.push(item)
          }
        })
        this.$message({
          message: response.msg,
          type: 'success'
        })
      } else {
        const dataList = response.data.split(',') // 将数据按照逗号分隔为数组
        const formattedData = dataList
          .reduce((acc, item, index) => {
            const lineIndex = Math.floor(index / 3) // 计算当前行索引
            acc[lineIndex] = acc[lineIndex] || [] // 初始化该行
            acc[lineIndex].push(item) // 将当前元素加入对应的行
            return acc
          }, [])
          .map((line) => line.join(','))
          .join('<br>') // 将每行的内容拼接成字符串，并用 <br> 换行

        const msgList = response.msg + '<br>' + formattedData
        this.$alert(msgList, this.$t('提示'), {
          dangerouslyUseHTMLString: true
        })
      }
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
    },

    getList() {
      changeAccountType({
        memberCode: this.form.memberCode,
        memberName: this.form.memberName
      }).then((res) => {
        res.data.forEach((ele) => {
          ele.rechargeDetailMap = {}
        })
        this.tableData = res.data
      })
    },
    // 上传文件数量超出后的动作
    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
      })
    },
    reset() {
      this.form.memberCode = ''
      this.form.memberName = ''
      this.getList()
    },
    // 充值
    saveDate(formName) {
      if (!this.rechargeMethod) {
        this.$message({
          message: '请先选择充值方式',
          type: 'warning'
        })
        return
      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let shouldTerminate = false
            this.tableData.forEach((ele) => {
              if (!ele.paymentMethod) {
                shouldTerminate = true
                this.$message({
                  message: '交款方式不能为空',
                  type: 'warning'
                })
                return
              }
            })

            if (!shouldTerminate) {
              this.$router.push({
                path: '/information/business/czzxqc',
                query: {
                  data: '',
                  czlx: 2,
                  detailParams: JSON.stringify(this.tableData),
                  rechargeMethod: this.rechargeMethod
                }
              })
            }
          }
        })
      }
    },

    getrechargeMethod() {
      getrechargeMethod().then((res) => {
        this.czWayList = res.data
      })
    },

    getpaymentType() {
      getpaymentType().then((res) => {
        this.paymentTypeList = res.data
      })
    },
    getenumsCzAccount() {
      getenumsCzAccount({ accountProperty: 1 }).then((res) => {
        this.enumsAccountList = res.rows
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__body-wrapper {
  height: 480px !important;
}
.thetables ::v-deep .el-select .el-input .el-select__caret {
  margin-top: 10px;
}
.thetables ::v-deep .el-input__suffix {
  margin-top: -4px;
}

::v-deep .el-table thead {
  color: #000000;
}
::v-deep .el-table .warning-row {
  background: #f9f9f9;
}
.page2 {
  // 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>
