<template>
  <div class="app-container">
    <!-- 添加或修改积分管理对话框 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col span=8>
          <el-form-item>
            <el-radio-group v-model="radio" @change="changeRadio">
              <el-radio label="1">充值</el-radio>
              <el-radio label="2">退款</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span=8>
          <el-form-item label="变动类型" prop="moneyType">
            <el-select v-model="form.moneyType" placeholder="请选择变动类型" @change="changeType">
              <el-option
                v-for="item in selectArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span=8>
          <el-form-item label="手机号" prop="phonenumber">
            <el-input
              v-model="form.phonenumber"
              @change="queryNickName"
              placeholder="请输入内容"
              :trigger-on-focus="false"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span=8>
          <el-form-item label="用户名称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入用户名称" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span=8>
          <el-form-item label="卡片编号" prop="cardNumber">
            <el-input v-model="form.cardNumber" placeholder="请输入卡片编号"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ifErrorReturn">
        <el-col span=8>
          <el-form-item label="订单信息" prop="orderNumber">
            <el-select v-model="form.orderNumber" placeholder="请选择订单">
              <el-option
                v-for="item in orderList"
                :key="item.orderNumber"
                :label="item.orderNumber + '总金额:' + item.orderTotal"
                :value="item.orderNumber"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col span=8>
          <el-form-item label="变动积分" prop="rechargeIntegral">
            <el-input v-model="form.rechargeIntegral" placeholder="请输入充值积分"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form label-width="200px">
      <el-form-item>
        <el-button type="primary" @click="submitForm()">确定</el-button>
      </el-form-item>
    </el-form>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" 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"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelTemplate">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addIntegral,
  updateIntegral,
  importTemplate
} from "@/api/integral/integral";
import {queryUserInfoByPhonenumber} from "@/api/system/user";
import {getToken} from "@/utils/auth";
import user from "@/store/modules/user";
import {getIntegralType, getFinishOrder} from "@/api/integral/change";


export default {
  name: "Integral",
  dicts: ['change_type', 'yes_or_no'],
  data() {
    return {
      radio: '1',
      type: {},
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      userList: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pns/integral/importData"
      },
      // 表单参数
      form: {
        nickName: ''
      },
      // 表单校验
      rules: {
        nickName: [
          {required: true, message: "用户名不能为空", trigger: "blur"}
        ],
        moneyType: [
          {required: true, message: "金额类型不能为空", trigger: "blur"}
        ],
        loginName: [
          {required: true, message: "用户编码不能为空", trigger: "blur"}
        ],
        rechargeIntegral: [
          {required: true, message: "充值积分不能为空", trigger: "blur"}
        ],
        orderNumber: [
          {required: true, message: "订单编号不能为空", trigger: "blur"}
        ]
      },
      //充值字典
      rechargeArr: [],
      //退款字典
      returnArr: [],
      //显示字典
      selectArr: [],
      ifErrorReturn: false,
      orderList: []
    };
  },
  created() {
    this.form.organizationCode = user.state.organ;
    this.getIntegralType();
  },
  methods: {
    getIntegralType() {
      getIntegralType().then(response => {
        this.rechargeArr = response.data.recharge;
        this.returnArr = response.data.return;
        this.selectArr = this.rechargeArr;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        moneyType: null,
        rechargeEquipmentCode: null,
        rechargeEquipmentName: null,
        loginName: null,
        nickName: null,
        cardNumber: null,
        cardName: null,
        rechargeTime: null,
        orderNumber: null,
        rechargeIntegral: null,
        isDelete: null,
        rechargeId: null,
        updateTime: null,
        phonenumber: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.form.organizationCode = user.state.organ;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateIntegral(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.reset();
            });
          } else {
            addIntegral(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.reset();
            });
          }
        }
      });
    },
    queryNickName() {
      if (this.form.phonenumber) {
        queryUserInfoByPhonenumber({phonenumber: this.form.phonenumber}).then((response) => {
          if (response.code === 200) {
            this.userList = response.data;
            if (this.userList != undefined) {
              this.form.loginName = this.userList.userName;
              this.form.nickName = this.userList.nickName;
              this.getFinishOrder();
            } else {
              this.form.nickName = "";
              this.form.loginName = "";
            }
          }
        }).catch((e) => {
          this.form.nickName = "";
          this.form.loginName = "";
        });
      }
    },
    handleImport() {
      this.upload.title = "集体充值";
      this.upload.open = true;
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.cancel();
      this.getList();
    },
    importTemplate() {
      importTemplate().then(response => {
        this.$download.name(response.msg);
      });
    },
    submitFileForm() {
      this.$refs.upload.submit();
    },
    orgFormatter(val) {
      let name = '';
      user.state.organDicts.forEach(item => {
        if (item.deptCode === val) {
          name = item.deptName;
        }
      })
      return name;
    },
    changeType(v) {
      if (v === '1') {
        this.handleImport();
        this.ifErrorReturn = false;
      } else if (v === '5') {
        this.ifErrorReturn = true;
        this.getFinishOrder()
      } else {
        this.ifErrorReturn = false;
      }
      this.$forceUpdate()
    },
    cancelTemplate() {
      this.upload.open = false;
      this.form.moneyType = '2';
    },
    changeRadio(val) {
      if (val === "1") {
        this.selectArr = this.rechargeArr;
        this.form.moneyType = '';
        this.ifErrorReturn = false;
      } else {
        this.selectArr = this.returnArr;
        this.form.moneyType = '';
      }
    },
    getFinishOrder() {
      if (this.form.moneyType === 5 && this.form.nickName != null && this.form.nickName !== '') {
        getFinishOrder({userNumber: this.form.loginName, jgid: this.form.organizationCode}).then(response => {
          this.orderList = response.data;
        })
      }
    }

  }
};
</script>
