<template>
  <div v-loading="loading">
    <baseTitle :title="'用户信息录入'"></baseTitle>
    <fvForm :schema="schame" @getInstance="getInstance" :rules="rules"></fvForm>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" @click="handleSubmit">提交</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>
  </div>
</template>

<script setup lang="jsx">
import {ElLoading, ElMessageBox, ElNotification} from 'element-plus';
import {useTagsView} from '@/stores/tagsview.js'
import {useAuthStore} from '@/stores/userstore.js'
import {useCacheStore} from "@/stores/cache.js";
import {
  getDeptOpt,
  getSubCompOpt,
  getRolesOpt,
  getJobOpt,
  getUserDetail,
  operate,
  judgeIsSameRole
} from '@/api/user/user.js'

const tagsViewStore = useTagsView()
const authStore = useAuthStore()
const cacheStore = useCacheStore();
const route = useRoute()
const form = ref(null)
const currentRoleArray = ref([])
const loading = ref(false)
const localData = reactive({
  subCompanyIdOpt: [],
  departmentIdOpt: [],
  roleOpt: [],
  jobOpt: []
})
const openChangeRoleDialog = (selectRoleId, data) => {
  ElMessageBox.confirm(`${getRoleName(selectRoleId)} 角色存在对应人员：${data[selectRoleId][0].nickName}，您确定要替换为  ${form.value.getValues().nickName}?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {

  }).catch((action) => {
    if (action == 'cancel') {
      form.value.getValues().roleIds = form.value.getValues().roleIds.filter(roleItem => roleItem != selectRoleId);
    }
  })
}
const schame = computed(() => {
  let arr = [
    {
      label: '公司',
      prop: 'subCompanyId',
      component: 'el-tree-select',
      props: {
        placeholder: '请输入',
        clearable: true,
        filterable: true,
        checkStrictly: true,
        data: localData.subCompanyIdOpt,
        disabled: route.query.userType == 0 ? true : false
      },
      on: {
        change: async (val) => {
          const {data} = await getDeptOpt({subCompanyId: val})
          localData.departmentIdOpt = data
        }
      }
    },
    {
      label: '归属部门',
      prop: 'departmentId',
      component: 'el-tree-select',
      props: {
        placeholder: '请选择',
        clearable: true,
        data: localData.departmentIdOpt,
        filterable: true,
        checkStrictly: true,
        disabled: route.query.userType == 0 ? true : false
      }
    },
    {
      label: '用户账号',
      prop: 'userName',
      component: 'el-input',
      props: {
        placeholder: '请输入',
        disabled: route.query.userType == 0 ? true : false
      }
    },
    {
      label: '用户昵称',
      prop: 'nickName',
      component: 'el-input',
      props: {
        placeholder: '请输入',
        disabled: route.query.userType == 0 ? true : false
      }
    },
    {
      label: '用户密码',
      prop: 'password',
      component: 'el-input',
      props: {
        placeholder: '请输入',
        type: 'password',
      }
    },
    {
      label: '岗位',
      prop: 'jobId',
      component: 'el-tree-select',
      props: {
        placeholder: '请选择',
        filterable: true,
        checkStrictly: true,
        data: localData.jobOpt,
        disabled: route.query.userType == 0 ? true : false
      }
    },
    {
      label: '角色',
      prop: 'roleIds',
      component: 'el-tree-select',
      props: {
        placeholder: '请选择',
        multiple: true,
        data: localData.roleOpt
      },
      on: {
        change: async (val) => {
          const {code, data} = await judgeIsSameRole(form.value.getValues().userId)
          if (code === 1000) {
            // console.log('currentRoleArray.value', currentRoleArray.value)
            // console.log('data,val', data, val)
            let selectRoleLast = val[val?.length - 1]
            if (currentRoleArray.value.length !== 0) {//当前用户存在角色
              currentRoleArray.value?.forEach(currentItem => {
                console.log('currentItem', currentItem, data[currentItem], form.value.getValues().userId)
                //当前用户已经选择科创部对接人/财务对接人时移除角色不出现替换弹窗
                if (currentItem && data[currentItem] && data[currentItem].length > 0 && data[currentItem][0].userId == form.value.getValues().userId) {
                  console.log('已选择对接人')
                  //选择两个对接人
                  if (data[selectRoleLast]?.length > 0 && data[selectRoleLast][0].userId !== form.value.getValues().userId) {
                    console.log('选择两个对接人')
                    openChangeRoleDialog(selectRoleLast, data)
                  }
                } else {
                  //当前用户未选择对接人
                  if (data[selectRoleLast]?.length > 0) {
                    openChangeRoleDialog(selectRoleLast, data)
                  }
                }
              })
            } else {//当前用户未分配角色
              if (data[selectRoleLast]?.length > 0) {
                openChangeRoleDialog(selectRoleLast, data)
              }
            }
          }
        }
      }
    },
    {
      label: '性别',
      prop: 'sex',
      component: 'el-tree-select',
      props: {
        placeholder: '请选择',
        data: cacheStore.getDict('user_sex'),
        disabled: route.query.userType == 0 ? true : false
      }
    },
    {
      label: '帐号状态',
      prop: 'state',
      component: 'el-tree-select',
      props: {
        placeholder: '请选择',
        data: cacheStore.getDict('normal_disable'),
        disabled: route.query.userType == 0 ? true : false
      }
    },
    {
      label: '手机号码',
      prop: 'mobile',
      component: 'el-input',
      props: {
        placeholder: '请输入',
        disabled: route.query.userType == 0 ? true : false
      }
    },
    {
      label: '邮箱',
      prop: 'email',
      component: 'el-input',
      props: {
        placeholder: '请输入',
        disabled: route.query.userType == 0 ? true : false
      }
    },
  ]
  let editArr = []
  if (!route.query.isAdd) {
    arr.forEach(item => {
      if (item.prop != 'password') {
        editArr.push(item)
      }
    })
    return !authStore.roles.includes('superAdmin') ? editArr.slice(1) : editArr
  }
  return !authStore.roles.includes('superAdmin') ? arr.slice(1) : arr
})

const rules = reactive({
  userName: [{required: true, message: '请输入', trigger: 'change'}],
  nickName: [{required: true, message: '请输入', trigger: 'change'}],
  password: [{required: true, message: '请输入', trigger: 'change'}],
  departmentId: [{required: true, message: '请选择', trigger: 'change'}],
  subCompanyId: [{required: true, message: '请选择', trigger: 'change'}],
  jobId: [{required: true, message: '请选择', trigger: 'change'}],
  roleIds: [{required: true, message: '请选择', trigger: 'change'}],
  sex: [{required: true, message: '请选择', trigger: 'change'}],
  state: [{required: true, message: '请选择', trigger: 'change'}],
})
const getRoleName = (roleId) => {
  console.log('roleId', roleId, localData.roleOpt, localData.roleOpt.filter(item => item.value == roleId))
  return localData.roleOpt.filter(item => item.value == roleId)[0].label
}
const getInstance = (e) => {
  form.value = e
}

const init = async () => {
  const reqList = [
    getDeptOpt(),
    getSubCompOpt(),
    getRolesOpt(),
    getJobOpt()
  ]
  const resAll = await Promise.all(reqList)
  localData.departmentIdOpt = resAll[0].data
  localData.subCompanyIdOpt = resAll[1].data
  localData.roleOpt = resAll[2].data
  localData.jobOpt = resAll[3].data
}

const getInfo = async () => {
  if (!route.query.id) return
  // 获取详情数据
  const {data} = await getUserDetail(route.query.id)
  if (data.subCompanyId) {
    const res = await getDeptOpt({subCompanyId: data.subCompanyId})
    localData.departmentIdOpt = res.data
  }
  nextTick(() => {
    form.value.setValues(data)
    currentRoleArray.value = form.value.getValues().roleIds
  })

}

const handleSubmit = async () => {
  const loading = ElLoading.service({fullscreen: true})
  const {isValidate} = await form.value.validate()
  if (!isValidate) {
    loading.close()
    return Promise.reject()
  }
  const values = form.value.getValues()
  operate(values, route.query.userType).then(res => {
    ElNotification({
      title: route.query.isAdd ? '新增' : '编辑',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    loading.close()
    res.code === 1000 ? tagsViewStore.delViewAndGoView('/system/user') : null
  }).catch(() => {
    loading.close()
  }).finally(() => {
    loading.close()
  })
}

const handleBack = () => {
  history.back()
}

onMounted(async () => {
  loading.value = true
  await init()
  if (!route.query.isAdd) {
    await getInfo()
  }
  loading.value = false
})

</script>

<style lang="scss" scoped>

</style>
