<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="10vh"
    width="750px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    append-to-body
    @close="showModelThis = false"
  >
    <el-card style="margin-top: -20px">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        status-icon
        :rules="rulesThis"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="按钮标识：" prop="action_code">
          <el-select
            style="width: 100%"
            v-model="ruleForm.action_code"
            placeholder="请选择按钮标识"
            clearable
            filterable
            :disabled="type === 'view'"
            @change="codeChange"
          >
            <el-option
              v-for="item in btnList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-radio v-model="ruleForm.status" :label="'1'" :disabled="type === 'view'">
            启用
          </el-radio>
          <el-radio v-model="ruleForm.status" :label="'0'" :disabled="type === 'view'">
            禁用
          </el-radio>
        </el-form-item>
      </el-form>

      <el-col :span="24" style="text-align: right; padding: 0 0 10px 0">
        <el-button v-if="type !== 'view'" type="primary" @click="submitForm">
          保 存
        </el-button>
        <el-button @click="showModelThis = false">{{
          type === "view" ? "关 闭" : "取 消"
        }}</el-button>
      </el-col>
    </el-card>
  </el-dialog>
</template>

<script>
import asyncRequest from "@/apis/service/system/setMenu";
import resToken from "@/mixins/resToken";
// import action from '@/apis/service/system/action';
export default {
  mixins: [resToken],
  props: ["showModel", "type", "formData"],
  data() {
    return {
      loading: false,
      showIconModel: false,
      title: "",
      btnList:[],
      showModelThis: this.showModel,
      ruleForm: {},
      rulesThis: this.rules,
      rules: {
        action_code: [{ required: true, message: "请选择按钮", trigger: "change",}],
        status: [{ required: true, message: "请选择状态", trigger: "blur" },]
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  mounted(){
    this.requsetButtonList()
  },
  methods: {
    codeChange(code) {
      for (let i = 0; i < this.btnList.length; i++) {
        if (this.btnList[i].code === code) {
          this.ruleForm.action_name = this.btnList[i].name;
          break;
        }
      }
    },
    setVal(val) {
      this.ruleForm.status = val;
      this.$refs.ruleForm.validateField("status");
    },
    async requsetButtonList(){
      const { data, code } = await asyncRequest.actionQuery({})
      console.log(data)
      if(Number(code) === 1){
        this.btnList = data.map(item => ({
          name:item.action_name,
          code:item.action_code
        }))
      }
    },
    async initForm() {
      this.loading = false;
      // console.log(this.showModel, this.type, this.formData);
      switch (this.type) {
        case "view":
          this.title = "按钮详情";
          this.rulesThis = {};
          await this.initData();
          break;
        case "edit":
          this.title = "修改按钮";
          this.rulesThis = this.rules;
          await this.initData();
          break;

        default:
          this.title = "添加按钮";
          this.rulesThis = this.rules;
          await this.initData();
          break;
      }
    },
    async initData() {
      this.loading = true;
      const { id, status, menuid, action_code, action_name } = this.formData;
      console.log(this.formData);
      this.ruleForm = {
        id: String(id ?? ""), // 父级ID（一级为0）
        menuid: String(menuid ?? ""), // 所有父级编号（用逗号分隔）
        action_code: String(action_code ?? ""), // 编码（用于按钮是否显示）
        action_name: String(action_name ?? ""), // 编码（用于按钮是否显示）
        status: String(status ?? ""), // 图标（导航图标）
      };
      this.loading = false;
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate();
        }
      });
    },
    async submitForm() {
      if (this.loading) {
        return false;
      }
      this.loading = true;

      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const model = JSON.parse(JSON.stringify(this.ruleForm))
          model.menu_id = model.menuid
          delete model['menuid']
          let res = {};
          if (this.type == "add") {
            console.log(model)
            res = await asyncRequest.actionadd(model);
          } else {
            res = await asyncRequest.actionedit(model);
          }
          this.loading = false;
          const { code: mcode, message } = res;
          if (mcode === 1) {
            this.ruleForm = {};
            const title = this.type == "add" ? "添加成功" : "修改成功";
            this.$notify.success({
              title,
              message: "",
            });
            this.showModelThis = false;
            this.$emit("refresh");
          }
        } else {
          this.loading = false;
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.g-block {
  display: inline-block;
  padding: 10px 5px;
  text-align: center;
  border: 1px #ccc dashed;
  margin: 1px;
  font-size: 0px;
  cursor: pointer;
  i {
    font-size: 30px;
    line-height: 30px;
    display: block;
    margin: 0 auto;
    width: 30px;
  }
}
</style>
