<template>
  <div class="app-container">
    <div class="head-container">
      <!-- 搜索 -->
      <el-input
        v-model="listQuery.Filter"
        clearable
        size="small"
        placeholder="搜索..."
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        class="filter-item searchbutton"
        size="mini"
        type="success"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索
      </el-button>
      <div style="padding: 6px 0;">
        <el-button
          class="filter-item addbutton"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="handleCreate"
          v-permission="['BaseService.Job.Create']"
        >新增
        </el-button>
        <el-button
          class="filter-item modifybutton"
          size="mini"
          type="success"
          icon="el-icon-edit"
          @click="handleUpdate()"
        >修改
        </el-button>
        <el-button
          slot="reference"
          class="filter-item delbutton"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete()"
        >删除
        </el-button>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :title="formTitle"
      @close="cancel()"
      width="800px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <el-form-item label="选择用户" prop="userId">
          <template prop="userId">
            <el-popover
              placement="bottom"
              width="700"
              trigger="manual"
              v-model="showPopover">
              <CrmRelativeProduct
                v-if="showPopover"
                action="default"
                @close="showPopover=false"
                @changeCheckout="checkInfos"
                :filedString="whichone"
              />
              <flexbox
                slot="reference"
                wrap="wrap"
                class="flexbox-container"
                @click.native="contentClick">
                <div ref="getname"
                     v-for="(item, index) in dataValue"
                     :key="index"
                     class="flexbox-item"
                     @click.stop="deleteinfo(index)">{{ item.name }}
                  <i class="delete-icon el-icon-close"/>
                </div>
                <div
                  v-if="dataValue.length == 0"
                  class="add-item">+添加
                </div>
              </flexbox>
            </el-popover>
          </template>
        </el-form-item>
        <el-form-item label="选择组织" prop="orgId">
          <template prop="orgId">
            <el-popover
              placement="bottom"
              width="700"
              trigger="manual"
              v-model="showPopoverorg">
              <CrmRelativeProduct
                v-if="showPopoverorg"
                action="default"
                @close="showPopoverorg=false"
                @changeCheckout="checkInfosorg"
                :filedString="whichone"
              />
              <flexbox
                slot="reference"
                wrap="wrap"
                class="flexbox-container"
                @click.native="contentClickorg">
                <div ref="getname"
                     v-for="(item, index) in dataValueorg"
                     :key="index"
                     class="flexbox-item"
                     @click.stop="deleteinfoorg(index)">{{ item.name }}
                  <i class="delete-icon el-icon-close"/>
                </div>
                <div
                  v-if="dataValueorg.length == 0"
                  class="add-item">+添加
                </div>
              </flexbox>
            </el-popover>
          </template>
        </el-form-item>
        <el-form-item label="选择角色" prop="role">
          <span v-for="item in form.roles" style="margin-right: 5px">
            <el-checkbox v-model="item.role">{{item.roleName}}</el-checkbox>
          </span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="text" @click="cancel">取消</el-button>
        <el-button size="small" v-loading="formLoading" type="primary" @click="save">确认</el-button>
      </div>
    </el-dialog>
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      size="small"
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="44px"></el-table-column>
      <el-table-column label="用户名称" prop="name" sortable="custom" align="center" width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属组织" prop="sort" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.description}}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" prop="sort" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.description}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
            v-permission=""
            icon="el-icon-edit"
          />
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(row)"
            v-permission=""
            icon="el-icon-delete"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="totalCount>0"
      :total="totalCount"
      :page.sync="page"
      :limit.sync="listQuery.MaxResultCount"
      @pagination="getList"
    />
  </div>
</template>

<script>
  import Pagination from "@/components/Pagination";
  import permission from "@/directive/permission/index.js";
  import CrmRelativeProduct from "./model/CrmRelativeProduct"; //引入子组件

  export default {
    name: "SystemOrgUserRole",
    components: {Pagination, CrmRelativeProduct},
    directives: {permission},
    data() {
      return {
        rules: {
          userId: [{required: true, message: "请选择用户", trigger: "blur"}],
          orgId: [{required: true, message: "请选择组织", trigger: "blur"}],
          roles: [{required: false, message: "请选择角色", trigger: "blur"}]
        },
        defaultForm: {
          userId: null,
          orgId: null,
          roles: []
        },
        form: {},
        list: null,
        totalCount: 0,
        listLoading: true,
        formLoading: false,
        listQuery: {
          Filter: "",
          Sorting: "",
          SkipCount: 0,
          MaxResultCount: 10
        },
        page: 1,
        dialogFormVisible: false,
        multipleSelection: [],
        formTitle: "",
        isEdit: false,
        showPopover: false, // 内容
        showPopoverorg: false,
        dataValue: [],
        dataValueorg: [],
        whichone: 'user',
      };
    },
    created() {
      this.getList();
    },
    methods: {
      getList() {
        this.listLoading = true;
        this.listQuery.SkipCount = (this.page - 1) * 10;
        this.$axios
          .gets("/api/base/userOrgRole/all", this.listQuery)
          .then(response => {
            this.list = response.items;
            this.totalCount = response.totalCount;
            this.listLoading = false;
          });
      },
      fetchData(id) {
        this.$axios.gets("/api/base/userOrgRole/" + id).then(response => {
          this.form = response;
          this.form.userId = response.userId;
          this.form.orgId = response.orgId;
          this.dataValue.push(response.userIdToName)
          this.dataValueorg.push(response.orgIdToName)
          this.form.roles = this.form.roles.map(item => {
            if (item.id == response.roleId) {
              return {
                'roleName': item.name,
                'id': item.id,
                'role': true
              }
            } else {
              return {
                'roleName': item.name,
                'id': item.id,
                'role': false
              }
            }
          })

        });
      },
      handleFilter() {
        this.page = 1;
        this.getList();
      },
      save() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.formLoading = true;
            this.form.roleNames = this.checkedRole;
            if (this.isEdit) {
              this.$axios
                .puts("/api/base/userOrgRole/" + this.form.id, this.form)
                .then(response => {
                  this.formLoading = false;
                  this.$notify({
                    title: "成功",
                    message: "更新成功",
                    type: "success",
                    duration: 2000
                  });
                  this.dialogFormVisible = false;
                  this.getList();
                })
                .catch(() => {
                  this.formLoading = false;
                });
            } else {
              this.form.roles = this.form.roles.map(item => {
                if (item.role == true)
                  return {
                    roleID: item.id
                  }
              })
              this.$axios
                .posts("/api/base/userOrgRole", this.form)
                .then(response => {
                  this.formLoading = false;
                  this.$notify({
                    title: "成功",
                    message: "新增成功",
                    type: "success",
                    duration: 2000
                  });
                  this.dialogFormVisible = false;
                  this.getList();
                })
                .catch(() => {
                  this.formLoading = false;
                });
            }
          }
        });
      },
      handleCreate() {
        this.formTitle = "新增";
        this.isEdit = false;
        this.dialogFormVisible = true;
        this.getAllRole()
      },
      handleDelete(row) {
        var params = [];
        let alert = "";
        if (row) {
          params.push(row.id);
          alert = row.name;
        } else {
          if (this.multipleSelection.length === 0) {
            this.$message({
              message: "未选择",
              type: "warning"
            });
            return;
          }
          this.multipleSelection.forEach(element => {
            let id = element.id;
            params.push(id);
          });
          alert = "选中项";
        }
        this.$confirm("是否删除" + alert + "?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$axios
              .posts("/api/base/userOrgRole/delete", params)
              .then(response => {
                this.$notify({
                  title: "成功",
                  message: "删除成功",
                  type: "success",
                  duration: 2000
                });
                this.getList();
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      handleUpdate(row) {
        this.formTitle = "修改";
        this.isEdit = true;
        this.getAllRole()
        if (row) {
          this.fetchData(row.id);
          this.dialogFormVisible = true;
        } else {
          if (this.multipleSelection.length != 1) {
            this.$message({
              message: "编辑必须选择单行",
              type: "warning"
            });
            return;
          } else {
            this.fetchData(this.multipleSelection[0].id);
            this.dialogFormVisible = true;
          }
        }
      },
      sortChange(data) {
        const {prop, order} = data;
        if (!prop || !order) {
          this.handleFilter();
          return;
        }
        this.listQuery.Sorting = prop + " " + order;
        this.handleFilter();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleRowClick(row, column, event) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(row);
      },
      cancel() {
        this.form = Object.assign({}, this.defaultForm);
        this.dialogFormVisible = false;
        this.$refs.form.clearValidate();
      },
      changeEnabled(data, val) {
        data.active = val ? "启用" : "停用";
        this.$confirm("是否" + data.active + data.name + "？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$axios
              .puts("/api/base/job/" + data.id, data)
              .then(response => {
                this.$notify({
                  title: "成功",
                  message: "更新成功",
                  type: "success",
                  duration: 2000
                });
              })
              .catch(() => {
                data.enabled = !data.enabled;
              });
          })
          .catch(() => {
            data.enabled = !data.enabled;
          });
      },

      getAllRole() {
        this.$axios
          .gets("/api/identity/roles/all")
          .then(response => {
            this.defaultForm.roles = response.items.map(item => {
              return {
                'roleName': item.name,
                'id': item.id,
                'role': false
              }
            })
            this.form = Object.assign({}, this.defaultForm)
          });

      },
      contentClick() {
        this.showPopover = true;
        this.whichone = 'user'
      },
      contentClickorg() {
        this.showPopoverorg = true;
        this.whichone = 'org'

      },
      checkInfos(data) {
        this.dataValue = data.data ? data.data : []
        this.$set(this.dataValue, data.data);
        this.dataValue.map(item => {//将弹窗回填的值绑定到form表单中的name字段上
          this.$set(this.form, 'userId', item.id)
        })
      },
      /** 删除 */
      deleteinfo(index) {
        if (this.dataValue.length === 1) {
          this.dataValue = []
        } else {
          this.dataValue.splice(index, 1)
        }

        this.$emit('value-change', {
          index: this.index,
          value: this.dataValue
        })
      },

      checkInfosorg(data) {
        this.dataValueorg = data.data ? data.data : []
        this.$set(this.dataValueorg, data.data);
        this.dataValueorg.map(item => {//将弹窗回填的值绑定到form表单中的name字段上
          this.$set(this.form, 'orgId', item.id)
        })
      },
      /** 删除 */
      deleteinfoorg(index) {
        if (this.dataValueorg.length === 1) {
          this.dataValueorg = []
        } else {
          this.dataValueorg.splice(index, 1)
        }

        this.$emit('value-change', {
          index: this.index,
          value: this.dataValueorg
        })
      },
    }
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .flexbox-container {
    position: relative;
    border-radius: 3px;
    font-size: 12px;
    border: 1px solid #ddd;
    color: #333333;

    margin-top: 3px;
    padding: 5px;
    line-height: 10px;
    min-height: 25px;
    max-height: 105px;
    overflow-y: auto;
    min-width: 200px;
    max-width: 50px;

    .flexbox-item {
      background-color: #e2ebf9;
      border-radius: 3px;
      padding: 5px;
      cursor: pointer;
    }

    .add-item {
      padding: 5px;
      color: #3e84e9;
      cursor: pointer;
    }

    .delete-icon {
      color: #999;
      cursor: pointer;
    }

    &:hover {
      border-color: #c0c4cc;
    }
  }
</style>
