<template>
  <div class="app-container">
    <div class="container">
      <div class="formBox exchangeRecordOperation">
        <el-form
          v-for="(item, index) in queryParamsList"
          :key="item.memberId"
          :model="queryParamsList[index]"
          :ref="`queryForm${item.memberId}`"
          size="small"
          :inline="true"
          :rules="rules"
          :disabled="viewRecordDisable"
          label-width="168px"
        >
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <el-row :gutter="10">
                <span class="card-title">{{ $t("基础信息") }}</span>
              </el-row>
              <el-row :gutter="10">
                <el-form-item :label="$t('会员名称')">
                  <el-autocomplete
                    v-model="item.memberName"
                    :disabled="rewardEdit || veriftyDisable"
                    :fetch-suggestions="querySearchAsync"
                    :placeholder="$t('请输入会员名称')"
                    @select="handleSelectMemberQuery"
                  ></el-autocomplete>
                  <!-- <el-input
                    :placeholder=""
                    clearable
                    v-model="item.memberName"
                    onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
                  /> -->
                </el-form-item>
                <el-form-item id="colorRedInput" :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('礼品选择')"
                  prop="rewardName"
                  id="colorRedInput"
                >
                  <el-input
                    :placeholder="$t('请选择礼品')"
                    clearable
                    :disabled="true"
                    v-model="item.rewardName"
                    onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
                  />
                </el-form-item>
                <el-button
                  type="success"
                  size="small"
                  @click="handleSelectMember"
                >
                  {{ $t("选择") }}</el-button
                >
                <el-form-item :label="$t('礼品积分')" id="colorRedInput">
                  <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('请输入兑换数量')"
                    :disabled="rewardEdit || veriftyDisable"
                    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('本次兑换积分')" id="colorRedInput">
                  <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('兑换后剩余积分')" id="colorRedInput">
                  <el-input
                    :placeholder="$t('兑换后剩余积分')"
                    clearable
                    :disabled="true"
                    id="colorRedInput"
                    v-model="item.remainingPoints"
                    onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
                  />
                </el-form-item>
              </el-row>
              <el-row :gutter="10">
                <el-row>
                  <span class="card-title">{{ $t("详细信息") }}</span>
                </el-row>
                <el-row>
                  <el-form-item :label="$t('兑换方式')" prop="redeemType">
                    <dict-selector
                      clearable
                      :disabled="veriftyDisable"
                      :type="DICT_TYPE.WAY_OF_RECEIVING"
                      v-model="item.redeemType"
                    >
                    </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 :label="$t('费用')">
                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-form-item prop="expenses">
                          <el-input
                            v-model="item.expenses"
                            :disabled="veriftyDisable"
                            :placeholder="$t('请输入数字')"
                            clearable
                            onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
                          />
                        </el-form-item>
                      </el-col>
                      <el-col :span="10">
                        <el-form-item prop="currency">
                          <el-select
                            v-model="item.currency"
                            :disabled="veriftyDisable"
                            :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-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"
                      :disabled="veriftyDisable"
                      onkeyup="this.value=this.value.replace(/(^\s*)|(\s*$)/g,'')"
                    />
                  </el-form-item>
                  <el-form-item :label="$t('兑换时间')">
                    <el-date-picker
                      type="date"
                      placement="bottom-start"
                      :disabled="veriftyDisable"
                      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"
                      :disabled="veriftyDisable || viewRecordDisable"
                    ></file-upload>
                  </el-form-item>
                  <el-form-item :label="$t('备注')">
                    <el-input
                      style="width: 500px"
                      :disabled="veriftyDisable"
                      type="textarea"
                      v-model="item.remark"
                    ></el-input>
                  </el-form-item>
                  <div class="view" v-if="viewRecordDisable || veriftyDisable">
                    <el-form-item :label="$t('核销人')">
                      <el-input v-model="item.verifyUser"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('核销时间')">
                      <el-date-picker
                        type="date"
                        :placeholder="$t('选择核销时间')"
                        v-model="item.verifyTime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placement="bottom-start"
                      ></el-date-picker>
                    </el-form-item>
                    <el-form-item :label="$t('创建人')" v-if="!veriftyDisable">
                      <el-input v-model="item.creatorName"></el-input>
                    </el-form-item>
                    <el-form-item
                      :label="$t('创建时间')"
                      v-if="!veriftyDisable"
                    >
                      <el-date-picker
                        type="date"
                        :placeholder="$t('创建时间')"
                        v-model="item.createTime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placement="bottom-start"
                      ></el-date-picker>
                    </el-form-item>
                    <el-form-item
                      :label="$t('最后更新人')"
                      v-if="!veriftyDisable"
                    >
                      <el-input v-model="item.updater"></el-input>
                    </el-form-item>
                    <el-form-item
                      :label="$t('最后更新时间')"
                      v-if="!veriftyDisable"
                    >
                      <el-date-picker
                        type="date"
                        :placeholder="$t('最后更新时间')"
                        v-model="item.updateTime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placement="bottom-start"
                      ></el-date-picker>
                    </el-form-item>
                  </div>
                </el-row>
              </el-row>
            </div>
          </el-card>
        </el-form>
      </div>

      <el-row justify="end" :gutter="20" type="flex" class="handleButton">
        <el-col :span="3">
          <el-button
            type="primary"
            @click="handleBulkConversion"
            v-if="!viewRecordDisable"
            >{{ submitButtonText }}</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button @click="handleBack">{{ $t("返回") }}</el-button>
        </el-col>
      </el-row>
    </div>

    <choose-Gift
      :dialogVisible.sync="dialogVisible"
      @transferSelectRewards="onGetSelectRewardsInfo"
    >
    </choose-Gift>
  </div>
</template>
<script>
import { bulkConversion } from "@/api/ecw/giftManagement";
import FileUpload from "@/components/FileUpload";
import chooseGift from "./components/chooseGift.vue";
import { getExpressPage } from "@/api/ecw/express";
import { getCurrencyList } from "@/api/ecw/currency";
import { getNowDateTime, parseTime } from "@/utils/ruoyi";
import { getMemberList } from "@/api/ecw/giftManagement";
import {
  getRewardDetailQuery,
  updatedRewardsDetails,
  verifyRedeem,
} from "@/api/ecw/memberManagement";
import { memberUserGet } from "@/api/member/user";

export default {
  name: "exchangeRecordOperation",
  components: {
    chooseGift,
    FileUpload,
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (!this.quantityComputation) {
        return callback(
          new Error(this.$t("兑换积分大于当前总积分，请重新输入兑换数量"))
        );
      } else {
        return callback();
      }
    };
    var expensesCurrency = (rule, value, callback) => {
      if (this.queryParamsList[0].expenses && !value) {
        return callback(
          new Error(this.$t("请选择币种"))
        );
      } else {
        return callback();
      }
    };
    return {
      env: process.env.NODE_ENV,
      // 是否显示弹出层
      dialogVisible: false,

      // 查询参数
      queryParamsList: [
        {
          memberId: null,
          holdScore: null,
          rewardId: "",
          pointsRequire: "",
          rewardCount: null,
          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,
          memberName: null,
          rewardName: null,
        },
      ],
      // 网点
      nodeList: [],
      //快递公司列表
      expressList: [],
      currencyList: [],
      quantityComputation: null,
      checkFormResult: [],
      rewardEdit: false,
      submitButtonText: "确认兑换",
      viewRecordDisable: false,
      veriftyDisable: false,
      rules: {
        rewardCount: [
          {
            required: true,
            message: this.$t("请输入兑换数量"),
            trigger: "blur",
          },
          {
            validator: validatePass2,
            trigger: ["blur", "change"],
          },
        ],
        rewardName: [
          {
            required: true,
            message: this.$t("请选择礼品"),
            trigger: "blur",
          },
        ],
        expenses: [
          // {
          //   required: true,
          //   message: this.$t("请输入费用"),
          //   trigger: "blur",
          // },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: this.$t("请输入整数或保留小数点后两位"),
            trigger: "blur",
          },
        ],
        currency: [
          {
            // required: true,
            // message: this.$t("请选择币种"),
            validator:expensesCurrency,
            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.getExpressList();
    this.currencyListAPI();

    switch (this.$route.query.pageStatus) {
      case "edit":
        this.submitButtonText = this.$t("保存");
        this.getExchangeDetail();
        break;
      case "view":
        this.viewRecordDisable = true;
        this.getExchangeDetail();
        break;
      case "verify":
        this.veriftyDisable = true;
        this.submitButtonText = this.$t("确认核销");
        this.getExchangeDetail();
        break;
      case "add":
        this.submitButtonText = this.$t("确认兑换");
        this.getDetails();
        break;

      default:
        this.submitButtonText = this.$t("确认兑换");
        break;
    }
  },

  activated() {},
  methods: {
    getDetails() {
      memberUserGet({ id: this.$route.query.memberId }).then((r) => {
        console.log(r, "rrrr");
        // this.details = r.data;
        this.isChinese
          ? (this.queryParamsList[0].memberName = r.data.nickname)
          : (this.queryParamsList[0].memberName = r.data.englishName);
        this.queryParamsList[0].holdScore = r.data.userScoreLevelInfo.holdScore;
        this.queryParamsList[0].memberId = r.data.id;
      });
    },
    getExchangeDetail() {
      this.queryParamsList = [];
      this.$nextTick(() => {
        let params = {
          id: this.$route.query.exchangeRewardID,
        };
        getRewardDetailQuery(params).then((res) => {
          this.rewardEdit = true;
          const data = res.data;
          let params = this.queryParamsList[0];
          this.queryParamsList = [{ ...data, params }];

          if (this.isChinese) {
            this.queryParamsList[0].memberName = data.memberNameZh;
            this.queryParamsList[0].rewardName = data.rewardTitleZh;
          } else {
            this.queryParamsList[0].memberName = data.memberNameEn;
            this.queryParamsList[0].rewardName = data.rewardTitleEn;
          }
          this.queryParamsList[0].redemptionTime = parseTime(
            data.redemptionTime
          ); //兑换时间

          this.queryParamsList[0].verifyUser = this.$store.getters.name;

          this.queryParamsList[0].verifyTime = parseTime(data.verifyTime);
          this.queryParamsList[0].updateTime = parseTime(data.updateTime);
          this.queryParamsList[0].createTime = parseTime(data.createTime);
          this.queryParamsList[0].expressDate = parseTime(data.expressDate); //快递时间
          this.handleRewardCount(data, 0, data.rewardCount);
          if (this.$route.query.pageStatus == "verify") {
            this.queryParamsList[0].verifyTime = getNowDateTime();
          }
          this.$forceUpdate();
        });
      });
    },
    handleSelectMemberQuery(item) {
      this.isChinese
        ? (this.queryParamsList[0].memberName = item.memberNameZh)
        : (this.queryParamsList[0].memberName = item.englishName);
      this.queryParamsList[0].holdScore = item.holdScore;
      this.queryParamsList[0].memberId = item.id;

      this.queryParamsList[0].spendCredit =
        this.queryParamsList[0].pointsRequire *
        this.queryParamsList[0].rewardCount;

      this.queryParamsList[0].remainingPoints =
        this.queryParamsList[0].holdScore - this.queryParamsList[0].spendCredit;
      this.quantityComputation =
        this.queryParamsList[0].remainingPoints >= 0 ? true : false;
    },
    querySearchAsync(queryString, cb) {
      let result = [];
      if (queryString == "") {
        cb(result);
      } else {
        try {
          let params = {
            country: null,
            city: null,
            endTime: "",
            holdScore: null,
            holdScoreOperate: null,
            key: this.queryParamsList[0].memberName,
            pageNo: 1,
            pageSize: 20,
            startTime: "",
            usedScore: null,
            usedScoreOperate: null,
          };
          getMemberList(params).then((res) => {
            result = res.data.list.map((item) => {
              if (this.isChinese) {
                return {
                  ...item,
                  value: `${item.memberNameZh}(${item.mobile})`,
                };
              } else {
                return {
                  ...item,
                  value: `${item.memberNameEn}(${item.mobile})`,
                };
              }
            });
            cb(result);
          });
        } catch {
          this.$message.success(this.$t("获取数据失败"));
        }
      }
    },
    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;
    },

    currencyListAPI() {
      getCurrencyList().then((res) => {
        this.currencyList = res.data;
      });
    },
    onGetSelectRewardsInfo(item) {
      this.queryParamsList[0].rewardId = item.id;
      this.queryParamsList[0];
      if (this.isChinese) {
        this.queryParamsList[0].rewardName = item.titleZh;
      } else {
        this.queryParamsList[0].rewardName = item.titleEn;
      }
      this.queryParamsList[0].pointsRequire = item.pointsRequire;

      this.queryParamsList[0].rewardCount = "";
      this.queryParamsList[0].spendCredit = "";
      this.queryParamsList[0].remainingPoints =
        this.queryParamsList[0].holdScore;
      this.quantityComputation =
        this.queryParamsList[0].remainingPoints >= 0 ? true : false;
    },
    handleSelectMember() {
      this.dialogVisible = true;
    },
    getExpressList() {
      let params = {
        pageNo: 1,
        pageSize: 1000,
      };
      getExpressPage(params).then((res) => {
        this.expressList = res.data.list;
      });
    },
    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);
    },
    resetForm() {
      this.queryParamsList = [
        {
          memberId: null,
          holdScore: null,
          rewardId: "",
          pointsRequire: "",
          rewardCount: null,
          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,
          memberName: null,
          rewardName: null,
        },
      ];
    },
    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;
            }
          });
          if (this.$route.query.pageStatus == "edit") {
            updatedRewardsDetails(params[0]).then((res) => {
              this.$message.success(this.$t("更新成功"));
              this.$router.go(-1);
            });
            //编辑
          } else if (this.$route.query.pageStatus == "verify") {
            verifyRedeem(params[0]).then((res) => {
              this.$message.success(this.$t("核销成功"));
              this.$router.go(-1);
            });
          } else {
            //兑换
            bulkConversion(params).then((res) => {
              if (res.code == "0") {
                this.queryParamsList = this.resetForm();
                this.$message.success(this.$t("兑换成功"));
                this.$router.go(-1);
              }
            });
          }
        })
        .catch(() => {
          this.checkFormResult = [];
          this.$message.error(this.$t("请填写必要的信息"));
        });
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep #colorRedInput .el-input__inner {
  color: red;
  font-size: 14px;
}
::v-deep .exchangeRecordOperation{
   .el-input{
    width: 206px;
   }
}
.card-title {
  padding-right: 10px;
  border-right: 4px solid rgb(64, 158, 255);
  font-size: 16px;
  font-weight: 600;
}
.del-btn {
  color: red;
}
.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>
