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,
  ImagePreview,
  List,
  Popup,
  showDialog,
  showFailToast,
  showImagePreview,
  showLoadingToast,
  showSuccessToast,
  showToast,
  Uploader
} from 'vant'
import { computed, 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'
import iconDown from '../images/icon-down.png'
import html2canvas from 'html2canvas'
import { promisefiyPostMessage } from '@/helpers/native-message'
import { getUploadSign, onOnlyFileUpload } from '@/helpers/oss-file-upload'

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 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('/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 viewImage = reactive({
      show: false,
      startPosition: 0,
      downIndex: 0,
      downLoading: false
    })
    // 图片列表
    const images = computed(() => {
      return state.list.map((file: any) => {
        return file.fileUrl
      })
    })
    const imgTobase64 = (_img: any) => {
      const _canvas = document.createElement('canvas')
      _canvas.width = _img.width
      _canvas.height = _img.height
      const ctx = _canvas.getContext('2d')
      ctx?.drawImage(_img, 0, 0, _canvas.width, _canvas.height)
      console.log(_img, _canvas)
      return _canvas.toDataURL('image/png')
    }
    const saveImg = async () => {
      const src = images.value[viewImage.downIndex]
      if (viewImage.downLoading || !src) return
      const t = showLoadingToast({
        message: '保存中',
        duration: 0
      })
      const _img = document.createElement('img')
      _img.crossOrigin = 'anonymous'
      _img.onload = async () => {
        const base64 = imgTobase64(_img)
        // console.log("🚀 ~ base64:", base64)
        try {
          const res = await promisefiyPostMessage({
            api: 'savePicture',
            content: {
              base64: base64
            }
          })
          if (res?.content?.status === 'success') {
            showSuccessToast('已保存到相册')
          } else {
            showFailToast('保存失败')
          }
        } catch (error) {}
        t.close()
        viewImage.downLoading = false
      }
      _img.src = src + `?v=${Date.now()}`
    }
    // 预览图片
    const onShowImage = (index: number) => {
      viewImage.downIndex = viewImage.startPosition = index
      viewImage.show = true
      // 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>

          <div
            style={{
              overflow: 'hidden'
            }}
          >
            <Button
              icon="plus"
              block
              class={styles.addPhone}
              onClick={() => (state.showPhoto = true)}
            >
              上传照片
            </Button>
          </div>
        </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>

        <ImagePreview
          v-model:show={viewImage.show}
          startPosition={viewImage.startPosition}
          images={images.value}
          onChange={(index: number) => (viewImage.downIndex = index)}
        >
          {{
            cover: () => (
              <div class={styles.downBtn} onClick={() => saveImg()}>
                <img src={iconDown} />
              </div>
            )
          }}
        </ImagePreview>
      </div>
    )
  }
})
