import {
  ref,
  toRefs
} from 'vue';
import {
  getSysDictByCode
} from '@/api/sysDict' //引入封装数字字典接口
/**
 * 获取字典数据
 */
let list = []
export function getDict(...args) {
  const res = ref({});
  return (() => {
    args.forEach((d, index) => {
      res.value[d] = [];
      getSysDictByCode({
        dictCode: d
      }).then(result => {
        result.itemList.forEach(p => {
          p.label = p.zdmc
          p.value = p.dm
          p.id = p.dm
          p.elTagType = p.dictType
          if ( p.itemList && p.itemList.length > 0) {
            getChildren(p)
          }
          p.children = p.itemList
        })
        res.value[d] = result.itemList
      })
    })
    return toRefs(res.value);
  })()
}

export function getChildren(item) {
  item.label = item.zdmc
  item.value = item.dm
  item.id = item.dm
  if (item.itemList && item.itemList.length > 0) {
    item.itemList.forEach(v => {
      getChildren(v)
    })
  }
  item.children = item.itemList
}
/**
 * 设置级联选择器回显
 * @param {*} id 选中ID
 * @param {*} array 级联数据树
 * @param {*} childDeptList 子集变量
 */
export function setCascader(id, array, childDeptList = 'childDeptList', fun) {
  if (array) {
    array.forEach(item => {
      if (item.childDeptList && item.id != id) {
        setCascader(id, item.childDeptList, childDeptList, fun)
      } else if (item.childDeptList && item.id == id) {
        fun(item)
      } else if (!item.childDeptList && item.id == id) {
        fun(item)
      }
    })
  }
}
/**
 * 当type=1时获取出生日期,type=2时获取性别,type=3时获取年龄 all
 * @param {*} IdCard 
 * @param {*} type 
 * @returns 
 */
export function IdCard(IdCard, type) {
  let user = {
    birthday: '',
    sex: '',
    age: ''
  }
  if (type === 1 || type == 'all') {
    //获取出生日期
    let birthday = IdCard.substring(6, 10) + "-" + IdCard.substring(10, 12) + "-" + IdCard.substring(12, 14)
    if (type == 'all') {
      user.birthday = birthday
    } else {
      return birthday
    }
  }
  if (type === 2 || type == 'all') {
    //获取性别
    if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
      if (type == 'all') {
        user.sex = '男'
      } else {
        return "男女"
      }
    } else {
      if (type == 'all') {
        user.sex = '女'
      } else {
        return "女"
      }
    }
  }
  if (type === 3 || type == 'all') {
    //获取年龄
    var ageDate = new Date()
    var month = ageDate.getMonth() + 1
    var day = ageDate.getDate()
    var age = ageDate.getFullYear() - IdCard.substring(6, 10) - 1
    if (IdCard.substring(10, 12) < month || IdCard.substring(10, 12) === month && IdCard.substring(12, 14) <= day) {
      age++
    }
    if (age <= 0) {
      age = 1
    }
    if (type == 'all') {
      user.age = age
    } else {
      return age
    }

  }
  return user
}
