<template>
  <basic-container class="mt-10">
    <avue-crud
      :option="option"
      :data="data"
      ref="crud"
      v-model="form"
      v-model:page="page"
      :before-open="beforeOpen"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu="{ row }">
        <el-button icon="Open" type="primary" text @click="Enable(row)">
          {{ row.clientId.indexOf('project_web') === -1 ? '启用' : '停用' }}
        </el-button>
        <el-button icon="Refresh" type="primary" text @click="restPwd(row)">
          重置密码
        </el-button>
      </template>
      <template #status="{ row }">
        <el-tag
          :type="row.clientId.indexOf('project_web') === -1 ? 'danger' : ''"
        >
          {{ row.clientId.indexOf('project_web') === -1 ? '停用' : '启用' }}
        </el-tag>
      </template>
      <template #menu-left>
        <el-button type="primary" plain @click="showQrCode = true"
          >通过微信邀请
        </el-button>
      </template>
    </avue-crud>
    <el-dialog
      v-model="showEdit"
      append-to-body
      center
      title="用户信息设置"
      width="50%"
      @close="closeCode"
    >
      <div>
        <el-form
          ref="form"
          :model="userInfoForm"
          :rules="rules"
          class="mt-20"
          label-width="100px"
        >
          <div class="flex flex-center">
            <el-form-item class="full-width" label="登录账号" prop="name">
              <el-input
                v-model="userInfoForm.account"
                clearable
                placeholder="输入用户名称"
              />
            </el-form-item>
            <el-form-item
              class="full-width mr-20"
              label="真实姓名"
              :rules="rules"
              prop="realName"
            >
              <el-input
                v-model="userInfoForm.realName"
                clearable
                placeholder="输入真实姓名"
              >
              </el-input>
            </el-form-item>
          </div>
          <div class="flex flex-center">
            <el-form-item label="手机号码" class="full-width" prop="phone">
              <el-input
                v-model="userInfoForm.phone"
                clearable
                placeholder="输入手机号码"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              class="full-width mr-20"
              label="登陆密码"
              prop="password"
            >
              <el-input
                v-model="userInfoForm.password"
                :disabled="form.type !== 'add'"
                clearable
                :placeholder="form.type !== 'add' ? '******' : '输入登陆密码'"
              >
              </el-input>
            </el-form-item>
          </div>
          <div class="flex flex-align-center">
            <span class="ml-20 bold">部门选择</span>
            <el-form-item class="flex">
              <el-select
                class="mt-20"
                v-model="userInfoForm.deptId"
                style="width: 250px; margin-left: -75px"
                placeholder="选择用户所属部门"
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.id"
                  :label="item.deptName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="flex flex-col mt-10">
            <span class="ml-20 bold">职务选择</span>
            <el-form-item class="flex flex-wrap">
              <div class="flex flex-center padding pointer">
                <el-radio-group size="large" v-model="userInfoForm.roleIds">
                  <el-radio v-for="item in jobs" :key="item.id" :label="item.id"
                    >{{ item.roleName }}
                  </el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </div>
          <div class="flex flex-col" style="margin-top: -10px">
            <div class="flex flex-align-center">
              <span class="bold ml-20">管理股室</span>
              <el-checkbox
                size="large"
                style="margin-left: 33px"
                v-model="checkAll"
                @change="choseAll"
                >全选
              </el-checkbox>
            </div>
            <el-form-item class="flex flex-wrap">
              <div class="flex flex-center padding pointer">
                <el-checkbox
                  v-model="item.checked"
                  :label="item.id"
                  size="large"
                  v-for="item in deptList"
                  :key="item.id"
                  @change="deptChose($event, item)"
                >
                  {{ item.deptName }}
                </el-checkbox>
              </div>
            </el-form-item>
          </div>
          <div class="flex flex-center">
            <base-button
              title="取消"
              type="0"
              icon="Close"
              @click="showEdit = false"
            />
            <base-button
              class="ml-10"
              title="保存"
              icon="Check"
              @click="roleSave"
            />
          </div>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog
      v-model="showQrCode"
      title="邀请二维码"
      width="500"
      @close="closeCode"
    >
      <div>
        <div class="full-width flex flex-center">
          <span class="mr-20">用户所属部门</span>
          <el-select
            v-model="userInfoForm.deptId"
            placeholder="选择用户所属部门"
            @change="qrCodeSelect"
          >
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.deptName"
              :value="item.id"
            />
          </el-select>
        </div>
        <div v-if="qrCodeText.length > 0" class="flex flex-center flex-col">
          <vue-qr
            class="mt-10"
            :currentLevel="1"
            :logoCornerRadius="4"
            :logoScale="0.25"
            :logoSrc="logoSrc"
            :text="qrCodeText"
            size="220"
          />
          <span>- 复制二维码图片，通过微信发送邀请 -</span>
        </div>
        <el-empty v-else description="暂无数据" />
      </div>
    </el-dialog>
  </basic-container>
</template>

<route>
{
name: '用户管理',
meta: { 'back':true,'showMsg' : "如果手机号为用户微信绑定的手机号时，微信小程序将自动登录，并同步信息！"}
}
</route>

<script>
import BasicContainer from '@/components/basic-container/main.vue'
import { useStore } from '@/store/user.js'
import baseButton from '@/components/base-button.vue'
import VueQr from 'vue-qr/src/packages/vue-qr.vue'

export default {
  name: 'manage',
  components: {
    BasicContainer,
    baseButton,
    VueQr
  },
  setup() {
    const user = useStore()
    return { user }
  },
  data() {
    return {
      showAdd: false,
      showQrCode: false,
      showEdit: false,
      qrCodeText: '',
      sessionId: '',
      logoSrc: new URL('@/assets/img/logo.png', import.meta.url).href,
      form: {},
      page: {
        curren: 1,
        size: 10
      },
      data: [],
      option: {
        align: 'center',
        menuAlign: 'center',
        menuWidth: 240,
        size: 'mini',
        addBtn: true,
        addBtnText: '添加用户',
        viewBtn: false,
        delBtn: false,
        refreshBtn: true,
        columnBtn: false,
        labelWidth: 140,
        border: true,
        column: [
          {
            label: '登录账号',
            prop: 'account',
            display: false,
            width: 170
          },
          {
            label: '真实姓名',
            prop: 'realName'
          },
          {
            label: '手机号码',
            prop: 'phone'
          },
          {
            label: '职务',
            prop: 'roleName'
          },
          {
            label: '状态',
            prop: 'status'
          }
        ]
      },
      jobs: [],
      deptList: [],
      checkAll: false,
      userInfoForm: {
        name: '',
        realName: '',
        phone: '',
        password: '',
        roleIds: '',
        deptIds: [],
        deptId: ''
      },
      rules: {
        name: {
          required: true,
          message: '用户名称不能为空！',
          trigger: 'blur'
        },
        realName: {
          required: true,
          message: '真实姓名不能为空！',
          trigger: 'blur'
        },
        phone: [
          {
            required: true,
            message: '手机号码不能为空！',
            trigger: 'blur'
          },
          {
            min: 11,
            max: 11,
            message: '请填写正确的手机号码！',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getOrg()
    this.getJobList()
  },
  methods: {
    onLoad() {
      this.loading = true
      this.page.current = this.page.currentPage
      this.page.size = this.page.pageSize
      const data = { deptId: this.user.info.deptId }
      console.log(this.page)
      this.$api.role
        .roleList(Object.assign(this.page, data))
        .then(res => {
          this.loading = false
          if (res.code === 200) {
            this.data = res.data.records
            this.page.total = res.data.total
          } else {
            this.$message.error(res.msg)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    Enable(row) {
      this.$confirm('确定启用/停用该用户?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.role
          .roleStart({
            userId: row.id,
            status: row.clientId.indexOf('project_web') > -1 ? 0 : 1
          })
          .then(res => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.onLoad()
            } else {
              this.$message.error(res.msg)
            }
          })
      })
    },
    beforeOpen(done, type) {
      this.form.type = type
      if (type === 'edit') {
        this.rowEdit()
      } else if (type === 'add') {
        this.userInfoForm = {
          account: '',
          realName: '',
          phone: '',
          password: '',
          roleIds: '',
          deptIds: [],
          deptId: ''
        }
        this.deptList.map(e => (e.checked = false))
        this.showEdit = true
      } else {
        done()
      }
    },
    rowEdit() {
      if (this.form.clientId.indexOf('project_web') === -1) {
        this.$message.error('该账号已经停用，无需进行编辑！')
        return
      }
      this.userInfoForm.account = this.form.account
      this.userInfoForm.realName = this.form.realName
      this.userInfoForm.phone = this.form.phone
      this.userInfoForm.password = this.form.password
      this.userInfoForm.deptId = this.form.deptId
      this.jobs.find(e => {
        const temp = this.form.roleId.split(',').find(sub => sub === e.id)
        if (temp) {
          this.userInfoForm.roleIds = temp
        }
        return temp
      })
      this.$api.role.managerList({ userId: this.form.id }).then(res => {
        if (res.code === 200) {
          res.data.forEach(ele => {
            const tmp = this.deptList.findIndex(sub => sub.id === ele.deptId)
            if (tmp > -1) {
              this.deptList[tmp].checked = true
            }
            this.userInfoForm.deptIds = this.deptList.map(e => e.id)
          })
          if (
            this.deptList.filter(e => e.checked).length === this.deptList.length
          ) {
            this.checkAll = true
          } else {
            this.checkAll = false
          }
          this.showEdit = true
        }
      })
    },
    currentChange(currentPage) {
      this.page.current = currentPage
    },
    sizeChange(pageSize) {
      this.page.size = pageSize
    },
    refreshChange() {
      this.onLoad()
    },
    getJobList() {
      this.$api.role.jobList({ roleAlias: 'post' }).then(res => {
        if (res.code === 200) {
          this.jobs = res.data
        }
      })
    },
    getOrg() {
      this.$api.role.deptList().then(res => {
        if (res.code === 200) {
          this.showOrg = true
          this.deptList = res.data.map(e => {
            e.checked = false
            return e
          })
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    choseAll(res) {
      this.deptList.map(e => {
        e.checked = res
        return e
      })
      if (res) {
        this.userInfoForm.deptIds = this.deptList.map(e => e.id)
      } else {
        this.userInfoForm.deptIds = []
      }
      console.log(this.userInfoForm.deptIds)
    },
    deptChose(res, item) {
      const tmp = this.deptList.find(ele => ele.id === item.id)
      if (tmp) {
        if (tmp.checked) {
          if (this.userInfoForm.deptIds.findIndex(e => e === tmp.id) === -1) {
            this.userInfoForm.deptIds.push(tmp.id)
          }
        } else {
          this.userInfoForm.deptIds = this.userInfoForm.deptIds.filter(
            ele => ele !== tmp.id
          )
        }
      }
      const count = this.deptList.filter(e => e.checked).length
      this.checkAll = count === this.deptList.length
    },
    roleSave() {
      if (this.deptList.filter(e => e.checked).length === 0) {
        this.$message.error('请选择管理股室')
        return
      }
      if (this.userInfoForm.roleIds.length === 0) {
        this.$message.error('请选择职务')
        return
      }
      const data = this.userInfoForm
      if (data.deptIds.length > 0) {
        data.deptIds = data.deptIds.join(',')
      } else {
        data.deptIds = this.form.deptId
      }
      data.isUpdate = false
      if (this.form.id) {
        data.userId = this.form.id
        this.$api.role.roleUpdate(data).then(res => {
          if (res.code === 200) {
            this.showEdit = false
            this.$message.success(res.msg)
            this.onLoad()
          } else {
            this.$message.error(res.msg)
          }
        })
      } else {
        this.$api.role.roleSave(data).then(res => {
          if (res.code === 200) {
            this.showEdit = false
            this.$message.success(res.msg)
            this.onLoad()
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    restPwd(row) {
      console.log(row)
      this.$prompt('', '更改 (' + row.name + ') 的密码', {
        inputPattern: /\w{6,16}/,
        inputErrorMessage: '密码长度在 6 到 16 个字符'
      }).then(({ value }) => {
        if (value.length === 0) {
          return
        }
        this.$api.role
          .restPwde({ userId: row.id, password: value })
          .then(res => {
            if (res.code === 200) {
              console.log(res)
            }
          })
      })
    },
    qrCodeSelect(deptId) {
      this.$api.role.invitation({ deptId, type: 4 }).then(res => {
        if (res.code === 200) {
          this.qrCodeText =
            'https://dev.wutongresearch.club/apply?id=' +
            res.data.qrcodeId +
            '&deptId=' +
            deptId +
            '&roleName=股室'
        }
      })
    },
    closeCode() {
      this.userInfoForm = {
        name: '',
        realName: '',
        phone: '',
        password: '',
        roleIds: '',
        deptIds: [],
        deptId: ''
      }
      this.deptList.map(e => (e.checked = false))
      this.qrCodeText = ''
    }
  }
}
</script>

<style scoped></style>
