<template>
  <div class="app-container">
    <el-button type="success" @click="handleSelectMember"> {{ $t("添加会员") }}</el-button>
    <div class="container exchangeBulkOperation">
      <div v-if="memberList.length > 0">
        <div class="formBox" v-for="(item, index) in queryParamsList" :key="item.memberId">
          <el-form :model="queryParamsList[index]" :ref="`queryForm${item.memberId}`" size="small" :inline="true" :rules="rules" label-width="168px">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <el-row :gutter="10">
                  <span class="card-title">{{ $t("基础信息") }}</span>
                  <el-button style="padding: 0 10px" @click="handleExpand(item)" type="text">{{ item.expand ? $t("收起") : $t("展开") }}<i :class="item.expand ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"></i></el-button>
                  <el-button type="text" @click="handleDelete(index, item)" class="del-btn">{{ $t("删除") }}</el-button>
                </el-row>
                <el-row :gutter="10">
                  <el-form-item :label="$t('会员名称')">
                    <el-input :placeholder="$t('请输入会员名称')" clearable :disabled="true" v-model="item.memberName" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                  </el-form-item>
                  <el-form-item :label="$t('当前积分')">
                    <el-input :placeholder="$t('请输入当前积分')" clearable :disabled="true" v-model="item.holdScore" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                  </el-form-item>
                  <el-form-item :label="$t('礼品选择')">
                    <el-input :placeholder="$t('请选择礼品')" clearable :disabled="true" v-model="item.rewardName" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                  </el-form-item>
                  <el-form-item :label="$t('礼品积分')">
                    <el-input :placeholder="$t('请输入礼品积分')" clearable :disabled="true" v-model="item.pointsRequire" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                  </el-form-item>
                  <el-form-item :label="$t('兑换数量')" prop="rewardCount">
                    <el-input
                      :placeholder="$t('请输入兑换数量')"
                      clearable
                      v-model.number="item.rewardCount"
                      @change="
                        (val) => {
                          handleRewardCount(item, index, val)
                        }
                      "
                      onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
                    />
                  </el-form-item>
                  <el-form-item :label="$t('本次兑换积分')">
                    <el-input :placeholder="$t('请输入本次兑换积分')" clearable :disabled="true" v-model="item.spendCredit" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                  </el-form-item>
                  <el-form-item :label="$t('兑换后剩余积分')">
                    <el-input :placeholder="$t('兑换后剩余积分')" clearable :disabled="true" v-model="item.remainingPoints" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                  </el-form-item>
                </el-row>
                <el-row :gutter="10" v-show="item.expand">
                  <el-row>
                    <span class="card-title">{{ $t("详细信息") }}</span>
                  </el-row>
                  <el-row>
                    <el-form-item :label="$t('兑换方式')" prop="redeemType">
                      <dict-selector clearable :type="DICT_TYPE.WAY_OF_RECEIVING" :filter="(e) => filterDicRedeemTypeList(e)" v-model="item.redeemType" @change="handleRedeemType(item)"> </dict-selector>
                    </el-form-item>
                    <el-form-item :label="$t('兑换入口')">
                      <dict-selector clearable :disabled="true" v-model="item.entrance" :type="DICT_TYPE.PLATFORM_TYPE"> </dict-selector>
                    </el-form-item>
                    <el-form-item class="expenses" :label="$t('费用')">
                      <el-row>
                        <el-col :span="12">
                          <el-form-item prop="expenses" :rules="rules.expenses" v-show="item.currency">
                            <el-input v-model="item.expenses" :placeholder="$t('请输入数字')" clearable onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                          </el-form-item>
                          <el-form-item v-show="!item.currency">
                            <el-input v-model="item.expenses" :placeholder="$t('请输入数字')" clearable onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <div>
                            <el-form-item prop="currency" :rules="rules.currency" v-show="item.expenses">
                              <el-select clearable v-model="item.currency" :placeholder="$t('请选择币种')">
                                <el-option v-for="nodeItem in currencyList" :key="nodeItem.id" :label="isChinese ? nodeItem.titleZh : nodeItem.titleEn" :value="nodeItem.id" />
                              </el-select>
                            </el-form-item>
                            <el-form-item v-show="!item.expenses">
                              <el-select clearable v-model="item.currency" :placeholder="$t('请选择币种')">
                                <el-option v-for="nodeItem in currencyList" :key="nodeItem.id" :label="isChinese ? nodeItem.titleZh : nodeItem.titleEn" :value="nodeItem.id" />
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                      </el-row>
                    </el-form-item>
                    <el-form-item :label="$t('收件人姓名')"><el-input :placeholder="$t('请输入收件人姓名')" clearable v-model="item.recipientName" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" /> </el-form-item>
                    <el-form-item :label="$t('收件人电话')">
                      <el-input :placeholder="$t('请输入收件人电话')" clearable v-model="item.recipientPhoneNum" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                    </el-form-item>
                    <el-form-item :label="$t('收件人地址')" v-if="item.redeemType != '1'">
                      <el-input :placeholder="$t('请输入收件人地址')" clearable v-model="item.recipientAddress" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                    </el-form-item>
                    <el-form-item :label="$t('兑换人')">
                      <el-input :placeholder="$t('请输入兑换人')" clearable v-model="item.redeemer" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                    </el-form-item>
                    <el-form-item :label="$t('兑换时间')">
                      <el-date-picker type="datetime" placement="bottom-start" value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('选择兑换时间')" v-model="item.redemptionTime"></el-date-picker>
                    </el-form-item>
                    <el-form-item :label="$t('快递公司')" v-if="item.redeemType != '1'">
                      <el-select v-model="item.courierCompany" :placeholder="$t('请选择快递公司')">
                        <el-option v-for="nodeItem in expressList" :key="nodeItem.id" :label="nodeItem.companyName" :value="nodeItem.id" />
                      </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('快递单号')" v-if="item.redeemType != '1'">
                      <el-input :placeholder="$t('请输入快递单号')" clearable v-model="item.expressNo" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                    </el-form-item>
                    <el-form-item :label="$t('快递日期')" v-if="item.redeemType != '1'">
                      <el-date-picker type="date" :placeholder="$t('选择快递日期')" v-model="item.expressDate" value-format="yyyy-MM-dd HH:mm:ss" placement="bottom-start"></el-date-picker>
                    </el-form-item>
                    <el-form-item :label="$t('快递寄出人')">
                      <el-input :placeholder="$t('请输入快递寄出人')" clearable v-model="item.expressSender" onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')" />
                    </el-form-item>
                    <el-form-item :label="$t('上传附件')">
                      <file-upload v-model="item.annex"></file-upload>
                    </el-form-item>
                    <el-form-item :label="$t('备注')">
                      <el-input style="width: 500px" type="textarea" v-model="item.remark"></el-input>
                    </el-form-item>
                  </el-row>
                </el-row>
              </div>
            </el-card>
          </el-form>
        </div>
      </div>
      <div v-else class="emptyText">
        {{ $t("请先添加准备兑换礼品的会员") }}
      </div>
      <el-row justify="end" :gutter="20" type="flex" class="handleButton">
        <el-col :span="2">
          <el-button v-if="memberList.length > 0" type="primary" @click="handleBulkConversion">{{ $t("确认兑换") }}</el-button>
        </el-col>
        <el-col :span="2">
          <el-button @click="handleBack">{{ $t("返回") }}</el-button>
        </el-col>
      </el-row>
    </div>

    <choose-Member :dialogVisible.sync="dialogVisible" @transferSelectMemberInfo="onGetSelectMemberInfo" :memberSelectList="memberList"> </choose-Member>
  </div>
</template>
<script>
import { getRewardsDetails, bulkConversion } from "@/api/ecw/giftManagement"
import FileUpload from "@/components/FileUpload"
import chooseMember from "./components/chooseMember.vue"
import { getExpressPage } from "@/api/ecw/express"
import { getCurrencyList } from "@/api/ecw/currency"
import { getNowDateTime } from "@/utils/ruoyi"
import { handleError } from "@vue/runtime-dom"

export default {
  name: "giftManagementList",
  components: {
    chooseMember,
    FileUpload
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (!this.quantityComputation) {
        return callback(new Error(this.$t("兑换积分大于当前总积分，请重新输入兑换数量")))
      } else {
        return callback()
      }
    }
    return {
      env: process.env.NODE_ENV,
      // 是否显示弹出层
      dialogVisible: false,
      // 查询参数
      queryParamsList: [],
      // 网点
      nodeList: [],
      //快递公司列表
      expressList: [],
      memberList: [],
      currencyList: [],
      quantityComputation: null,
      checkFormResult: [],
      rules: {
        rewardCount: [
          {
            required: true,
            message: this.$t("请输入兑换数量"),
            trigger: "blur"
          },
          {
            validator: validatePass2,
            trigger: ["blur", "change"]
          }
        ],
        expenses: [
          {
            required: true,
            message: this.$t("请输入费用"),
            trigger: "blur"
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: this.$t("请输入整数或保留小数点后两位"),
            trigger: "blur"
          }
        ],
        currency: [
          {
            required: true,
            message: this.$t("请选择币种"),
            trigger: "change"
          }
        ],
        redeemType: [
          {
            required: true,
            message: this.$t("请选择兑换方式"),
            trigger: "change"
          }
        ],
        recipientName: [
          {
            required: true,
            message: this.$t("请输入收件人姓名"),
            trigger: "blur"
          }
        ],
        recipientPhoneNum: [
          {
            required: true,
            message: this.$t("请输入收件人电话"),
            trigger: "blur"
          }
        ],
        recipientAddress: [
          {
            required: true,
            message: this.$t("请输入收件人地址"),
            trigger: "blur"
          }
        ]
      }
    }
  },
  computed: {
    isChinese() {
      return this.$i18n.locale === "zh_CN"
    }
  },
  created() {
    this.getRewardsDetailsAPI()
    this.getExpressList()
    this.currencyListAPI()
  },
  activated() {},
  methods: {
    //兑换方式下拉列表默认关联礼品
    filterDicRedeemTypeList(e) {
      return this.rewardsDetails.pickMethod.split(",").some((val) => e.value == val)
    },
    handleRedeemType(item) {
      this.$nextTick(() => {
        this.$refs[`queryForm${item.memberId}`][0].clearValidate()
      })
    },
    handleRewardCount(item, index, value) {
      this.queryParamsList[index].spendCredit = this.queryParamsList[index].pointsRequire * value
      this.queryParamsList[index].remainingPoints = this.queryParamsList[index].holdScore - this.queryParamsList[index].spendCredit
      this.quantityComputation = this.queryParamsList[index].remainingPoints >= 0 ? true : false
    },

    handleDelete(index, item) {
      this.$modal
        .confirm(this.$t("是否确认删除此数据"))
        .then(() => {
          this.queryParamsList.splice(index, 1)

          this.memberList = this.memberList.filter((res) => res.id != item.memberId)

          this.$modal.msgSuccess(this.$t("删除成功"))
        })
        .catch(() => {})
    },
    handleExpand(item) {
      this.queryParamsList.forEach((element) => {
        if (element.memberId == item.memberId) {
          element.expand = !item.expand
        }
      })
    },
    currencyListAPI() {
      getCurrencyList().then((res) => {
        this.currencyList = res.data
      })
    },
    onGetSelectMemberInfo(data) {
      if (data.length > 0) {
        data.filter((item) => {
          let inculde = this.queryParamsList.some((itemQuery) => {
            return item.id == itemQuery.memberId
          })
          if (!inculde) {
            let queryParams = {
              expand: true,
              memberId: item.id,
              holdScore: item.holdScore,
              rewardId: this.rewardsDetails.id,
              pointsRequire: this.rewardsDetails.pointsRequire,
              rewardCount: 1,
              spendCredit: null, //本次兑换花费积分
              remainingPoints: null, //剩余积分
              redeemType: null,
              entrance: 1,
              expenses: null,
              currency: null,
              recipientName: null,
              recipientPhoneNum: null,
              recipientAddress: null,
              redeemer: this.$store.getters.name,
              redemptionTime: getNowDateTime(),
              courierCompany: null,
              expressNo: null,
              expressSender: this.$store.getters.name,
              expressDate: null,
              remark: null,
              annex: null
            }
            if (this.isChinese) {
              queryParams.memberName = item.memberNameZh
              queryParams.rewardName = this.rewardsDetails.titleZh
            } else {
              queryParams.memberName = item.memberNameEn
              queryParams.rewardName = this.rewardsDetails.titleEn
            }
            queryParams.spendCredit = queryParams.pointsRequire
            queryParams.remainingPoints = queryParams.holdScore - queryParams.spendCredit
            this.quantityComputation = queryParams.remainingPoints >= 0 ? true : false
            this.memberList.push(item)
            this.queryParamsList.push({ ...queryParams })
            this.$nextTick(() => {
              this.$refs[`queryForm${item.id}`][0].clearValidate()
              this.$refs[`queryForm${item.id}`][0].validateField("rewardCount")
            })
          }
        })
      }
    },
    handleSelectMember() {
      this.dialogVisible = true
    },
    getExpressList() {
      let params = {
        pageNo: 1,
        pageSize: 1000
      }
      getExpressPage(params).then((res) => {
        this.expressList = res.data.list
      })
    },
    getRewardsDetailsAPI() {
      let params = {
        id: this.$route.query.rewardsID
      }
      getRewardsDetails(params).then((res) => {
        this.rewardsDetails = res.data
      })
    },
    handleBack() {
      this.$store.dispatch("tagsView/delCurrentView")
    },
    checkForm(formName) {
      const result = new Promise((resolve, reject) => {
        this.$refs[formName][0].validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject()
          }
        })
      })
      this.checkFormResult.push(result)
    },
    handleBulkConversion() {
      this.queryParamsList.forEach((element) => {
        this.checkForm(`queryForm${element.memberId}`)
      })
      Promise.all(this.checkFormResult)
        .then((res) => {
          this.checkFormResult = []
          let params = this.queryParamsList.map((item) => {
            if (item.redeemType == "1") {
              let { recipientAddress, expressNo, expressDate, courierCompany, ...itemNew } = item
              return itemNew
            } else {
              return item
            }
          })
          bulkConversion(params).then((res) => {
            if (res.code == "0") {
              this.queryParamsList = []
              this.memberList = []
              this.$message.success(this.$t("兑换成功"))
            }
          })
        })
        .catch(() => {
          this.checkFormResult = []
          this.$message.error(this.$t("兑换失败,请填写必要的信息"))
        })
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .exchangeBulkOperation {
  .formBox {
    .el-date-editor.el-input,
    .el-input,
    .upload-file {
      width: 286px;
    }
  }

  .expenses {
    .el-form-item {
      margin-right: 0;
    }
    .el-row {
      width: 286px;
    }
    .el-input {
      width: 140px;
    }
    .el-form-item--small.el-form-item {
      margin-bottom: 0;
    }
  }
}
.card-title {
  padding-right: 10px;
  border-right: 4px solid rgb(64, 158, 255);
  font-size: 16px;
  font-weight: 600;
}
.del-btn {
  color: red;
}
.app-container .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 194px;
}
.container {
  padding: 20px 0;
}
.emptyText {
  font-size: 20px;
  padding: 20px;
  line-height: 200px;
  text-align: center;
  color: #97a8be;
}
.handleButton {
  padding-right: 160px;
  margin-top: 50px;
  button {
    width: 100%;
  }
}
</style>
