<template>
  <basic-container>
    <div style="margin-bottom: 10px">
      <el-button v-if="permission.manage_rules_ruleTypes_addFirstType" @click="handleAddFirstType" type="primary"
        >新增一级分类</el-button
      >
      <el-button type="danger" @click="mutiDel">批量删除</el-button>
      <el-button type="success" @click="mutiShowOrHidType('show')"
        >批量显示</el-button
      >
      <el-button type="info" @click="mutiShowOrHidType('hide')"
        >批量隐藏</el-button
      >
    </div>

    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      @selection-change="handleSelectionChange"
      v-loading="loading"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="" label="序号" width="50">
        <template slot-scope="scope">{{ scope.row.index }}</template>
      </el-table-column>
      <el-table-column type="" prop="parentName" label="一级分类" width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="二级分类"
        width="180"
        :style="secondTypeSelfStyle"
      >
        <template slot-scope="{ row }">
          <span v-if="row.children">展开</span>
          <!-- <span v-if="row.children && !row.open" @click="openItem(row)" class="rules-open-close-item">收起</span>-->
          <span v-if="row.type == 2">{{ row.name }}</span>
          <span v-if="row.type == 1 && !row.children">-</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="{ row }">
          <span v-if="row.status == 0">显示</span>
          <span v-else>隐藏</span>
        </template>
      </el-table-column>
      <el-table-column prop="" label="排序">
        <template slot-scope="{ row }">
          <el-button type="text" @click="moveType(row, 'up')">上移</el-button>
          <el-button type="text" @click="moveType(row, 'down')">下移</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作">
        <template slot-scope="{ row }">
          <el-button
            v-if="row.status == 0 && permission.manage_rules_ruleTypes_hideType"
            type="text"
            @click="hideOrShowRule(row.id, 'hide')"
            >隐藏</el-button
          >
          <el-button v-if="row.status==1 && permission.manage_rules_ruleTypes_showType" type="text" @click="hideOrShowRule(row.id, 'show')"
            >显示</el-button
          >
          <el-button
            type="text"
            @click="viewRuleType(row.id)"
            v-if="row.type == 1"
            >查看</el-button
          >

          <el-button type="text" @click="delRule(row.id)" v-if="permission.manage_rules_ruleTypes_delType">删除</el-button>

          <el-button
            @click="handleAddSecondType(row.id)"
            icon="el-icon-circle-plus-outline"
            type="text"
            v-if="row.type == 1 && permission.manage_rules_ruleTypes_addSecondType"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--添加一级分类的抽屉-->
    <el-drawer
      :title="drawerTitle"
      :before-close="handleClose"
      :visible.sync="addFirstTypeDrawer"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      size="50%"
    >
      <div class="demo-drawer__content">
        <el-form :model="form" :rules="rules" ref="firstTypeForm">
          <el-form-item
            label="一级分类名称"
            :label-width="formLabelWidth"
            prop="name"
          >
            <el-input
              v-model="form.name"
              autocomplete="off"
              maxlength="20"
              required
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item
            label="分类介绍"
            :label-width="formLabelWidth"
            prop="introduce"
          >
            <el-input
              type="textarea"
              v-model="form.introduce"
              required
              maxlength="100"
              show-word-limit
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="温馨提示"
            :label-width="formLabelWidth"
            prop="prompt"
          >
            <el-input
              type="textarea"
              v-model="form.prompt"
              required
              maxlength="100"
              show-word-limit
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="addFirstTypeDrawer=false">取 消</el-button>
          <el-button type="primary" @click="addFirstTypesubmit" :loading="addFirstTypeBtnLoading">提交</el-button>
        </div>
      </div>
    </el-drawer>
    <!--添加二级分类-->
    <el-dialog
      title="添加二级分类"
      :visible.sync="secondTypeDialogVisible"
      append-to-body
    >
      <el-form
        :model="secondTypeform"
        :rules="addSecondTypeFormRules"
        ref="addSecondTypeForm"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model="secondTypeform.name"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="secondTypeDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitAddSecondType"
          :loading="submitBtnLoading"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!---->
  </basic-container>
</template>
<script>
import {
  getRuleTypesList,
  delRuleType,
  hideRuleType,
  addRuleType,
  addSecondRuleType,
  ruleTypeDetail,
  moveRuleType,
  editTypeInfo,
} from "@/api/manage/rules";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      selectionList: [],
      tableData: [],
      loading: false,
      drawerTitle: false,
      addFirstTypeDrawer: false,
      secondTypeDialogVisible: false,
      parentId: null,
      open: true,
      operateType: "",
      editTypeId: "",
      submitBtnLoading: false,
      addFirstTypeBtnLoading:false,
      form: {
        name: "",
        introduce: "",
        prompt: "",
      },
      secondTypeform: {
        name: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入一级分类名称", trigger: "blur" },
        ],

        introduce: [{ required: true, message: "请输入介绍", trigger: "blur" }],
        prompt: [
          { required: true, message: "请输入温馨提示", trigger: "blur" },
        ],
      },
      addSecondTypeFormRules: {
        name: [
          { required: true, message: "请输入二级分类名称", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((element) => {
        ids.push(element.id);
      });
      return ids;
    },
  },
  mounted() {
    this.onload();
  },
  methods: {
    handleSelectionChange(list) {
      this.selectionList = list;
    },
    /**查看一级分类 */
    viewRuleType(id) {
      this.operateType = "edit";
      this.drawerTitle = "查看一级分类";
      this.editTypeId = id;
      ruleTypeDetail(id).then((res) => {
        this.form = res.data.data;
        this.addFirstTypeDrawer = true;
      });
    },
    handleAddFirstType() {
      this.operateType = "add";
      this.drawerTitle = "新增一级分类";
      this.addFirstTypeDrawer = true;
      this.form = {
        name: "",
        introduce: "",
        prompt: "",
      };
    },
    /**新增/编辑一级分类 */
    addFirstTypesubmit() {
      this.addFirstTypeBtnLoading=true;
      const fatherId = 0;
      const remarks = "";
      this.$refs.firstTypeForm.validate((valid) => {
        if (valid) {
          if (this.operateType == "add") {
            addRuleType(
              fatherId,
              this.form.name,
              this.form.introduce,
              this.form.prompt,
              remarks
            )
              .then(() => {
                this.addFirstTypeBtnLoading=false;
                this.$message.success("添加成功");
                this.addFirstTypeDrawer = false;
                this.onload();
              })
              .catch((err) => {
                this.$message.error(err);
              });
          } else {
            let idArr = [];
            idArr.push(this.editTypeId);
            editTypeInfo(
              idArr,
              this.form.name,
              this.form.introduce,
              this.form.prompt
            ).then(() => {
              this.addFirstTypeBtnLoading=false;
              this.$message.success("修改成功");
              this.addFirstTypeDrawer = false;
              this.onload();
            });
          }
        }
      });
    },
    /**新增二级分类 */
    handleAddSecondType(fatherId) {
      this.parentId = fatherId;
      this.secondTypeDialogVisible = true;
      this.secondTypeform = {};
    },
    submitAddSecondType() {
      this.submitBtnLoading = true;
      this.$refs.addSecondTypeForm.validate((valid) => {
        if (valid) {
          addSecondRuleType(this.parentId, this.secondTypeform.name).then(
            () => {
              this.submitBtnLoading = false;
              this.secondTypeDialogVisible = false;
              this.$message.success("添加成功");
              this.onload();
            }
          );
        }
      });
    },
    hideOrShowRule(id, type) {
      let ids = [];
      ids.push(id);
      let tips = type == "show" ? "显示" : "隐藏";
      type = type == "show" ? 0 : 1;
      this.$confirm(`是否确定${tips}该分类?`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        hideRuleType(ids, type)
          .then(() => {
            this.$message.success(`${tips}成功`);
            this.onload();
          })
          .catch((err) => {
            this.$message.error(err);
          });
      });
    },

    mutiShowOrHidType(type) {
      let tips = type == "show" ? "显示" : "隐藏";
      type = type == "show" ? 0 : 1;

      if (this.selectionList.length == 0) {
        this.$message.closeAll();
        this.$message.error("至少选择一条数据");
      } else {
        this.$confirm(`是否确定批量${tips}分类?`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          hideRuleType(this.ids, type)
            .then(() => {
              this.$message.success("操作成功");
              this.onload();
            })
            .catch((err) => {
              this.$message.error(err);
            });
        });
      }
    },
    mutiDel() {
      if (this.selectionList.length == 0) {
        this.$message.closeAll();
        this.$message.error("至少选择一条数据");
      } else {
        this.$confirm("是否确定批量删除分类?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          delRuleType(this.ids, 1)
            .then(() => {
              this.$message.success("批量删除成功");
              this.onload();
            })
            .catch((err) => {
              this.$message.error(err);
            });
        });
      }
    },
    delRule(id) {
      let ids = [];
      ids.push(id);
      this.$confirm("是否确定删除该分类?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delRuleType(ids, 1)
          .then(() => {
            this.$message.success("删除成功");
            this.onload();
          })
          .catch((err) => {
            this.$message.error(err);
          });
      });
    },
    /**移动分类顺序 */
    moveType(row, type) {
      type = type == "up" ? 0 : 1;
      moveRuleType(row.id, type, row.sort, row.fatherId).then(() => {
        this.$message.closeAll();
        this.$message.success("操作成功");
        this.onload();
      });
    },
    onload() {
      this.loading = true;
      getRuleTypesList().then((res) => {
        let data = res.data.data;
        let i = 1;
        data.forEach((element) => {
          if (element["type"] == 1) {
            element["parentName"] = element["name"];
            delete element["name"];
          }
          if (element["rulesGroups"]) {
            element["index"] = i++;

            if (element["rulesGroups"].length != 0) {
              element["children"] = element["rulesGroups"];
            }
          }
        });
        this.tableData = data;
        this.loading = false;
      });
    },
  },
};
</script>
<style >
</style>