import { computed, isRef, onMounted, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { getCateTreeData } from '@/utils'

export default function useClassifyList(options, immediate = true) {
  const loading = isRef(options.loading) ? options.loading : null;
  const total = ref(0);
  const cateList = ref([]);
  const current = ref({});
  const cateTree = computed(() => {
    const data = getCateTreeData(cateList.value)
    if (options.useAll) return [{ _id: 'ALL', label: '全部', childrenIds: [...allCateIds.value] }, ...data]
    return data
  });
  const cateIds = computed(() => {
    const id = current.value && current.value._id ? current.value._id : '';
    const childrenIds = current.value && Array.isArray(current.value.childrenIds) ? current.value.childrenIds : [];
    return [id, ...childrenIds].filter(i => Boolean(i) && i !== 'ALL')
  })
  const allCateIds = computed(() => cateList.value.map(i => i._id).sort())

  const addApi = typeof options.add === 'function' ? options.add : () => { };
  const getListApi = typeof options.getList === 'function' ? options.getList : () => { };
  const removeApi = typeof options.remove === 'function' ? options.remove : () => { };
  const sortApi = typeof options.sort === 'function' ? options.sort : () => { };
  const updateApi = typeof options.update === 'function' ? options.update : () => { };
  const callback = typeof options.callback === 'function' ? options.callback : () => { };
  const getTotalApi = typeof options.getTotal === 'function' ? options.getTotal : null;
  const format = typeof options.format === 'function' ? options.format : (i) => i;

  async function addCate(data) {
    const params = { corpId: sessionStorage.getItem('corpId'), ...data }
    const { success, message } = await addApi(params);
    if (success) getCateList()
    return { success, message }
  }

  async function removeCate(id) {
    const params = { corpId: sessionStorage.getItem('corpId'), id }
    const { success, message } = await removeApi(params);
    if (success) getCateList()
    return { success, message }
  }

  async function sortCate(sortData) {
    const params = { corpId: sessionStorage.getItem('corpId'), sortData }
    const { success, message } = await sortApi(params);
    if (success) getCateList()
    return { success, message }
  }

  async function updateCate(data) {
    const params = { corpId: sessionStorage.getItem('corpId'), ...data }
    const { success, message } = await updateApi(params);
    if (success) getCateList()
    return { success, message }
  }

  async function getCateList(id) {
    if (loading) loading.value = true;
    const { success, data, message } = await getListApi({ corpId: sessionStorage.getItem('corpId') });
    if (success) {
      cateList.value = data && Array.isArray(data.list) ? format(data.list) : [];
      const cate = cateList.value.find(i => i._id === id);
      if (cate) changeCurrent(cate);
    } else {
      ElMessage.error(message);
      cateList.value = []
    }
    if (loading) loading.value = false;
  }

  async function getTotal(cateIds) {
    const { data } = await getTotalApi({ corpId: sessionStorage.getItem('corpId'), cateIds });
    total.value = data && data.data > 0 ? data.data : 0
  }


  function changeCurrent(data) {
    current.value = { ...data }
  }

  if (immediate) onMounted(() => getCateList())

  watch(current, (n, o) => {
    const newId = n && n._id ? n._id : '';
    const oldId = o && o._id ? o._id : '';
    const newChildIds = n && Array.isArray(n.childrenIds) ? n.childrenIds.join() : '';
    const oldChildIds = o && Array.isArray(o.childrenIds) ? o.childrenIds.join() : '';
    if (newId !== oldId || newChildIds !== oldChildIds) callback()
  })

  if (getTotalApi) {
    watch(allCateIds, (n, o) => {
      const arr = Array.isArray(o) ? o : []
      if (n.join() != arr.join()) getTotal(n)
    })
  }


  return {
    cateList,
    current,
    cateIds,
    cateTree,
    changeCurrent,
    getCateList,
    total,
    componentProps: {
      pname: ref('分类列表'),
      addMethod: addCate,
      removeMethod: removeCate,
      sortMethod: sortCate,
      updateMethod: updateCate,
    }
  }
}