<template>
  <div class="container">
    <template v-if="!isDepart">
      <direct-search
        ref="form"
        :label-position="'right'"
        :forms="searchList"
        :style="{ textAlign: 'left' }"
        @handleSearch="handleFormSearch"
      />
      <el-table-self
        ref="table"
        :table-data="tableData"
        :columns="columns"
        :list-loading="listLoading"
        :current-page="pageIndex"
        :total-count="total"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        @pageSizeChange="handleSizeChange"
        @currentPageChange="handleCurrentChange"
      />
      <dialog-form
        width="450px"
        :close-modal="false"
        ref="dialog"
        title="分配用户用户"
        :form-edit="formEdit"
        :form-data="formData"
        @handleConfirm="handleConfirm"
      ></dialog-form>
    </template>
  </div>
</template>

<script>
import paginationMixin from "@/components/TabComponents/mixin"
import {
  getGroupUserPage,
  addGroupUser,
  delGroupUser,
} from "@/api/coop-group.js"
import { getUserPage } from "@/api/user"
import { mapGetters } from "vuex"
export default {
  name: "GroupUser",
  mixins: [paginationMixin],
  props: {
    groupId: String,
  },
  data() {
    const userList = []
    getUserPage({ current: 1, size: 1000 }).then((res) => {
      if (res.code === 1) {
        const d = res.data
        d.records &&
          d.records.forEach((item) => {
            userList.push({
              label: item.name,
              value: item.id,
            })
          })
      }
    })
    return {
      isDepart: false,
      orgMap: {},
      listLoading: false,
      // 查询列表
      searchList: [
        {
          label: "用户名称",
          type: "input",
          prop: "userName",
          placeholder: "请输入用户名称",
        },
        {
          type: "button",
          value: "查询",
          icon: "el-icon-search",
        },
        {
          type: "button",
          color: "primary",
          icon: "el-icon-plus",
          value: "分配用户",
          func: this.handleAdd,
        },
      ],
      columns: [
        {
          label: "用户名称",
          minWidth: 120,
          value: "userName",
        },
        {
          label: "协作组",
          minWidth: 120,
          value: "groupName",
        },

        {
          label: "机构名称",
          minWidth: 120,
          value: "orgName",
        },
        {
          label: "科室名称",
          minWidth: 120,
          value: "deptName",
        },
        {
          label: "操作",
          width: 120,
          fixed: "right",
          operType: "button",
          operations: [
            {
              func: this.handleDel,
              formatter(row) {
                return {
                  label: "删除",
                  type: "danger",
                }
              },
            },
          ],
        },
      ],
      tableData: [],
      cacheForm: {},
      title: "",
      formData: [
        {
          type: "select",
          label: "用户",
          placeholder: "请选择用户",
          prop: "userId",
          multiple: true,
          opts: userList,
          rules: [{ required: true, message: "请选择用户" }],
        },
      ],
      formEdit: {},
    }
  },
  watch: {
    groupId(groupId) {
      if (groupId) {
        this.handleFormSearch({ groupId })
      } else {
        this.tableData = []
      }
    },
  },
  computed: {
    ...mapGetters({
      group: "user/group",
    }),
  },
  methods: {
    handleDepart({ orgName, id }) {
      this.orgMap = {
        orgName,
        orgId: id,
      }
      this.isDepart = true
    },
    handleAdd() {
      if (!this.cacheForm.groupId) {
        this.$message.error("请先选择/分配协作组")
        return
      }
      this.$refs.dialog.open()
    },
    handleConfirm(form) {
      const data = form.userId.map((_) => {
        return {
          groupId: this.cacheForm.groupId,
          userId: _,
        }
      })
      addGroupUser(data)
        .then((res) => {
          if (res.code === 1) {
            this.$message.success("分配用户成功")
            this.handleSearch()
          }
        })
        .finally(() => {
          this.$refs.dialog.close()
        })
    },
    handleDel(row) {
      this.$confirm(`是否删除【${row.userName}】?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delGroupUser(row.id).then((res) => {
            if (res.code === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              })
              this.handleSearch()
            }
          })
        })
        .catch(() => {})
    },

    // 查询
    handleFormSearch(form) {
      this.pageIndex = 1
      this.handleSearch(form)
    },
    handleSearch(form) {
      const params = Object.assign(this.cacheForm, form)
      this.listLoading = true
      for (let key in params) {
        if (params[key] === "") {
          delete params[key]
        }
      }
      params.current = this.pageIndex
      params.size = this.pageSize
      getGroupUserPage(params).then((res) => {
        this.listLoading = false
        if (res.code === 1) {
          const d = res.data
          this.tableData = d.records || []
          this.total = Number(d.total)
        }
      })
    },
  },
  created() {
    const routeName = this.$route.name
    if (routeName === "GroupUser" && this.group.groupId) {
      this.handleFormSearch({ groupId: this.group.groupId })
    }
  },
}
</script>
