import { Cell, CellGroup, Checkbox, Icon, Toast } from 'vant'
import { defineComponent, watch } from 'vue'
import { musicJSON as musicData } from '../..'
import SettingState from '/src/pages/detail/setting-state'
import styles from './index.module.less'
import request from '/src/helpers/request'
import detailState from '/src/pages/detail/state'
import axios from 'umi-request'
import { useClientType, useOriginSearch } from '../../uses'
import { musicInfo } from '../../state'

/**检测是否需要生成缓存数据 */
export const getHasCache = () => {
  let isProduction = false
  // 是否有五线谱的缓存
  if (SettingState.sett.type === 'staff') {
    isProduction = !musicInfo.musicSvg?.staff
  } else {
    //是否有固定调和首调的缓存
    isProduction = SettingState.sett.keySignature ? !musicInfo.musicSvg?.fixedTone : !musicInfo.musicSvg?.firstTone
  }
  return isProduction
}
export default defineComponent({
  name: 'productJson',
  setup(props, { expose }) {
    const search = useOriginSearch()
    const autoProduct = (val: any) => {
      if (search.modeType === 'json') return
      // console.log(musicData.rended, '渲染是否结束')
      if (!musicData.svg) {
        musicData.svg = document.getElementById('osmdSvgPage1')?.outerHTML || ''
      }
      if (!musicData.svg) {
        return
      }
      handleSave(false)
    }
    expose({
      autoProduct,
    })
    //清空数据
    const handleRemove = async () => {
      await handleUpdate({
        id: musicInfo.id,
        musicSvg: '',
      })
      Toast('清除成功')
      setTimeout(() => {
        history.go(0)
      }, 500)
    }
    //保存数据
    const handleSave = async (showMsg: boolean = true) => {
      // 没有json数据
      if (!musicData.json) {
        if (showMsg) Toast('没有生成json数据,联系开发人员')
        return
      }
      if (!musicData.svg) {
        if (showMsg) Toast('没有生成svg数据,联系开发人员')
        return
      }
      let toast = null as any
      if (showMsg) {
        toast = Toast.loading({
          message: '上传数据中 1/2',
          duration: 0,
        })
      }

      // console.log(musicData)
      // 上传json数据
      const renderData = {
        svg: '',
        json: '',
      }
      renderData.json = await beforeUpload(`${detailState.activeDetail?.id}.json`, musicData.json)
      if (toast) toast.message = '上传数据中 2/2'
      renderData.svg = await beforeUpload(`${detailState.activeDetail?.id}.svg`, musicData.svg)
      if (!renderData.json || !renderData.svg) {
        if (showMsg) Toast('上传缓存数据失败')
        return
      }
      let body = {
        id: musicInfo.id,
        musicSvg: '',
      }
      const musicSvg = {} as any
      if (SettingState.sett.type === 'staff') {
        musicSvg.staff = renderData
      } else {
        if (SettingState.sett.keySignature) {
          // 固定调
          musicSvg.fixedTone = renderData
        } else {
          //首调
          musicSvg.firstTone = renderData
        }
      }
      body.musicSvg = JSON.stringify(musicSvg)
      if (toast) toast.message = '保存数据中'
      console.log('🚀 ~ body:', body)
      const res = await handleUpdate(body)
      if ((res as any)?.code == 200) {
        if (toast) toast.message = '保存成功'
      } else {
        if (toast) toast.message = '保存失败'
      }
      setTimeout(() => {
        if (toast) toast.close()
      }, 300)
    }

    // 保存
    const handleUpdate = async (body: any) => {
      const res: any = await request.post('/musicSheet/updateRenderFile', {
        requestType: 'json',
        data: body,
      })
      if (res.code === 200 && body.musicSvg) {
        musicInfo.musicSvg = JSON.parse(body.musicSvg)
      }
      return res
    }
    const beforeUpload = async (fileName: string, fileData: string) => {
      const bucketName = 'cloud-coach'
      const ossUrl = `https://${bucketName}.ks3-cn-beijing.ksyuncs.com/`
      let key = Date.now() + '_' + fileName
      let obj = {
        filename: fileName,
        bucketName,
        postData: {
          filename: fileName,
          acl: 'public-read',
          key: key,
          // unknowValueField: [],
        },
      }
      const res = await request.post('/open/getUploadSign', {
        requestType: 'json',
        data: obj,
      })
      const formData = new FormData()
      const body = {
        policy: res.data.policy,
        signature: res.data.signature,
        key: key,
        KSSAccessKeyId: res.data.kssAccessKeyId,
        acl: 'public-read',
        name: fileName,
      }
      for (let itemKey in body) {
        formData.append(itemKey, (body as any)[itemKey])
      }
      formData.append('file', new Blob([fileData]))
      const res2 = await axios.post(ossUrl, {
        data: formData,
      })
      return ossUrl + key
    }
    return () => (
      
      <>
        {search.modeType === 'json' && (
          <div class={styles.wrap}>
            <CellGroup>
              <Cell center>
                {{
                  title: () => (
                    <div class={styles.wrapItem}>
                      <span>缓存状态: </span>
                      <span>
                        五线谱&nbsp;
                        {musicInfo.musicSvg?.staff ? (
                          <Icon name="success" color="rgba(103,201,176,1)" />
                        ) : (
                          <Icon name="cross" color="#ff6868" />
                        )}
                      </span>
                      <span>
                        首调&nbsp;
                        {musicInfo.musicSvg?.firstTone ? (
                          <Icon name="success" color="rgba(103,201,176,1)" />
                        ) : (
                          <Icon name="cross" color="#ff6868" />
                        )}
                      </span>
                      <span>
                        固定调&nbsp;
                        {musicInfo.musicSvg?.fixedTone ? (
                          <Icon name="checked" color="rgba(103,201,176,1)" />
                        ) : (
                          <Icon name="cross" color="#ff6868" />
                        )}
                      </span>
                    </div>
                  ),
                }}
              </Cell>
              <Cell class={styles.clearItem} title="清除缓存数据" clickable onClick={handleRemove}></Cell>
              <Cell class={styles.saveItem} title="保存缓存数据" clickable onClick={handleSave}></Cell>
            </CellGroup>
          </div>
        )}
      </>
    )
  },
})
