import { defineComponent, reactive, Ref, ref } from 'vue'
import { Sticky, List, Popup, Field, Button, Toast } from 'vant'
import Search from '@/components/col-search'
import request from '@/helpers/request'
import Item, { auditStatus, auditStatusColor } from './item'
// import SelectTag from '../search/select-tag'
import { useRoute, useRouter } from 'vue-router'
import ColResult from '@/components/col-result'
import styles from '../../views/music/list/index.module.less'
import { getRandomKey, musicBuy } from '../../views/music/music'
import ColHeader from '@/components/col-header'
import TheSticky from '@/components/the-sticky'

const noop = () => {}

export default defineComponent({
  name: 'ReviewList',
  props: {
    hideSearch: {
      type: Boolean,
      default: false
    },
    defauleParams: {
      type: Object,
      default: () => ({})
    },
    onItemClick: {
      type: Function,
      default: noop
    },
    teacherId: {
      type: String || Number,
      default: ''
    }
  },
  setup({ hideSearch, defauleParams, onItemClick, teacherId }, { expose }) {
    localStorage.setItem('behaviorId', getRandomKey())
    const route = useRoute()
    const router = useRouter()
    const tempParams: any = {}
    const query = route.query
    if (query.version) {
      tempParams.version = query.version || '' // 处理ios审核版本
    }
    const params = reactive({
      search: (route.query.search as string) || '',
      musicTagIds: route.query.tagids || '',
      page: 1,
      ...tempParams,
      ...defauleParams
    })
    const data = ref<any>(null)
    const loading = ref(false)
    const finished = ref(false)
    const isError = ref(false)
    const tagVisibility = ref(false)

    const onSearch = (value: string) => {
      params.page = 1
      params.search = value
      data.value = null
      FetchList()
    }

    const FetchList = async () => {
      if (loading.value) {
        return
      }
      loading.value = true
      isError.value = false
      try {
        const res = await request.post('/api-admin/music/sheet/audit/list', {
          data: {
            ...params
          }
        })
        if (data.value) {
          const result = (data.value?.rows || []).concat(res.data.rows || [])
          data.value.rows = result
        }
        data.value = data.value || res.data
        params.page = res.data.pageNo + 1
        finished.value = res.data.pageNo >= res.data.totalPage
      } catch (error) {
        isError.value = true
      }
      loading.value = false
    }

    const onComfirm = tags => {
      const d = Object.values(tags).flat().filter(Boolean).join(',')
      params.musicTagIds = d
      params.page = 1
      data.value = null
      FetchList()
      tagVisibility.value = false
    }

    expose({
      onSearch,
      onComfirm
    })

    const message = ref('')
    const detail: Ref<any> = ref(null)
    const visivle = ref(false)

    const submit = async (data: any) => {
      try {
        await request.post('/api-admin/music/sheet/audit', {
          data
        })
        Toast.success('提交成功')
        visivle.value = false
        message.value = ''
        onSearch(params.search)
      } catch (error) {}
    }

    return () => (
      <>
        <List
          loading={loading.value}
          finished={finished.value}
          finished-text={
            data.value && data.value.rows.length ? '没有更多了' : ''
          }
          onLoad={FetchList}
          error={isError.value}
        >
          {!hideSearch && (
            <TheSticky>
              <ColHeader border={false} />
              <Search onSearch={onSearch} />
            </TheSticky>
          )}

          {data.value && data.value.rows.length
            ? data.value.rows.map(item => (
                <Item
                  data={item}
                  onClick={() => {
                    detail.value = {
                      ...item
                    }
                    visivle.value = true
                    console.log(item)
                    // router.push({
                    //   path: '/review/' + item.musicSheetId,
                    //   state: item
                    // })
                  }}
                />
              ))
            : !loading.value && (
                <ColResult
                  tips="暂无曲目"
                  classImgSize="SMALL"
                  btnStatus={false}
                />
              )}
        </List>
        <Popup
          position="bottom"
          closeable
          style={{ minHeight: '30%' }}
          show={!!detail.value && visivle.value}
          onClosed={() => (detail.value = null)}
          onClose={() => (visivle.value = false)}
          teleport="body"
          round
        >
          <Field
            label="曲目名称"
            readonly
            modelValue={detail.value?.musicSheetName}
          />
          <Field
            label="曲谱检查"
            readonly
            isLink
            modelValue="立即查看"
            onClick={() =>
              musicBuy({ id: detail.value?.musicSheetId }, undefined, {
                client: 'teacher'
              })
            }
          />
          {detail.value?.auditStatus === 'DOING' ? (
            <>
              <Field
                readonly={detail.value?.auditStatus !== 'DOING'}
                v-model={message.value}
                rows="3"
                clearable
                autosize
                label="审核理由"
                type="textarea"
                placeholder="请输入审核理由"
                required={detail.value?.auditStatus === 'DOING'}
              />
              <div
                style={{
                  display: 'flex'
                }}
              >
                <Button
                  disabled={
                    !message.value && detail.value?.auditStatus === 'DOING'
                  }
                  block
                  type="danger"
                  onClick={() =>
                    submit({
                      musicSheetId: detail.value?.musicSheetId,
                      authStatus: 'UNPASS',
                      remark: message.value
                    })
                  }
                >
                  拒绝
                </Button>
                <Button
                  disabled={
                    !message.value && detail.value?.auditStatus === 'DOING'
                  }
                  block
                  type="primary"
                  onClick={() =>
                    submit({
                      musicSheetId: detail.value?.musicSheetId,
                      authStatus: 'PASS',
                      remark: message.value
                    })
                  }
                >
                  同意
                </Button>
              </div>
            </>
          ) : null}
        </Popup>
      </>
    )
  }
})
