import OEmpty from '@/components/o-empty'
import request from '@/helpers/request'
import {
  ActionSheet,
  Button,
  closeToast,
  Field,
  List,
  Popup,
  showConfirmDialog,
  showLoadingToast,
  showToast,
  Uploader
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './photo.module.less'
// import iconPhoneDefaut from '../images/icon-photo-default.png'
import OHeader from '@/components/o-header'
import OSticky from '@/components/o-sticky'
import { getOssUploadUrl } from '@/state'
// import umiRequest from 'umi-request'
import { getUploadSign, onOnlyFileUpload } from '@/helpers/oss-file-upload'
import { state as baseState } from '@/state'

export default defineComponent({
  name: 'phone-create',
  props: {
    height: {
      type: [String, Number],
      default: 'auto'
    }
  },
  setup(props) {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      oPopover: false,
      showPhoto: false,
      status: false,
      isLoading: false,
      photoName: null as any, // 相册名称
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        page: 1,
        rows: 20
      },
      selectItem: {} as any,
      selectType: 'add',
      fileList: [] as any,
      bucket: 'gyt'
    })

    const onAddPhoto = async () => {
      try {
        if (!state.photoName) {
          showToast('请输入相册名称')
          state.status = true
          return
        }
        if (state.selectType === 'add') {
          await request.post(baseState.platformApi + '/orchestraPhotoAlbum/save', {
            data: {
              orchestraId: route.query.orchestraId,
              name: state.photoName,
              parentId: route.query.parentId,
              schoolId: route.query.schoolId
            }
          })
          // setTimeout(() => {
          //   showToast('添加成功')
          // }, 100)
          state.status = false
          state.photoName = null
          onSearch()
        } else {
          await request.post(baseState.platformApi + '/orchestraPhotoAlbum/update', {
            data: {
              id: state.selectItem.id,
              orchestraId: route.query.orchestraId,
              parentId: route.query.parentId,
              name: state.photoName
            }
          })
          // setTimeout(() => {
          //   showToast('修改成功')
          // }, 100)
          state.status = false
          state.photoName = null
          onSearch()
        }

        // setTimeout(() => {
        //   state.photoName = null
        //   onSearch()
        // }, 1100)
      } catch {
        //
      }
    }

    const onSearch = () => {
      state.params.page = 1
      state.list = []
      state.listState.dataShow = true // 判断是否有数据
      state.listState.loading = false
      state.listState.finished = false
      getList()
    }

    // 班级列表
    const getList = async () => {
      try {
        if (state.isLoading) return
        state.isLoading = true
        const res = await request.post(baseState.platformApi + '/orchestraPhotoAlbum/page', {
          data: {
            ...state.params,
            orchestraId: route.query.orchestraId,
            parentId: route.query.parentId,
            schoolId: route.query.schoolId
          }
        })
        state.listState.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (state.list.length > 0 && result.current === 1) {
          return
        }
        const rows = result.rows || []
        state.list = state.list.concat(rows)
        state.listState.finished = result.current >= result.pages
        state.params.page = result.current + 1
        state.listState.dataShow = state.list.length > 0
        state.isLoading = false
      } catch {
        state.listState.dataShow = false
        state.listState.finished = true
        state.isLoading = false
      }
    }

    const onDetail = (item: any) => {
      sessionStorage.setItem('orchestra-detail-tab', 'photo')
      router.push({
        path: '/photo-detail',
        query: {
          photoId: item.id,
          name: item.name
        }
      })
    }

    const onRename = async () => {
      state.photoName = state.selectItem.name
      state.status = true
    }

    const onRemove = async () => {
      showConfirmDialog({
        message: '您确认删除该相册吗？'
      }).then(async () => {
        try {
          await request.post(baseState.platformApi + '/orchestraPhotoAlbum/remove', {
            requestType: 'form',
            data: {
              id: state.selectItem.id
            }
          })
          // setTimeout(() => {
          //   showToast('删除成功')
          // }, 100)

          // setTimeout(() => {
          onSearch()
          // }, 1100)
        } catch {
          //
        }
      })
    }

    onMounted(() => {
      getList()
    })
    const beforeRead = (file: any) => {
      // console.log(file, 'beforeRead')
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        showToast(`上传文件大小不能超过 5MB`)
        return false
      }
      return true
    }
    const beforeDelete = (file: any, detail: { index: any }) => {
      // this.dataModel.splice(detail.index, 1)
      return true
    }
    const afterRead = async (file: any, detail: any) => {
      try {
        file.status = 'uploading'
        file.message = '上传中...'
        await uploadFile(file)
      } catch (error) {
        //
        closeToast()
      }
    }

    const uploadFile = async (files: any) => {
      // 上传文件
      try {
        console.log(files, 'files')
        const file = files.file
        // 获取签名
        // const signUrl = baseState.platformApi + '/open/getUploadSign'
        // const tempName = file.name || ''
        // const fileName = '/orchestra/' + (tempName && tempName.replace(/ /gi, '_'))
        // const key = new Date().getTime() + fileName

        // const res = await request.post(signUrl, {
        //   data: {
        //     filename: fileName,
        //     bucketName: state.bucket,
        //     postData: {
        //       filename: fileName,
        //       acl: 'public-read',
        //       key: key,
        //       unknowValueField: []
        //     }
        //   }
        // })
        const tempName = file.name || ''
        const fileName = '/orchestra/' + (tempName && tempName.replace(/ /gi, '_'))

        const key = new Date().getTime() + fileName
        const { data } = await getUploadSign({
          filename: key,
          bucketName: state.bucket,
          postData: {
            filename: key,
            acl: 'public-read',
            key: key,
            unknowValueField: []
          }
        })
        showLoadingToast({
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0
        })
        const obj = {
          policy: data.policy,
          signature: data.signature,
          key: key,
          KSSAccessKeyId: data.kssAccessKeyId,
          acl: 'public-read',
          name: key,
          file
        }
        const uploadUrl = await onOnlyFileUpload(getOssUploadUrl(state.bucket), obj)

        closeToast()

        // state.fileList.push({ url: uploadUrl })
        files.src = uploadUrl
        files.status = 'done'
      } catch (error) {
        files.status = 'failed'
        console.log(error, 'uploadFile')
      }
    }

    // 上传图片
    const onSubmitPhoto = async () => {
      try {
        if (state.fileList.length <= 0) {
          showToast('请上传照片')
          return
        }
        const files = state.fileList.map((file: any) => {
          return file.src
        })
        console.log(files, 'onSubmitPhoto')

        await request.post(baseState.platformApi + '/orchestraPhoto/save', {
          data: {
            orchestraId: route.query.orchestraId,
            orchestraPhotoAlbumId: route.query.parentId,
            fileUrl: files.join(',')
          }
        })

        state.showPhoto = false
        state.fileList = []
        state.params.page = 1
        state.list = []
        state.listState.dataShow = true // 判断是否有数据
        state.listState.loading = false
        state.listState.finished = false
        getList()
      } catch {
        //
      }
    }
    return () => (
      <div class={!state.listState.dataShow && 'emptyRootContainer'}>
        <OSticky position="top">
          <OHeader title={'创建相册'}></OHeader>
          <div class={styles.btnGroup}>
            <Button
              icon="plus"
              block
              class={styles.addPhone}
              onClick={() => {
                state.photoName = ''
                state.status = true
                state.selectType = 'add'
              }}
            >
              新建相册
            </Button>
            <Button
              icon="plus"
              block
              class={styles.addPhone}
              onClick={() => (state.showPhoto = true)}
            >
              上传照片
            </Button>
          </div>
        </OSticky>
        <div class={styles.phone}>
          {state.listState.dataShow ? (
            <List
              // v-model:loading={state.listState.loading}
              finished={state.listState.finished}
              finishedText=" "
              onLoad={getList}
              immediateCheck={false}
              class={styles.informationGroup}
            >
              <div class={styles.phoneContainer}>
                {state.list.map((item: any) => (
                  <div class={styles.item} onClick={() => onDetail(item)}>
                    {/* <i class={styles.more}></i> */}
                    <i
                      class={styles.more}
                      onClick={(e: any) => {
                        e.stopPropagation()
                        state.oPopover = true
                        state.selectItem = item
                        state.selectType = 'update'
                      }}
                    ></i>

                    <div class={styles.imgSection}>
                      <div
                        class={styles.img}
                        style={
                          item.coverUrl
                            ? { backgroundImage: `url(${item.coverUrl})`, backgroundSize: 'cover' }
                            : ''
                        }
                      ></div>
                    </div>

                    <p class={[styles.name, 'van-ellipsis']}>{item.name}</p>
                    <p class={styles.num}>{item.photoCount}张</p>
                  </div>
                ))}
              </div>
            </List>
          ) : (
            <OEmpty btnStatus={false} tips="暂无相册" />
          )}

          <Popup v-model:show={state.status} round style={{ width: '80%' }}>
            <div class={styles.container}>
              <div class={styles.dialogTitle}>
                <i></i>
                {state.selectType === 'add' ? '新建相册' : '重命名相册'}
              </div>
              <Field
                class={styles.phoneName}
                v-model={state.photoName}
                placeholder="请输入相册名称"
                maxlength={15}
              />

              <div class={['van-hairline--top van-dialog__footer']}>
                <Button
                  onClick={() => (state.status = false)}
                  class={['van-button van-button--default van-button--large van-dialog__cancel']}
                >
                  取消
                </Button>
                <Button
                  onClick={onAddPhoto}
                  class={[
                    'van-button van-button--default van-button--large van-dialog__confirm van-hairline--left'
                  ]}
                >
                  确认
                </Button>
              </div>
            </div>
          </Popup>

          <ActionSheet
            cancelText="取消"
            v-model:show={state.oPopover}
            closeOnClickAction
            actions={[
              { name: '重命名', callback: () => onRename() },
              { name: '删除', color: '#F44541', callback: () => onRemove() }
            ]}
          />
        </div>

        <Popup v-model:show={state.showPhoto} round style={{ width: '92%' }}>
          <div class={styles.container}>
            <div class={styles.dialogTitle}>
              <i></i>
              上传照片
            </div>

            <div class={styles.photos}>
              <Uploader
                v-model={state.fileList}
                afterRead={afterRead}
                beforeRead={beforeRead}
                beforeDelete={beforeDelete}
                accept="image/*"
                maxCount={9}
              />
            </div>

            <div class={['van-hairline--top van-dialog__footer']}>
              <Button
                onClick={() => {
                  state.showPhoto = false
                  state.fileList = []
                }}
                class={['van-button van-button--default van-button--large van-dialog__cancel']}
              >
                取消
              </Button>
              <Button
                onClick={onSubmitPhoto}
                class={[
                  'van-button van-button--default van-button--large van-dialog__confirm van-hairline--left'
                ]}
              >
                确认
              </Button>
            </div>
          </div>
        </Popup>
      </div>
    )
  }
})
