import { getUserInfo } from '@/api/oauth2/user'
import common from '@/utils/common'

export default {
  namespaced: true,
  state: {
    // 用户信息
    info: {},
    // 帐号
    account: '',
    // 切换的账号
    switchAccount: '',
    // 是否开启注册
    regOpen: false
  },
  actions: {
    /**
     * @description 设置用户数据
     * @param {Object} context
     * @param {*} info info
     */
    set({ state, dispatch }, info) {
      return new Promise(async resolve => {
        // store 赋值
        state.info = info
        // 持久化
        await dispatch(
          'ibps/db/set',
          {
            dbName: 'sys',
            path: 'user.info',
            value: info,
            user: true
          },
          { root: true }
        )
        // end
        resolve()
      })
    },
    /**
     * @description 从数据库取用户数据
     * @param {Object} state vuex state
     */
    get({ state, dispatch }) {
      return new Promise(async resolve => {
        // store 赋值
        state.info = await dispatch(
          'ibps/db/get',
          {
            dbName: 'sys',
            path: 'user.info',
            defaultValue: {},
            user: true
          },
          { root: true }
        )
        // end
        resolve()
      })
    },
    /**
     * @description 从数据库取用户数据
     * @param {Object} context
     */
    load({ state, dispatch }) {
      return new Promise(async(resolve, reject) => {
        await dispatch('getAccount')
        getUserInfo(state.account)
          .then(async response => {
            if (!response) {
              reject(response)
            }
            const info = response.data
            // 设置当前
            await dispatch('set', info)
            let level = {}
            if (info.positions && info.positions.length) {
              // 当存在第二级为空时，说明具备最高级权限
              const hasFirst = info.positions.some(
                obj => obj.path.split('.')[1] === ''
              )
              level = {
                first: [
                  ...new Set(info.positions.map(obj => obj.path.split('.')[0]))
                ].join(','),
                second: hasFirst
                  ? ''
                  : [
                    ...new Set(
                      info.positions.map(obj => obj.path.split('.')[1])
                    )
                  ].join(',')
              }
              await dispatch('ibps/param/setLevel', level, {
                root: true
              })
            }
            // 获取所有用户信息
            await dispatch('getUserList', level)
            // 获取所有部门信息
            await dispatch('getDeptList', level)
            // // 获取当前子系统
            // await dispatch('ibps/system/loadSystem', null, {
            //   root: true
            // })
            resolve(info)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    /**
     * 获取用户名
     * @param {*} param0
     */
    getAccount({ state, dispatch }) {
      return new Promise(async resolve => {
        // store 赋值
        state.account = await dispatch(
          'ibps/db/get',
          {
            dbName: 'sys',
            path: 'account',
            defaultValue: '',
            user: true
          },
          { root: true }
        )
        // end
        resolve()
      })
    },
    setAccount({ state, dispatch }, account) {
      return new Promise(async resolve => {
        // store 赋值
        state.account = account
        // 持久化
        await dispatch(
          'ibps/db/set',
          {
            dbName: 'sys',
            path: 'account',
            value: account,
            user: true
          },
          { root: true }
        )
        // end
        resolve()
      })
    },
    /**
     * 获取所有系统用户账号
     */
    getUserList({ state, dispatch }, { first, second }) {
      const params = second
        ? `'%${second}%' or entity.id_ = '${first}'`
        : first
          ? `'%${first}%'`
          : '%%'
      const sql = `select users.id_ as userId, users.name_ as userName, ifnull(users.mobile_, '') as phone, ifnull(group_concat(distinct positions.id_ order by positions.id_ separator ','), '') as positionId, ifnull(group_concat(distinct positions.name_ order by positions.id_ separator ','), '') as positions, ifnull(group_concat(distinct roles.id_ order by roles.role_note_ asc separator ','), '') as roleId, ifnull(group_concat(distinct roles.name_ order by roles.role_note_ asc separator ','), '') as roles, (select ifnull(people.qian_zi_tu_wen_, '') from t_ryjbqk as people where people.parent_id_ = users.id_) as signatureId, (select ifnull(files.file_name_, '') from ibps_file_attachment as files where files.id_ = signatureId) as signatureName from ibps_party_employee as users left join (select ur.user_id_, r.role_note_, group_concat(distinct r.id_ order by r.id_ separator ',') as id_, group_concat(distinct r.name_ order by r.id_ separator ',') as name_ from ibps_party_user_role as ur join ibps_party_role as r on ur.role_id_ = r.id_ group by ur.user_id_) as roles on users.id_ = roles.user_id_ left join ibps_party_entity as positions on find_in_set(positions.id_, users.positions_) where exists (select 1 from ibps_party_entity as entity where find_in_set(entity.id_, users.positions_) and (entity.path_ like ${params})) group by users.id_`
      common
        .request('sql', sql)
        .then(res => {
          const { data = [] } = res.variables || {}
          dispatch('ibps/param/setUserList', data, {
            root: true
          })
        })
        .catch(error => {
          console.log(error)
          alert('获取所有用户信息失败！')
        })
    },
    /**
     * 获取所有系统部门信息
     */
    getDeptList({ state, dispatch }, { first, second }) {
      const params = second
        ? ` and (pe.path_ like '%${second}%' or pe.id_ = '${first}')`
        : first
          ? ` and pe.path_ like '%${first}%'`
          : ''
      // const sql = `select id_ as positionId, name_ as positionName, path_ as path, depth_ as depth, sn_ as sn from ibps_party_entity where party_type_ = 'position'${params} order by depth_ asc, sn_ asc`
      const sql = `select pe.id_ as positionId, pe.name_ as positionName, pe.path_ as path, pe.depth_ as depth, pe.sn_ as sn, ifnull(r.name_, '') as manager, ifnull(r.id_, '') as managerId from ibps_party_entity as pe left join (select em.id_, em.positions_, em.name_ from ibps_party_employee as em left join ibps_party_user_role as ur on em.id_ = ur.user_id_ left join ibps_party_role as pr on pr.id_ = ur.role_id_ where role_alias_ in ('zhsfzr', 'syszr', 'zhglzzc')) as r on find_in_set(pe.id_, r.positions_) > 0 where pe.party_type_ = 'position'${params} group by pe.id_ order by pe.depth_ asc, pe.sn_ asc,pe.id_ asc`
      common
        .request('sql', sql)
        .then(res => {
          const { data = [] } = res.variables || {}
          dispatch('ibps/param/setDeptList', data, {
            root: true
          })
        })
        .catch(error => {
          console.log(error)
          alert('获取所有部门信息失败！')
        })
    }
  }
}
