<template>
  <div class="container">
    <direct-search
      ref="form"
      :label-position="'right'"
      :forms="searchList"
      :style="{ textAlign: 'left' }"
      @handleSearch="handleFormSearch"
    />
    <el-table-self
      ref="table"
      :table-data="tableData"
      :columns="columns"
      tab-type="index"
      tab-label="序号"
      :list-loading="listLoading"
      :current-page="pageIndex"
      :total-count="total"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      @pageSizeChange="handleSizeChange"
      @currentPageChange="handleCurrentChange"
    />
    <dialog-form
      ref="dialog"
      width="750px"
      :close-modal="false"
      :title="title"
      :form-edit="formEdit"
      :form-data="formData"
      @handleConfirm="handleConfirm"
    ></dialog-form>
    <dialog-form
      ref="role"
      width="450px"
      title="角色授权"
      :form-data="formDataRole"
      @handleConfirm="handleRoleConfirm"
    ></dialog-form>
    <dialog-form
      ref="consortiaRole"
      width="450px"
      title="医联体授权"
      :form-data="consortiaDataRole"
      :current="current"
      @handleConfirm="handleConsortiaConfirm"
      @loadMore="loadMore"
    ></dialog-form>
  </div>
</template>

<script>
import paginationMixin from "@/components/TabComponents/mixin"
import {
  getUserPage,
  addUser,
  delUser,
  getHprolePage,
  getUserInfo,
  setUserRole,
  resetPassword,
  baseEnable,
} from "@/api/user"
import { getOrgList, getDepartPage } from "@/api/org"
import { medicalunionList, baseUnion } from "@/api/medicalunion-management"

import { mapGetters } from "vuex"
export default {
  name: "User",
  mixins: [paginationMixin],
  data() {
    const isAdmin = this.$store.getters["user/roles"].find(
      (_) => _.roleCode === "admin"
    )
    const roleList = []
    getHprolePage({ current: 1, size: 100 }).then((res) => {
      if (res.code === 1) {
        const d = res.data
        d.records.forEach((item) => {
          roleList.push({
            label: item.roleName,
            value: item.id,
            roleCode: item.roleCode,
            disabled: item.roleCode !== "doctor" && !isAdmin,
          })
        })
      }
    })
    const orgList = []
    getOrgList().then((res) => {
      if (res.code === 1) {
        const d = res.data || []
        d.forEach((item) => {
          orgList.push({
            label: item.orgName,
            value: item.id,
          })
        })
      }
    })

    const validatePass = (rule, value, callback) => {
      if (value !== this.$refs.dialog.form.passwd) {
        callback(new Error("两次输入密码不一致!"))
      } else {
        callback()
      }
    }
    return {
      listLoading: false,
      current: 1,
      isAdd: false,
      id: null,
      // 查询列表
      searchList: [
        {
          label: "选择角色",
          type: "select",
          opts: roleList,
          prop: "roleId",
          placeholder: "请选择角色",
        },
        {
          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,
        },
      ],
      searchQuery: "",
      columns: [
        {
          label: "登录名",
          width: 140,
          value: "userName",
        },
        {
          label: "角色",
          value: "roles",
          minWidth: 180,
          formatter: (row) => {
            if (row.roles.length > 0) {
              let roleName = row.roles.map((e) => e.roleName)
              return roleName.join("、")
            } else {
              return "--"
            }
          },
        },
        {
          label: "医联体名称",
          value: "unions",
          minWidth: 180,
          formatter: (row) => {
            if (row.unions.length > 0) {
              let unionName = row.unions.map((e) => e.unionName)
              return unionName.join("、")
            } else {
              return "--"
            }
          },
        },
        {
          label: "医联体编号",
          value: "unions",
          minWidth: 180,
          formatter: (row) => {
            if (row.unions.length > 0) {
              let unionNo = row.unions.map((e) => e.unionNo)
              return unionNo.join("、")
            } else {
              return "--"
            }
          },
        },
        {
          label: "添加时间",
          width: 140,
          value: "createTime",
          formatter: (row) => {
            if (row.createTime) {
              return row.createTime
            } else {
              return "--"
            }
          },
        },
        {
          label: "状态",
          width: 140,
          type: "switch",
          value: "status",
          func: this.openChage,
        },
        {
          label: "操作",
          width: 220,
          fixed: "right",
          type: "button",
          operations: [
            {
              func: this.handleAdd,
              formatter(row) {
                return {
                  label: "编辑",
                  type: "primary",
                }
              },
            },
            {
              type: "dropdown",
              children: [
                {
                  func: this.handleRole,
                  icon: "el-icon-user",
                  label: "角色授权",
                  style: {
                    color: "#409EFF",
                  },
                },
                {
                  func: this.handleConsortia,
                  icon: "el-icon-office-building",
                  label: "医联体授权",
                  style: {
                    color: "#67C23A",
                  },
                },
                {
                  func: this.handleReset,
                  label: "重置密码",
                  icon: "el-icon-refresh",
                  style: {
                    color: "#E6A23C",
                  },
                },
                {
                  formatter: (row) => {
                    const disabled =
                      row.id === this.$store.getters["user/userInfo"].id
                    return {
                      disabled,
                      label: "删除",
                      style: {
                        color: disabled ? "#bbb" : "#F56C6C",
                        cursor: disabled ? "not-allowed" : "",
                        "pointer-events": "auto",
                      },
                    }
                  },
                  func: this.handleDel,
                  icon: "el-icon-delete",
                },
              ],
            },
          ],
        },
        // {
        //   label: "登录名",
        //   minWidth: 120,
        //   value: "name",
        // },
        // {
        //   label: "性别",
        //   value: "sex",
        //   width: 80,
        //   formatter: (row) => {
        //     return this.$handle.formatDicList(
        //       this.dictMap["d-sex"],
        //       String(row.sex)
        //     )
        //   },
        // },
        // {
        //   label: "身份证号",
        //   value: "idCard",
        //   minWidth: 180,
        // },
        // {
        //   label: "手机",
        //   minWidth: 120,
        //   value: "phone",
        // },
        // {
        //   label: "机构",
        //   minWidth: 180,
        //   value: "orgName",
        // },
        // {
        //   label: "科室",
        //   minWidth: 180,
        //   value: "deptName",
        // },
      ],
      tableData: [],
      cacheForm: {},
      title: "",
      formData: [
        {
          type: "input",
          label: "姓名",
          placeholder: "请输入姓名",
          spanCount: 12,
          prop: "name",
          rules: [{ required: true, message: "请输入姓名" }],
        },
        {
          type: "select",
          label: "性别",
          spanCount: 12,
          prop: "sex",
          optsFormatter: () => {
            return this.dictMap && this.dictMap["d-sex"]
          },
        },
        {
          type: "input",
          placeholder: "请输入身份证",
          label: "身份证",
          spanCount: 12,
          prop: "idCard",
        },
        {
          type: "input",
          placeholder: "请输入手机",
          label: "手机",
          spanCount: 12,
          prop: "phone",
        },
        {
          type: "select",
          label: "机构",
          spanCount: 12,
          prop: "orgId",
          opts: orgList,
          rules: [{ required: true, message: "请选择机构" }],
          func: this.orgChange,
        },
        {
          type: "select",
          label: "科室",
          spanCount: 12,
          rules: [{ required: true, message: "请选择科室" }],
          prop: "deptId",
          opts: [],
        },
        {
          type: "input",
          placeholder: "请输入邮箱",
          label: "邮箱",
          spanCount: 12,
          prop: "email",
          rules: [
            { required: true, message: "请输入邮箱" },
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"],
            },
          ],
        },
        {
          type: "input",
          label: "登录账号名",
          placeholder: "请输入账号名",
          spanCount: 12,
          prop: "userName",
          disabled: false,
          rules: [{ required: true, message: "请输入账号名" }],
        },
        {
          type: "input",
          label: "密码",
          placeholder: "请输入密码",
          spanCount: 12,
          inputType: "password",
          prop: "passwd",
          hidden: false,
          rules: [
            { required: true, message: "请输入密码" },
            // {
            //   pattern: /^[0-9a-zA-Z_]{6,18}$/,
            //   message: "用户密码为6~18位数字、字母、下划线组合",
            // },
          ],
        },
        {
          type: "input",
          label: "确认密码",
          placeholder: "请再一次输入密码",
          prop: "confirmPw",
          spanCount: 12,
          inputType: "password",
          hidden: false,
          rules: [
            { required: true, message: "请再一次输入密码" },
            // {
            //   pattern: /^[0-9a-zA-Z_]{6,18}$/,
            //   message: "用户密码为6~18位数字、字母、下划线组合",
            // },
            { validator: validatePass, trigger: "blur" },
          ],
        },
      ],
      formEdit: {},
      formDataRole: [
        {
          type: "select",
          label: "角色",
          prop: "roleList",
          opts: roleList,
          rules: [{ required: true, message: "请选择角色", trigger: "change" }],
          multiple: true,
        },
      ],
      roleList: roleList,
      consortiaList: [],
      consortiaDataRole: [
        {
          type: "remote",
          label: "医联体",
          placeholder: "请输入医联体",
          prop: "consortiaList",
          opts: [],
          multiple: true,
          remoteFunc: this.searchConsortia,
          rules: [
            { required: true, message: "请选择医联体", trigger: "change" },
          ],
          func: this.valueChange,
          multiple: true,
        },
      ],
      originalList: [],
    }
  },
  computed: {
    ...mapGetters({
      roles: "user/roles",
      userInfo: "user/userInfo",
    }),
    isAdmin() {
      return this.roles.find((_) => _.roleCode === "admin")
    },
  },
  created() {
    this.handleFormSearch()
    this.loadMore()
  },
  methods: {
    valueChange(val) {
      console.log(val)
      if (val.includes("all")) {
        // this.unionIds = this.consortiaList.map((e) => e.id)
        console.log(this.consortiaDataRole[0].opts)
      }
    },
    // 修改启用状态
    // 启用状态
    openChage(data, index) {
      console.log(data, index)
      let params = {
        id: data.id,
        status: data.status ? 1 : 0,
      }
      baseEnable(params).then((res) => {
        if (res.code == 1) {
          // this.$message.success("保存成功")
          // this.handleSearch()
        }
      })
    },
    loadMore(current = 1) {
      let params = {
        current: current,
        unionName: this.searchQuery ? this.searchQuery : undefined,
        size: 10000,
      }
      medicalunionList(params).then((res) => {
        if (res.code === 1) {
          const d = res.data.records || []
          if (d.length > 0) {
            this.current = res.data.current - 0
            d.forEach((item) => {
              this.consortiaList.push({
                label: item.unionName,
                value: item.id,
              })
            })
            this.consortiaDataRole[0].opts = [...this.consortiaList]
          }
        }
      })
    },
    searchConsortia(query) {
      if (query !== "") {
        // this.loading = true
        this.searchQuery = query
        console.log(query)
        this.consortiaList = []
        this.consortiaDataRole[0].opts = []
        this.loadMore()
        // this.consortiaList = []
      } else {
        this.options = []
      }
    },
    // 授权医联体
    handleConsortiaConfirm(unionIds) {
      let unionIdList = unionIds.consortiaList
      if (unionIds.consortiaList.includes("all")) {
        unionIdList = this.consortiaDataRole[0].opts.map((e) => e.value)
      }
      const data = {
        userId: this.rowId,
        unionIds: unionIdList,
      }
      baseUnion(data)
        .then((res) => {
          if (res.code === 1) {
            this.$message.success("授权成功")
            this.handleSearch()
            this.$refs.consortiaRole.close()
          } else {
            this.$refs.consortiaRole.loading = false
          }
        })
        .catch(() => {
          this.$refs.consortiaRole.loading = false
        })
    },
    orgChange(orgId) {
      const list = []
      this.$refs.dialog.initFields({ deptId: "" })
      if (!orgId) {
        this.formData[5].opts = list
        return
      }
      getDepartPage({ current: 1, size: 100, orgId }).then((res) => {
        if (res.code === 1) {
          const d = res.data
          d.records.forEach((item) => {
            list.push({
              label: item.deptName,
              value: item.id,
            })
          })
          this.formData[5].opts = list
        }
      })
    },
    handleReset(row) {
      this.$confirm(`【${row.name}】是否重置密码? 重置密码为:123456`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          resetPassword(row.id).then((res) => {
            if (res.code === 1) {
              this.$message({
                type: "success",
                message: "重置密码成功!",
              })
              if (this.userInfo.id === row.id) {
                this.$store.dispatch("user/logout").then(() => {
                  this.$message({
                    type: "warning",
                    message: "请重新登录!",
                  })
                  this.$router.push(`/login`)
                })
              }
            }
          })
        })
        .catch(() => {})
    },
    handleRole({ id }) {
      this.rowId = id
      this.$refs.role.open()

      getUserInfo({ userId: id }).then((res) => {
        if (res.code === 1) {
          const modifyList = []
          const originalList = []

          res.data.roleList.map((item) => {
            if (item.roleCode === "admin" && !this.isAdmin) {
              originalList.push(item.id)
            } else {
              modifyList.push(item.id)
            }
          })

          this.originalList = originalList
          this.$refs.role.initFields({
            roleList: modifyList,
          })
        }
      })
    },
    // 医联体授权弹窗
    handleConsortia({ id }) {
      this.rowId = id
      this.$refs.consortiaRole.open()
      getUserInfo({ userId: id }).then((res) => {
        if (res.code === 1) {
          const consortiaList = []

          res.data.unionList.map((item) => {
            consortiaList.push(item.id)
          })
          if (consortiaList.length == this.consortiaDataRole[0].opts.length) {
            this.consortiaList = ["all"]
          } else {
            this.consortiaList = consortiaList
          }
          this.$refs.consortiaRole.initFields({
            consortiaList: this.consortiaList,
          })
        }
      })
    },
    handleRoleConfirm(form) {
      const data = {
        roleList: this.originalList.concat(form.roleList).map((_) => {
          return {
            id: _,
          }
        }),
        user: {
          id: this.rowId,
        },
      }
      setUserRole(data).then((res) => {
        if (res.code === 1) {
          this.$message.success(res.msg)
          this.handleSearch()
          this.$refs.role.close()
        }
      })
    },
    handleAdd({
      id,
      name,
      sex,
      idCard,
      phone,
      email,
      userName,
      orgId,
      deptId,
    }) {
      this.title = id ? "编辑用户" : "新增用户"
      this.formData[7].disabled = this.formData[8].hidden = this.formData[9].hidden = id
        ? true
        : false
      this.formEdit = id
        ? {
            id,
            name,
            sex: sex ? String(sex) : "",
            idCard,
            phone,
            email,
            userName,
            orgId,
            deptId,
          }
        : {}
      this.orgChange(orgId)
      this.$refs.dialog.open()
    },
    handleConfirm(form) {
      const data = Object.assign({}, form)
      data.deptName = this.$handle.formatDicList(
        this.formData[5].opts,
        form.deptId
      )
      data.orgName = this.$handle.formatDicList(
        this.formData[4].opts,
        form.orgId
      )
      const msg = data.id ? "编辑成功" : "新增成功"
      addUser(data).then((res) => {
        if (res.code === 1) {
          this.$message.success(msg)
          this.handleSearch()
          this.$refs.dialog.close()
        }
      })
    },
    handleDel(row) {
      this.$confirm(`是否删除【${row.name}】?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUser(row.id).then((res) => {
            if (res.code === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              })
              if (this.pageIndex > 1 && this.tableData.length === 1) {
                this.pageIndex--
              }
              this.handleSearch()
            }
          })
        })
        .catch(() => {})
    },

    // 查询
    handleFormSearch(form) {
      this.pageIndex = 1
      this.handleSearch(form)
    },
    handleSearch(form) {
      this.cacheForm = Object.assign(this.cacheForm, form)
      this.listLoading = true
      const params = Object.assign({}, this.cacheForm)
      for (let key in params) {
        if (params[key] === "") {
          delete params[key]
        }
      }
      params.current = this.pageIndex
      params.size = this.pageSize
      getUserPage(params).then((res) => {
        this.listLoading = false
        if (res.code === 1) {
          const d = res.data
          this.tableData = d.records || []
          this.total = Number(d.total)
        }
      })
    },
    handleView(row) {
      this.$router.push(`detail?id=${row.id}`)
    },
  },
}
</script>
