<template>
  <div>
    <div class="d-flex flex-between">
      <div>
        <el-button type="success" size="medium" @click="addData">
          <span class="d-in-block v-mid el-icon-plus font-size-16"></span>
          <span class="d-in-block v-mid font-size-16">创建</span>
        </el-button>
        <el-button type="danger" size="medium" :disabled="multipleSelection.length == 0" @click="delData">
          <span class="d-in-block v-mid font-size-16">删除</span>
        </el-button>
      </div>
      <el-form label-width="100px" :inline="true">
        <el-form-item prop="qjylb_zylbmc">
          <el-input placeholder="请输入搜索关键字" v-model="qjylb_zylbmc" clearable @clear="getListData">
          </el-input>
        </el-form-item>
        <el-button type="primary" class="ml5" @click="getListData">搜索</el-button>
      </el-form>
    </div>
    <el-table :data="tableData" tooltip-effect="dark" v-loading="loading" ref="multipleTable" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" align="center" width="55">
      </el-table-column>
      <el-table-column label="序号" align="center" type="index" width="50">
      </el-table-column>
      <el-table-column label="资源类别名称" show-overflow-tooltip prop="qjylb_zylbmc" width="200">
      </el-table-column>
      <el-table-column label="资源描述" show-overflow-tooltip prop="qjylb_zyms" width="auto">
      </el-table-column>
      <el-table-column label="创建人" width="100" prop="qjylb_cjr"></el-table-column>
      <el-table-column label="创建时间" width="200" prop="qjylb_cjsj"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" @click="editData(scope.row)">编辑 </el-button>
          <el-button type="text" @click="setQxData(scope.row)">权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <footer class="flex-item-none" style="display: flex; justify-content: flex-end; margin-top: 30px">
      <el-pagination background layout="total,prev, pager, next" :page-size="limit" :total="total"></el-pagination>
    </footer>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="580px">
      <el-form :model="dialogForm" ref="dialogForm" :rules="rules" label-width="110px">
        <el-form-item label="资源类别名称" prop="qjylb_zylbmc">
          <el-input v-model="dialogForm.qjylb_zylbmc" placeholder="请输入资源类别名称"></el-input>
        </el-form-item>

        <el-form-item label="资源描述" prop="qjylb_zyms">
          <el-input type="textarea" v-model="dialogForm.qjylb_zyms" placeholder="请输入资源描述"></el-input>

        </el-form-item>

      </el-form>
      <div slot="footer">
        <el-button @click="formCancel">取 消</el-button>
        <el-button type="primary" :disabled="isButton" @click="formSubmit('dialogForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 权限 -->
    <el-dialog title="权限设置" :visible.sync="setDialogFormVisible" width="600px">
      <el-form :model="dialogForm" ref="zyqx_set" :rules="rules_check" label-width="100px" label-position="left">
        <el-form-item label="学校名称" prop="mineStatus">
          <el-select v-if="setDialogFormVisible" v-model="dialogForm.mineStatus" placeholder="请选择" multiple @change="selectChange" style="width:100%">
            <el-option :value="mineStatusValue" style="height: auto">
              <el-tree :data="treeData" show-checkbox node-key="id" default-expand-all ref="tree" highlight-current :default-checked-keys="sendData" :props="defaultProps" @check-change="handleCheckChange"></el-tree>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="setDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="qXFormSubmit('zyqx_set')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog title="权限设置" :visible.sync="setDialogFormVisible" width="600px" :close-on-click-modal="false" @close="formCancel">
      <el-select v-model="mineStatus" placeholder="请选择" multiple filterable @change="selectChange" style="flex: 1;">
        <el-option :value="mineStatusValue" style="height: auto">
          <el-tree default-expand-all :data="treeData" show-checkbox node-key="id" ref="tree" highlight-current :default-checked-keys="sendData" :props="defaultProps" @check-change="handleCheckChange"></el-tree>
        </el-option>
      </el-select>

      <div slot="footer">
        <el-button @click="formCancel">取消</el-button>
        <el-button type="primary" @click="qXFormSubmit('zyqx_set')">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { useUserStore } from "@/stores/user";
const { real_name } = useUserStore();
import { zylbgl_list, zylbgl_add, zylbgl_del, zylbgl_edit, org_tree, qx_get, qx_set } from "./api";
export default {
  name: "index",
  data() {
    return {
      isButton: false,
      isEdit: false,
      qjylb_zylbmc: "",
      dialogForm: {
        qjylb_zylbmc: "",
        qjylb_zyms: "",
        qjylb_cjr: "",
        qjylb_cjsj: "",
        mineStatus: []
      },
      tableData: [],
      limit: 10,
      total: 12,
      cur_page: 1,
      title: "",
      id: "",
      loading: false,
      dialogFormVisible: false,
      multipleSelection: [],
      rules: {
        qjylb_zylbmc: [
          { required: true, message: "请输入资源类别名称", trigger: "submit" },
        ],
        qjylb_zyms: [
          { required: true, message: "请输入资源描述", trigger: "blur" },
        ]
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      departmentData: [],
      setDialogFormVisible: false,
      mineStatusValue: [],
      sendData: [],
      rules_check: {
        mineStatus: [
          { required: true, message: '请勾选权限', trigger: 'change' }
        ],
      },
      treeData: []
    };
  },

  methods: {
    //组织机构树形
    getOrgTree() {
      org_tree({})
        .then(res => {
          if (res.code == "1") {
            //  let treeData = res.data.one_info;
            this.treeData = res.data.one_info;
          }
        })
        .catch(err => { console.log(err) })
    },

    //select框值改变时候触发的事件
    selectChange(e) {
      console.log(this.mineStatusValue, 55);
      var arrNew = [];
      var dataLength = this.mineStatusValue.length;

      var eleng = e.length;
      for (let i = 0; i < dataLength; i++) {
        for (let j = 0; j < eleng; j++) {
          if (e[j] === this.mineStatusValue[i].label) {
            arrNew.push(this.mineStatusValue[i])
          }
        }
      }
      this.$refs.tree.setCheckedNodes(arrNew);//设置勾选的值
    },
    handleCheckChange() {
      let res = this.$refs.tree.getCheckedNodes(true, true); //这里两个true，1. 是否只是叶子节点 2. 是否包含半选节点（就是使得选择的时候不包含父节点）
      let arrLabel = [];
      let arr = [];
      res.forEach(item => {
        arrLabel.push(item.label);
        arr.push(item);
      });
      this.mineStatusValue = arr;
      this.dialogForm.mineStatus = arrLabel;
      console.log('arr:' + JSON.stringify(arr))
      console.log('arrLabel:' + arrLabel)
    },

    async setQxData(item) {
      this.sendData = [];
      this.dialogForm.mineStatus = [];
      this.mineStatusValue = [];
      this.setDialogFormVisible = true;
      this.qjylb_id = item.qjylb_id;
      let obj = {
        qjylb_id: item.qjylb_id,
        site: "jnmf",
      }
      let data = await qx_get(obj)
        .then(res => {
          if (res.code == "1") {
            let empower = res.data.empower;
            return empower

          }
        })
        .catch(err => { console.log(err) })
      // let res = await qx_get(obj)
      // console.log(res, 687);
      // 
      let arr = [];
      data.map(item => {
        arr.push(item.jqq_dept_id);
        this.dialogForm.mineStatus.push(item.jqq_keyword);
      })
      this.sendData = JSON.parse(JSON.stringify(arr));

      this.$nextTick(() => {
        this.mineStatusValue = this.$refs.tree.getCheckedNodes(true, true);
      })
    },
    qXFormSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //JSON处理下 提交的参数
          console.log(this.mineStatusValue, "000")
          let tempJson = [];
          this.mineStatusValue.forEach(item => {
            tempJson.push({
              jqq_dept_id: item.id,
              jqq_keyword: item.label
            })
          })
          let transObj = {
            issubmit: 1,
            qjylb_id: this.qjylb_id,
            jdbg_qjylb_qx: tempJson
          };
          qx_set(transObj).then((res) => {
            if (res.code == 1) {
              this.$message({
                message: "设置成功！",
                type: "success",
              });
              this.getListData();
              this.setDialogFormVisible = false;
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          });

        }
      })
    },
    getListData() {
      this.loading = true;
      let data = {
        page: this.cur_page,
        limit: this.limit,
        qjylb_zylbmc: this.qjylb_zylbmc,
      };
      zylbgl_list(data).then((res) => {
        this.loading = false;
        this.tableData = res.data.page_data;
        this.cur_page = Number(res.data.page_now);
        this.total = Number(res.data.total_rows);


      });
    },
    handleCurrentChange(val) {
      this.cur_page = val;
      this.getListData();
    },

    addData() {
      this.title = "创建";
      this.isButton = false;
      this.dialogForm = {
        qjylb_zylbmc: "",
        qjylb_zyms: "",
        qjylb_cjr: "",
        qjylb_cjsj: "",

      };

      this.dialogFormVisible = true;
    },
    editData(item) {
      this.title = "编辑";
      this.isEdit = true;
      this.dialogFormVisible = true;
      this.id = item.qjylb_id;
      this.dialogForm.qjylb_zylbmc = item.qjylb_zylbmc;
      this.dialogForm.qjylb_zyms = item.qjylb_zyms;
    },
    formSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
           this.isButton = true;
          let data = {
            qjylb_zylbmc: this.dialogForm.qjylb_zylbmc,
            qjylb_zyms: this.dialogForm.qjylb_zyms,
            qjylb_cjr: real_name,

          };
          if (!this.isEdit) {
            zylbgl_add(data).then((res) => {
              if (res.code == 1) {
                this.$message({
                  message: "类别添加成功！",
                  type: "success",
                });
                this.getListData();
                this.dialogFormVisible = false;

              } else {
                  this.isButton = false;
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          } else {
            data.qjylb_id = this.id;
            zylbgl_edit(data).then((res) => {
              if (res.code == 1) {
                this.$message({
                  message: "类别编辑成功！",
                  type: "success",
                });
                this.dialogFormVisible = false;
                this.getListData();
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          }
        }
      });
    },
    formCancel() {
      this.dialogFormVisible = false;
    },

    delData() {
      this.$confirm("确认删除该类别?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            qjylb_id: this.multipleSelection,
          };
          zylbgl_del(data).then((res) => {
            if (res.code == 1) {
              this.$message({
                message: "类别删除成功！",
                type: "success",
              });
              this.getListData();
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          });
        })
        .catch(() => { });
    },
    handleSelectionChange(val) {
      this.multipleSelection = [];
      for (let i in val) {
        this.multipleSelection.push(val[i].qjylb_id);
      }
    },
  },
  mounted() {
    this.getListData();
    this.getOrgTree()
  },
};
</script>

<style scoped>
::v-deep .el-dialog__body {
  border-top: 1px solid #f0f3f8;
}
</style>