<script setup name="userManage">
import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
import {
  userList,
  userStatusSet,
  replaceLogin,
  userEdit,
  userDetail,
  controlledRoles
} from '@/http/apis/systemManage/userManage'
import ElTree from '@/components/elTree/index.vue'
import moment from 'moment'
import store from '@/store'
import { storeToRefs } from 'pinia'
import { getIsShowRegionTree, getTreeParams } from '@/utils/getIsShowRegionTree'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance(),
  userInfo = storeToRefs(store.userStore).userInfo || {},
  roleList = storeToRefs(store.userStore).roleList || {},
  // detailRoleList = ref(),
  searchForm = reactive({
    userRoleList: undefined,
    name: undefined,
    phoneNo: undefined,
    orgName: undefined
  }),
  tableListRef = ref(),
  total = ref(0),
  column = reactive([
    {
      label: '序号',
      type: 'index',
      width: '80'
    },
    {
      label: '姓名',
      key: 'name',
      prop: 'name'
    },
    {
      label: '手机号码',
      key: 'phoneNo',
      prop: 'phoneNo',
      width: '150'
    },
    {
      label: '所属单位（主职）',
      key: 'orgName',
      prop: 'orgName',
      showOverflowTooltip: true,
      width: 250
    },
    {
      label: '所属区域',
      key: 'regionName',
      prop: 'regionName',
      width: '150'
    },
    {
      label: '用户角色',
      key: 'userRoleList',
      prop: 'userRoleList',
      width: 200
    },
    {
      label: '状态',
      slot: 'isEnable',
      width: '100'
    },
    {
      label: '更新时间',
      key: 'updateTime',
      prop: 'updateTime',
      width: '250'
    },
    {
      label: '操作',
      slot: 'action',
      width: '200',
      fixed: 'right'
    }
  ]),
  data = ref([]),
  getTableData = async (pageParams = tableListRef.value.pageParams) => {
    const res = await userList({
      ...pageParams,
      ...searchForm,
      userRoleList: [{ id: searchForm.userRoleList }]
      // regionId: import.meta.env.MODE === 'production' ? treeInfo.value && treeInfo.value.region || undefined : '330102'
    })
    const dataClone = res.data.records
    dataClone.forEach(element => {
      const nameArr = []
      element.userRoleList.forEach(item => {
        nameArr.push(item.name)
      })
      element.userRoleList = nameArr
    })
    data.value = dataClone
    total.value = res.data.total
  },
  search = () => {
    getTableData()
  },
  reset = () => {
    searchForm.userRoleList = undefined
    searchForm.name = undefined
    searchForm.phoneNo = undefined
    searchForm.orgName = undefined
    tableListRef.value.pageParams.pageNumber = 1
    tableListRef.value.pageParams.pageSize = 10
    getTableData()
  },
  visible = ref(false),
  editName = ref(),
  form = ref({
  }),
  edit = async (row) => {
    getRoles()
    visible.value = true
    editName.value = row.name
    const roleRes = await userDetail({ employeeCode: row.employeeCode, userId: row.userId })
    const roles = []
    roleRes.data.userRoleInfoList.forEach(element => {
      roles.push(element.id)
    })
    form.value = {
      employeeCode: row.employeeCode,
      userRoleInfoList: roles,
      phoneNo: row.phoneNo,
      status: row.status !== 'DISABLE',
      userId: row.userId
    }
  },
  rules = {
    phoneNo: [
      {
        required: true,
        pattern: /^1[3456789]\d{9}$/,
        message: '手机号码格式不正确',
        trigger: 'blur'
      }
    ],
    userRoleInfoList: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
  },
  formRef = ref(),
  submit = async (formEl) => {
    if (!formEl) {
      return
    }
    await formEl.validate(async (valid) => {
      if (valid) {
        const postData = { ...form.value }
        const postDataClone = JSON.parse(JSON.stringify(postData))
        postDataClone.status ? postDataClone.status = 'ENABLE' : postDataClone.status = 'DISABLE'
        postDataClone.userRoleInfoList = []
        postData.userRoleInfoList.forEach(element => {
          postDataClone.userRoleInfoList.push({ id: element })
        })
        await userEdit(postDataClone)
        proxy.$message.success('编辑成功！')
        visible.value = false
        getTableData()
      }
    })
  },
  enabled = (data) => {
    const text = data.status === 'DISABLE' ? '启用' : '禁用'
    proxy.$messageBox
      .confirm(`是否${text}该用户?`, '提示！', {
        type: 'warning'
      })
      .then(async () => {
        await userStatusSet({
          employeeCode: data.employeeCode,
          operation: data.status === 'DISABLE' ? 'ENABLE' : 'DISABLE',
          userId: data.userId
        })
        proxy.$message.success(`${text}成功！`)
        getTableData()
      })
  },
  router = useRouter(),
  replace = async (data) => {
    proxy.$messageBox
      .confirm(`确定要代登录${data.name}账号?`, '提示！', {
        type: 'warning'
      })
      .then(async () => {
        const formData = new URLSearchParams()
        formData.append('userId', data.userId)
        await replaceLogin(formData)
        proxy.$message.success('登录成功！')
        location.reload()
        router.push('/')
      })
  },
  getTree = (data) => {
    searchForm.regionId = data.regionLevel === 3 ? data.regionCode : undefined
    tableListRef.value.pageParams.pageNumber = 1
    getTableData()
  },
  // 是否单位管理员
  isManager = ref(false),
  handleCheckedChange = (v, name) => {
    if (name === '单位管理员') {
      isManager.value = v
    }
  },
  // 获取可控角色列表
  controlledRoleList = ref(),
  getRoles = async () => {
    const res = await controlledRoles()
    controlledRoleList.value = res.data
  }
onMounted(() => {
  store.userStore.setRoleStore()
  if (!getIsShowRegionTree(['SUPER_ADMIN', 'REGION_MANAGER'])) getTableData()
})
</script>

<template>
  <el-row>
    <el-col v-if="getIsShowRegionTree(['SUPER_ADMIN','REGION_MANAGER'])" style="padding-right: 16px" :span="4">
      <elTree :params="getTreeParams({'SUPER_ADMIN':false,'REGION_MANAGER':false})" @get-tree="getTree" />
    </el-col>
    <el-col :span="getIsShowRegionTree(['SUPER_ADMIN','REGION_MANAGER'])?20:24">
      <div>
        <el-card class="search mb-16">
          <el-form label-suffix=":" :model="searchForm" size="small">
            <el-row :gutter="16" class="mb-16">
              <el-col :span="8">
                <el-form-item label="用户姓名">
                  <el-input
                    v-model="searchForm.name"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="手机号码">
                  <el-input
                    v-model="searchForm.phoneNo"
                    maxlength="11"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用户角色">
                  <el-select
                    v-model="searchForm.userRoleList"
                    style="width: 100%"
                    clearable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item,index) in roleList"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="8">
                <el-form-item label="所在单位" maxlength="50">
                  <el-input v-model="searchForm.orgName" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item class="btn">
                  <el-button type="primary" @click="search">查询</el-button>
                  <el-button @click="reset">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card>
          <template #header>
            <div class="flex justify-between items-center">
              <span>用户列表</span>
              <!-- <el-button type="primary" icon="Plus"  @click="add">
              新增用户
            </el-button> -->
            </div>
          </template>
          <table-list
            ref="tableListRef"
            :column="column"
            :data="data"
            :total="total"
            @get-table-data="getTableData"
          >
            <template #isEnable="{ scope }">
              <div
                class="dot"
                :style="{
                  background: scope.row.status == 'DISABLE' ? '#FF3B30' : '#4ECB74',
                }"
              ></div>
              &nbsp;<span
                :style="{
                  color: scope.row.status == 'DISABLE' ? '#FF3B30' : '#4ECB74',
                }"
                >{{ scope.row.status == 'DISABLE' ? "禁用中" : "启用中" }}</span>
            </template>
            <template #updated="{scope}">
              {{ moment(scope.row.updated).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template #action="{ scope }">
              <a @click="edit(scope.row)">编辑</a>
              <a v-if="scope.row.status === 'ENABLE'&&userInfo.userRoleInfoList?.filter(i=>i.code==='SUPER_ADMIN')?.length" @click="replace(scope.row)">代登录</a>
              <a @click="enabled(scope.row)">{{ scope.row.status === 'DISABLE' ?'启用':'禁用' }}</a>
            </template>
          </table-list>
        </el-card>
        <el-dialog
          :model-value="visible"
          :title="'编辑' + ' - ' + editName"
          width="600px"
          @close="visible = false"
        >
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="90px"
            label-suffix=":"
          >
            <el-form-item label="手机号码" prop="phoneNo">
              <el-input
                v-model="form.phoneNo"
                placeholder="请输入"
                maxlength="11"
              />
            </el-form-item>
            <el-form-item label="用户角色" prop="userRoleInfoList">
              <el-checkbox-group v-model="form.userRoleInfoList">
                <el-checkbox
                  v-for="item in controlledRoleList"
                  :key="item.id"
                  :label="item.id"
                  @change="(value)=>handleCheckedChange(value,item.name)"
                >{{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="form.status"
                style="
                 --el-switch-on-color: #4ecb74;
                 --el-switch-off-color: #ff3b30;
                "
              />&nbsp;
              <span :style="{ color: form.status ? '#4ECB74' : '#FF3B30' }">{{
                form.status? "已启用" : "已禁用"
              }}</span>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button type="primary" @click="submit(formRef)">
              提交
            </el-button>
            <el-button @click="visible = false">
              关闭
            </el-button>
          </template>
        </el-dialog>
      </div>
    </el-col>
  </el-row>
</template>
<style lang="less" scoped>
</style>
