<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"
      :list-loading="listLoading"
      :current-page="pageIndex"
      :total-count="total"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      @pageSizeChange="handleSizeChange"
      @currentPageChange="handleCurrentChange"
    />
    <dialog-form
      width="750px"
      :close-modal="false"
      ref="dialog"
      :title="title"
      :form-edit="formEdit"
      :form-data="formData"
      @handleConfirm="handleConfirm"
    ></dialog-form>
    <dialog-form
      width="450px"
      ref="role"
      title="角色授权"
      :form-data="formDataRole"
      @handleConfirm="handleRoleConfirm"
    ></dialog-form>
  </div>
</template>

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

import { mapGetters } from "vuex"
export default {
  name: "user",
  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,
      isAdd: false,
      id: null,
      // 查询列表
      searchList: [
        {
          label: "用户姓名",
          type: "input",
          prop: "name",
          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: "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",
        },
        {
          label: "登录账户名",
          minWidth: 150,
          value: "userName",
        },

        {
          label: "邮箱",
          minWidth: 180,
          value: "email",
        },
        // {
        //   label: "状态",
        //   value: "status",
        //   width: 100,
        //   formatter(row) {
        //     return row.status === 1 ? '启用' : '禁用'
        //   }
        // },
        {
          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.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",
                },
              ],
            },
          ],
        },
      ],
      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,
          func: this.orgChange,
        },
        {
          type: "select",
          label: "科室",
          spanCount: 12,
          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,
        },
      ],
      originalList: [],
    }
  },
  mixins: [paginationMixin],
  computed: {
    ...mapGetters({
      roles: "user/roles",
      userInfo: "user/userInfo",
    }),
    isAdmin() {
      return this.roles.find((_) => _.roleCode === "admin")
    },
  },
  methods: {
    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,
          })
        }
      })
    },
    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.$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}`)
    },
  },
  created() {
    this.handleFormSearch()
  },
}
</script>
