import Taro, { useDidHide, useDidShow } from '@tarojs/taro'
import { Text, View } from '@tarojs/components'
import classnames from 'classnames'
import { useCallback, useEffect, useRef, useState } from 'react'
import Product from './components/product'
import CreatePopup from './components/createPopup'
import UpdatePopup from './components/updatePopup'
import styles from './index.module.scss'
import Search from '@/components/search'
import { getFilterData } from '@/common/util'
import { alert, goLink } from '@/common/common'
import { CreateFavoriteApi, DelFavoriteApi, FavoriteListApi, UpdateFavoriteApi } from '@/api/favorite'
import useLogin from '@/use/useLogin'

export default () => {
  useLogin()

  // 获取搜索数据
  const [searchData, setSearchData] = useState('')
  const onSearch = useCallback((e) => {
    setSearchData(() => e)
  }, [])

  // 获取列表
  const [list, setList] = useState([])
  const { fetchData: fetchDataList } = FavoriteListApi()
  const getFavoriteList = async() => {
    const res = await fetchDataList(getFilterData({ name: searchData }))
    setList(() => res.data.list)
  }
  const changeOpenCon = (item) => {
    item.openStatus = !item.openStatus
    setList(e => [...e])
  }
  useDidShow(() => {
    getFavoriteList()
  })
  // 创建收藏夹
  const [collectioinShow, setCollectioinShow] = useState(false)
  const closeCollection = useCallback(() => {
    setCollectioinShow(false)
  }, [])

  // 更多编辑
  const [initData, setInitData] = useState({
    remark: '',
    name: '',
    id: 0,
  })
  const creatShow = () => {
    setCollectioinShow(true)
    setInitData(() => ({ remark: '', name: '', id: 0 }))
  }
  useEffect(() => {
    getFavoriteList()
  }, [searchData])
  // 新增
  const { fetchData } = CreateFavoriteApi()
  const onCreate = async(submitData) => {
    if (!submitData.name) { return alert.none('请输入收藏夹名称!') }
    const res = await fetchData({ ...submitData })
    if (res.success) {
      alert.success('创建成功')
      getFavoriteList()
    }
    else {
      alert.error('创建失败')
    }
  }

  const selectInfo = useRef<any>(null)
  const [updateShow, setUpdateShow] = useState(false)
  const closeUpdate = useCallback(() => {
    setUpdateShow(false)
  }, [])
  const moreUpdate = (item, e) => {
    e.stopPropagation()
    selectInfo.current = item
    console.log('item:::', item)
    setInitData(e => ({ ...e, remark: item.remark, name: item.name, id: item.id }))
    setUpdateShow(true)
  }

  // 删除改收藏夹
  const { fetchData: delFetchData } = DelFavoriteApi()
  const onDeleteCollect = useCallback(() => {
    if (!selectInfo.current.id) { return alert.error('参数不正确！') }
    if (selectInfo.current.id == 1) { return alert.none('删除失败,该文件夹不能删除!') }
    Taro.showModal({
      content: '确认删除该文件夹?',
      async success(res) {
        if (res.confirm) {
          const res = await delFetchData({ id: selectInfo.current.id })
          if (res.success) {
            alert.success('删除成功')
            getFavoriteList()
          }
          else {
            alert.error('删除失败')
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
    closeUpdate()
  }, [])

  // 编辑
  const { fetchData: updateFavoriteFetchData } = UpdateFavoriteApi()
  const onUpdateShow = useCallback(() => {
    setCollectioinShow(true)
  }, [])
  const onUpdate = async(submitData) => {
    if (!submitData.name) { return alert.none('请输入收藏夹名称!') }
    const res = await updateFavoriteFetchData({ ...submitData })
    if (res.success) {
      alert.success('编辑成功')
      getFavoriteList()
      closeUpdate()
    }
    else {
      alert.error('编辑失败')
    }
  }

  const onBatchManagement = useCallback(() => {
    goLink('/pages/collection/collectionClass/index', { id: initData.id })
    closeUpdate()
  }, [initData])

  // 操作文件夹
  const onCreatSuccess = (submitData) => {
    if (!initData.id) {
      onCreate(submitData)
    }
    else {
      onUpdate({ ...submitData, id: initData.id })
    }
    setCollectioinShow(false)
  }

  return (
    <View className={styles.collection_main}>
      <View className={styles.search}>
        <Search style={{ width: '100%' }} debounceTime={300} changeOnSearch={onSearch} placeholder="请输入面料关键词" />
        <View className={styles.miconfont_con} onClick={creatShow}><Text className={classnames(styles.miconfont, 'iconfont icon-jia')}></Text></View>
      </View>
      <View className={styles.class_list}>
        {list?.map((item: any, key) => <View className={styles.class_item} key={key}>
          <View key={item.id} className={styles.class_title} onClick={() => changeOpenCon(item)}>
            <Text className={classnames(styles.miconfont_left, 'iconfont icon-a-moreback', item.openStatus ? styles.miconfont_open : styles.miconfont_close)}></Text>
            <View className={styles.title}>{item.name}
              {item.product_color_list && <><Text className={styles.fg}>·</Text><Text className={styles.num}>{item.product_color_list.length}</Text></>}
            </View>
            <View className={styles.more} onClick={e => moreUpdate(item, e)}>更多</View>
          </View>
          <View className={styles.class_con} style={item.openStatus ? { maxHeight: `${10 * 260}rpx` } : { maxHeight: 0 }} >
            <Product productList={item.product_color_list || []} />
          </View>
        </View>)}
      </View>
      <UpdatePopup show={updateShow} onClose={closeUpdate} onDelete={onDeleteCollect} onUpdate={onUpdateShow} onBatchManagement={onBatchManagement} />
      <CreatePopup defaultValue={initData} show={collectioinShow} onClose={closeCollection} onSuccess={onCreatSuccess} />
    </View>
  )
}

