<template>
  <el-dialog
    :title="isApprove ? 'APPROVE CREDIT' : 'AMEND CREDIT'"
    :visible="visible"
    custom-class="toptop-dialog"
    :before-close="hideDialog"
    :close-on-click-modal="false">
    <el-form
      ref="creditForm"
      :model="form"
      :rules="rules"
      label-width="130px"
      label-position="right"
      v-loading="loading">
      <el-form-item
        label="User-Email:"
        v-if="isApprove">
        <el-input
          class="input-text"
          :value="form.userEmail"
          readonly/>
      </el-form-item>
      <el-form-item
        label="Select User:"
        prop="userPk"
        v-else>
        <el-select
          v-model="userInfo.index"
          class="input-text"
          filterable
          remote
          clearable
          :remote-method="getUserOptions"
          placeholder="Search user email"
          @change="changeUser">
          <el-option
            v-for="(item,index) in options.user"
            :key="index"
            :label="item.email"
            :value="index"/>
        </el-select>
      </el-form-item>
      <el-form-item
        label="Current Balance:">
        <el-input
          class="input-text"
          :value="userInfo.currentBalance"
          readonly/>
      </el-form-item>
      <el-form-item
        label="Credit Action:"
        v-if="isApprove">
        <el-input
          class="input-text"
          v-model="form.creditActionType"
          readonly/>
      </el-form-item>
      <el-form-item
        label="Credit Action:"
        prop="creditActionType"
        v-else>
        <el-select
          v-model="form.creditActionType"
          class="input-text"
          clearable>
          <el-option
            v-for="(item,index) in options.action"
            :key="index"
            :label="item"
            :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item
        label="Amount:"
        v-if="isApprove">
        <el-input
          class="input-text"
          v-model="form.creditActionAmount"
          readonly/>
      </el-form-item>
      <el-form-item
        label="Amount:"
        prop="creditActionAmount"
        v-else>
        <el-input
          class="input-text"
          v-model="form.creditActionAmount"
          maxlength="6"/>
      </el-form-item>
      <el-form-item
        label="Remarks:"
        prop="creditActionRemarks">
        <el-input
          class="input-text"
          v-model="form.creditActionRemarks"
          type="textarea"
          maxlength="300"
          :readonly="isApprove"
          :autosize="autoSize"/>
      </el-form-item>
      <el-form-item
        label="Status:"
        v-if="isApprove">
        <el-input
          class="input-text"
          v-model="form.creditActionStatus"
          readonly/>
      </el-form-item>
      <el-form-item
        label="Requester:"
        v-if="isApprove">
        <el-input
          class="input-text"
          v-model="form.requester"
          readonly/>
      </el-form-item>
      <div
        class="flexcc"
        style="padding-top: 20px;"
        v-if="isApprove"
        v-show="form.creditActionStatus == 'Pending Approval'">
        <el-button
          class="cancel-button button-reject"
          @click="onApprove('Rejected')"
          :disabled="loadingBtn">
          REJECT
        </el-button>
        <el-button
          type="accent"
          @click="onApprove('Approved')"
          :disabled="loadingBtn">
          APPROVE
        </el-button>
      </div>
      <div
        class="flexcc"
        style="padding-top: 20px;"
        v-else>
        <el-button
          class="cancel-button"
          @click="hideDialog">
          CANCEL
        </el-button>
        <el-button
          type="primary"
          @click="onSubmit"
          :loading="loadingBtn">
          SUBMIT
        </el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import financial from '@/http/api/financial';
export default {
  name: "CreditActionDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    request: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      loading: false,
      loadingBtn: false,
      isApprove: false,
      form: {
        userPk: "",
        creditActionId: "",
        creditActionType: "",
        creditActionAmount: "",
        creditActionRemarks: ""
      },
      rules: {
        userPk: {
          required: true,
          trigger: 'change',
          message: 'Please select user'
        },
        creditActionAmount: [{
          required: true,
          trigger: 'blur',
          message: 'Please type amount',
        }, {
          pattern: /^[1-9]+\d*\.?\d*$/,
          trigger: 'blur',
          message: 'Please type a correct number'
        }],
        creditActionType: {
          required: true,
          trigger: 'change',
          message: 'Please select credit action'
        },
        creditActionRemarks: {
          required: true,
          trigger: 'blur',
          message: 'Please type remarks'
        }
      },
      options: {
        user: [],
        action: []
      },
      approve: {
        creditActionId: "",
        creditActionStatus: ""
      },
      userInfo: {
        index: "",
        currentBalance: ""
      },
      autoSize: {
        minRows: 3,
        maxRows: 8
      }
    };
  },
  watch: {
    visible: {
      handler(n, o) {
        if (n) {
          this.userInfo = {};
          if (this.request) {
            this.isApprove = true;
            this.approve.creditActionId = this.request;
            this.getActionInfo();
          } else {
            this.isApprove = false;
            this.form = {
              userPk: "",
              creditActionId: "",
              creditActionType: "",
              creditActionAmount: "",
              creditActionRemarks: ""
            }
          }
          this.$nextTick(() => {
            this.$refs.creditForm.clearValidate();
          })
        }
      }
    }
  },
  mounted() {
    this.getUserOptions();
    this.getActionOptions();
  },
  methods: {
    hideDialog(e, h) {
      this.$emit("hide", h);
    },
    getUserOptions(word) {
      financial.getUserOptions({
        email: word
      }).then(res => {
        if (res.data) {
          this.options.user = res.data
        } else {
          this.options.user = []
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.options.user = []
      })
    },
    getActionOptions() {
      financial.getCreditTypeOptions().then(res => {
        if (res.data) {
          this.options.action = res.data
        } else {
          this.options.action = []
        }
      }).catch(err => {
        this.$message({
          message: error,
          type: 'error'
        })
        this.options.action = []
      })
    },
    getActionInfo() {
      this.loading = true;
      financial.viewCreditApply(this.approve.creditActionId).then(res => {
        if (res.data) {
          this.form = res.data;
          this.userInfo.currentBalance = res.data.currentBalance;
        }
        this.loading = false;
      }).catch(err => {
        this.$message({
          message: error,
          type: 'error'
        })
        this.loading = false;
      })
    },
    changeUser(index) {
      const user = this.options.user[index];
      this.form.userPk = user.userPk;
      this.userInfo.currentBalance = user.currentBalance;
    },
    onSubmit() {
      this.$refs.creditForm.validate((valid) => {
        if (valid) {
          this.createAction();
        }
      })
    },
    onApprove(status) {
      this.$confirm("Confirm operation?", status, {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        this.approve.creditActionStatus = status;
        this.$nextTick(() => {
          this.approveAction();
        })
      })
    },
    createAction() {
      this.loadingBtn = true;
      financial.createCreditApply(this.form).then(res => {
        this.loadingBtn = false;
        this.$message({
          message: res.msg,
          type: 'success',
        })
        this.hideDialog(true, true);
      }).catch(err => {
        this.loadingBtn = false;
        this.$message({
          message: err,
          type: 'error',
        })
      })
    },
    approveAction() {
      this.loadingBtn = true;
      financial.approveCreditApply(this.approve).then(res => {
        this.loadingBtn = false;
        this.$message({
          message: res.msg,
          type: 'success',
        })
        this.hideDialog(true, true);
      }).catch(err => {
        this.loadingBtn = false;
        this.$message({
          message: err,
          type: 'error',
        })
      })
    }
  }
}
</script>

<style scoped>
>>> .toptop-dialog {
  width: 100%;
  padding: 0 10px;
  max-width: 520px;
}
.input-text {
  width: 100%;
  max-width: 350px;
}
.input-text >>> .el-textarea__inner {
  font-family: sans-serif;
}
.cancel-button.button-reject {
  border-color: #ED3F3F;
}
.cancel-button.button-reject >>> span {
  color: #ED3F3F;
}

</style>