import OEmpty from '@/components/o-empty'
import OHeader from '@/components/o-header'
import OSticky from '@/components/o-sticky'
import request from '@/helpers/request'
import {
  Button,
  Checkbox,
  CheckboxGroup,
  closeToast,
  Icon,
  Image,
  List,
  Popup,
  showDialog,
  showImagePreview,
  showLoadingToast,
  showToast,
  Uploader
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import styles from './photo-detail.module.less'
import iconDelete from '../images/icon-delete.png'
import umiRequest from 'umi-request'
import { getOssUploadUrl } from '@/state'
import checkboxCheck from '../images/icon-checkbox-active.png'
import checkboxDefault from '@/common/images/icon-checkbox-default.png'

export default defineComponent({
  name: 'photo-detail',
  setup() {
    const route = useRoute()
    const state = reactive({
      isEdit: false,
      isLoading: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        page: 1,
        rows: 20
      },

      showPhoto: false,
      bucket: 'gyt',
      fileList: [] as any,
      checkboxRefs: [] as any,
      check: [] as any
    })

    const getList = async () => {
      try {
        if (state.isLoading) return
        state.isLoading = true
        const res = await request.post('/api-school/orchestraPhoto/page', {
          data: {
            ...state.params,
            orchestraPhotoAlbumId: route.query.photoId
          }
        })
        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 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 = '/api-school/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: []
            }
          }
        })
        showLoadingToast({
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0
        })
        const obj = {
          policy: res.data.policy,
          signature: res.data.signature,
          key: key,
          KSSAccessKeyId: res.data.kssAccessKeyId,
          acl: 'public-read',
          name: fileName
        }
        const formData = new FormData()
        for (const key in obj) {
          formData.append(key, obj[key])
        }
        formData.append('file', file, fileName)
        await umiRequest(getOssUploadUrl(state.bucket), {
          method: 'POST',
          data: formData
        })
        // console.log(getOssUploadUrl(state.bucket) + key)
        const uploadUrl = getOssUploadUrl(state.bucket) + key
        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('/api-school/orchestraPhoto/save', {
          data: {
            orchestraPhotoAlbumId: route.query.photoId,
            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()

        // setTimeout(() => {
        //   showToast('添加成功')
        //   state.showPhoto = false
        //   state.fileList = []
        // }, 100)
        // setTimeout(() => {
        //   state.params.page = 1
        //   state.list = []
        //   state.listState.dataShow = true // 判断是否有数据
        //   state.listState.loading = false
        //   state.listState.finished = false
        //   getList()
        // }, 1100)
      } catch {
        //
      }
    }

    // 预览图片
    const onShowImage = (index: number) => {
      const files = state.list.map((file: any) => {
        return file.fileUrl
      })

      showImagePreview({
        images: files,
        startPosition: index,
        closeable: true
      })
    }

    // 选择照片
    const onSelect = (type: string) => {
      state.checkboxRefs[type].toggle()
    }

    // 删除
    const onRemove = () => {
      if (state.check.length <= 0) {
        showToast('请选择需要删除的图片')
        return
      }
      showDialog({
        title: '确认删除',
        message: '删除选择的照片',
        confirmButtonText: '确认',
        showCancelButton: true
      }).then(async () => {
        console.log(state.check, 'check')
        try {
          await request.post('/api-school/orchestraPhoto/remove', {
            requestType: 'form',
            data: {
              ids: state.check.join(',')
            }
          })

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

          // setTimeout(() => {
          //   showToast('删除成功')
          // }, 100)
          // setTimeout(() => {
          //   state.params.page = 1
          //   state.list = []
          //   state.listState.dataShow = true // 判断是否有数据
          //   state.listState.loading = false
          //   state.listState.finished = false
          //   getList()
          // }, 1100)
        } catch {
          //
        }
      })
    }

    onMounted(() => {
      getList()
    })

    return () => (
      <div class={[styles.phoneDetail, !state.listState.dataShow && 'emptyRootContainer']}>
        <OSticky position="top">
          <OHeader title={(route.query.name as any) || ''}>
            {{
              right: () => (
                <Icon name={iconDelete} size={22} onClick={() => (state.isEdit = !state.isEdit)} />
              )
            }}
          </OHeader>

          <Button
            icon="plus"
            block
            class={styles.addPhone}
            onClick={() => (state.showPhoto = true)}
          >
            上传照片
          </Button>
        </OSticky>

        {state.listState.dataShow ? (
          <List
            // v-model:loading={state.listState.loading}
            finished={state.listState.finished}
            finishedText=" "
            onLoad={getList}
            immediateCheck={false}
          >
            <CheckboxGroup class={styles.phoneContainer} v-model={state.check}>
              {state.list.map((item: any, index: number) => (
                <div
                  class={[styles.item, state.check.includes(item.id) && styles.itemBorder]}
                  onClick={() => {
                    if (!state.isEdit) {
                      onShowImage(index)
                    } else {
                      onSelect(item.id)
                    }
                  }}
                >
                  <Checkbox
                    name={item.id}
                    checkedColor="#64a9ff"
                    class={[styles.checkbox, !state.isEdit && styles.checkboxHide]}
                    ref={(el: any) => (state.checkboxRefs[item.id] = el)}
                    onClick={(e: any) => {
                      e.stopPropagation()
                    }}
                    v-slots={{
                      icon: (props: any) => (
                        <Icon
                          class={styles.iconChecked}
                          name={props.checked ? checkboxCheck : checkboxDefault}
                        />
                      )
                    }}
                  />
                  <div
                    class={styles.img}
                    style={
                      item.fileUrl
                        ? { backgroundImage: `url(${item.fileUrl})`, backgroundSize: 'cover' }
                        : ''
                    }
                  ></div>
                </div>
              ))}
            </CheckboxGroup>
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无照片" />
        )}

        {state.isEdit && (
          <OSticky position="bottom">
            <div class={'btnGroup'}>
              <Button block round type="primary" onClick={onRemove}>
                删除
              </Button>
            </div>
          </OSticky>
        )}

        <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>
    )
  }
})
