<template>
  <div>
    <el-button type="primary" @click="apply()">立即申请</el-button>

    <!-- 申请应用弹窗 -->
    <el-dialog
      title="申请应用"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资源名称">
          {{ resForm.resName }}
        </el-form-item>
        <el-form-item label="资源描述">
          {{ resForm.remark }}
        </el-form-item>
        <el-form-item label="关联应用" prop="applicationId">
          <el-select v-model="form.applicationId">
            <el-option
              v-for="(app, i) in myAppList"
              :key="i"
              :label="app.appName"
              :value="app.id"
              :disabled="canSelect(app.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="返回格式" prop="format">
          <el-select v-model="form.format">
            <el-option label="XML" value="XML"></el-option>
            <el-option label="JSON" value="JSON"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="日访问量" prop="dayLimit">
          <el-input-number
            v-model="form.dayLimit"
            placeholder="每日最大访问量"
            :controls="false"
            :max="999999999"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="订阅资源"
          prop="isSubscribe"
          v-if="canSubstribe()"
        >
          <el-checkbox v-model="form.isSubscribe">订阅</el-checkbox>
        </el-form-item>
        <el-form-item
          label="回调地址"
          prop="subscribeUrl"
          v-if="form.isSubscribe"
        >
          <el-input
            v-model="form.subscribeUrl"
            placeholder="请输入回调地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="申请理由" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入申请理由"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { applyResource, myResources } from "@/api/customer/resource";
import { listMyApp } from "@/api/customer/application";
export default {
  name: "ApplyResourceComponents",
  computed: {
    ...mapGetters(["token"]),
  },
  props: {
    resForm: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      open: false,
      form: {},
      rules: {
        applicationId: {
          required: true,
          message: "请选择申请应用",
          trigger: "blur",
        },
        format: {
          required: true,
          message: "请选择返回格式",
          trigger: "blur",
        },
        // dayLimit: {
        //   required: true,
        //   message: "请填写日访问量",
        //   trigger: "blur",
        // },
        subscribeUrl: {
          required: true,
          message: "请填写回调地址",
          trigger: "blur",
        },
        remark: {
          required: true,
          message: "请填写申请理由",
          trigger: "blur",
        },
      },
      myAppList: [], // 我的应用列表
      appliedAppList: [], // 当前资源已经申请了的应用
    };
  },
  methods: {
    canSubstribe() {
      // console.log(this.resForm)
      if (!this.resForm || !this.resForm.data) {
        return false;
      }
      if (this.resForm.resType === "data") {
        return this.resForm.data.addField ? true : false;
      } else {
        return false;
      }
    },
    apply() {
      // 判断是否登录
      if (!this.token) {
        this.$confirm("申请资源需要登录，是否立即登录？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$router.push({
              path: "/login?redirect=" + encodeURIComponent(this.$route.path),
            });
          })
          .catch(() => {});
        return;
      }

      // 查询我的应用
      listMyApp({ status: "1" }).then((response) => {
        this.myAppList = response.data;
        if (!this.myAppList || this.myAppList.length === 0) {
          this.$confirm("当前用户还未配置应用，是否立即前往配置？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$router.push({
                path: "/customer/myapp",
              });
            })
            .catch(() => {});
          return;
        }

        // 查询当前资源当前用户申请情况
        myResources({
          resType: this.resForm.resType,
          resId: this.resForm.id,
        }).then((res) => {
          this.appliedAppList = res.data;
        });

        // 弹窗显示申请应用
        this.open = true;
      });
    },
    canSelect(applicationId) {
      console.log(this.appliedAppList);
      if (this.appliedAppList && this.appliedAppList.length > 0) {
        return this.appliedAppList.find(
          (p) => p.applicationId === applicationId && p.applyStatus !== "2"
        )
          ? true
          : false;
      }

      return false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        resourceType: null,
        resourceId: null,
        applicationId: null,
        remark: null,
        format: null,
        dayLimit: null,
        isSubscribe: null,
        subscribeUrl: null,
      };
      this.resetForm("form");
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(this.form);
          console.log(this.resForm);
          this.form.format = "JSON";
          const submitData = {
            resourceType: this.resForm.resType,
            resourceId: this.resForm.id,
            applicationId: this.form.applicationId,
            remark: this.form.remark,
            format: this.form.format,
            dayLimit: this.form.dayLimit,
            isSubscribe: this.form.isSubscribe ? "Y" : "N",
            subscribeUrl: this.form.subscribeUrl,
          };
          applyResource(submitData).then((response) => {
            this.$modal.msgSuccess("申请资源成功");
            this.cancel();
            this.$emit("callback", data);
          });
        }
      });
    },
  },
};
</script>