import OSticky from '@/components/o-sticky'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import {
  Button,
  Cell,
  CellGroup,
  DatePicker,
  Field,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  showSuccessToast,
  showToast
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import iconUpload from '../images/icon-upload.png'
import iconUploadVideo from '../images/icon-upload-video.png'
import iconUploadVideoCover from '../images/icon-upload-video-cover.png'
import OUploadAll from '@/components/o-upload-all'
import OHeader from '@/components/o-header'
import ODialog from '@/components/o-dialog'
import { useRoute, useRouter } from 'vue-router'
import { browser } from '@/helpers/utils'

export default defineComponent({
  name: 'story-operation',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const forms = reactive({
      id: route.query.id || null,
      content: '',
      orchestraStatus: false,
      orchestraList: [] as any,
      selectOrchestra: {} as any,
      createTime: new Date() as any,
      createTimeStatus: false,
      currentDate: [dayjs().format('YYYY'), dayjs().format('MM'), dayjs().format('DD')],
      storyType: 'IMAGE',
      attachments: [] as any, //群发消息附件
      video: [] as any,
      videoCover: [] as any,
      delStatus: false
    })

    // 获取乐团列表
    const getOrchestras = async () => {
      try {
        const { data } = await request.post('/api-school/orchestra/page', {
          data: {
            page: 1,
            rows: 100
          }
        })
        const temps = data.rows || []
        const s = [] as any
        temps.forEach((item: any) => {
          s.push({
            text: item.name,
            value: item.id
          })
        })
        forms.orchestraList = [...s]

        // 判断是否有乐团
        if (s.length > 0) {
          forms.selectOrchestra = s[0]
        }
      } catch {
        //
      }
    }

    const getDetails = async () => {
      try {
        if (!forms.id) {
          return
        }
        const { data } = await request.get('/api-school/orchestraStory/detail/' + forms.id)
        console.log(data)
        forms.content = data.content
        forms.createTime = data.createTime
        forms.storyType = data.type

        forms.orchestraList.forEach((item: any) => {
          if (item.value === item.orchestraId) {
            forms.selectOrchestra = item
          }
        })

        if (data.type === 'IMAGE') {
          data.attachments &&
            data.attachments.forEach((item: any) => {
              forms.attachments.push(item.url)
            })
        } else {
          const temp = data.attachments ? data.attachments[0] : []
          forms.video.push(temp.url)
          forms.videoCover.push(temp.coverImage)
        }
      } catch {
        //
      }
    }

    const onSumbit = async () => {
      try {
        if (!forms.selectOrchestra.value) {
          showToast('请选择乐团')
          return
        }
        if (!forms.createTime) {
          showToast('请选择事迹日期')
          return
        }
        if (!forms.content) {
          showToast('请输入事迹内容')
          return
        }

        if (forms.storyType === 'IMAGE' && forms.attachments.length <= 0) {
          showToast('请上传照片')
          return
        }
        if (forms.storyType === 'VIDEO') {
          if (forms.video.length <= 0) {
            showToast('请上传视频')
            return
          }
          if (forms.videoCover.length <= 0) {
            showToast('请上传视频封面')
            return
          }
        }

        const attachments: any = []
        if (forms.storyType === 'IMAGE') {
          forms.attachments.forEach((item: any) => {
            const temp = {
              attachmentType: forms.storyType,
              url: item
            }

            attachments.push(temp)
          })
        } else {
          attachments.push({
            attachmentType: forms.storyType,
            url: forms.video[0],
            coverImage: forms.videoCover[0]
          })
        }

        console.log({
          createTime: dayjs(forms.createTime).format('YYYY-MM-DD HH:mm:ss'),
          orchestraId: forms.selectOrchestra.value,
          content: forms.content,
          type: forms.storyType,
          attachments
        })
        const params = {
          createTime: dayjs(forms.createTime).format('YYYY-MM-DD HH:mm:ss'),
          orchestraId: forms.selectOrchestra.value,
          content: forms.content,
          type: forms.storyType,
          attachments
        }

        if (forms.id) {
          await request.post('/api-school/orchestraStory/update', {
            data: {
              ...params,
              id: forms.id
            }
          })

          setTimeout(() => {
            showSuccessToast('修改成功')
          }, 100)
        } else {
          await request.post('/api-school/orchestraStory/save', {
            data: params
          })

          setTimeout(() => {
            showSuccessToast('添加成功')
          }, 100)
        }

        setTimeout(() => {
          router.back()
        }, 1100)
      } catch {
        //
      }
    }

    //
    const onConfirm = async () => {
      try {
        await request.post('/api-school/orchestraStory/remove', {
          requestType: 'form',
          data: {
            id: forms.id
          }
        })

        setTimeout(() => {
          showSuccessToast('删除成功')
        }, 100)
        setTimeout(() => {
          router.back()
        }, 1100)
      } catch {
        //
      }
    }

    onMounted(async () => {
      if (forms.id) {
        document.title = '修改事迹'
      }
      await getOrchestras()
      await getDetails()
    })
    return () => (
      <div class={styles.storyOperation}>
        <OHeader title={forms.id ? '修改事迹' : '添加事迹'}>
          {{
            right: () =>
              forms.id && (
                <span
                  style={{ color: '#777777' }}
                  onClick={() => {
                    forms.delStatus = true
                  }}
                >
                  删除
                </span>
              )
          }}
        </OHeader>

        <CellGroup inset class={styles.cellGroup}>
          <Field
            inputAlign="right"
            label="所属乐团"
            modelValue={forms.selectOrchestra.text}
            placeholder="请选择所属乐团"
            onClick={() => {
              forms.orchestraStatus = true
            }}
            readonly
            isLink
          />
          <Field
            inputAlign="right"
            label="事迹日期"
            modelValue={forms.createTime ? dayjs(forms.createTime).format('YYYY-MM-DD') : ''}
            placeholder="请选择事迹日期"
            onClick={() => {
              forms.createTimeStatus = true
            }}
            readonly
            isLink
            class={styles.inputForm}
          />
        </CellGroup>

        <CellGroup inset class={styles.cellGroup}>
          <Cell title="事迹内容">
            {{
              title: () => (
                <div class={styles.title}>
                  <div class={styles.name}>事迹内容</div>
                  <div class={styles.nums}>{forms.content.length || 0}/200</div>
                </div>
              ),
              label: () => (
                <Field
                  style={{ padding: '0', marginTop: '12px' }}
                  placeholder="请输入乐团事迹内容"
                  type="textarea"
                  rows={3}
                  v-model={forms.content}
                  maxlength={200}
                />
              )
            }}
          </Cell>
        </CellGroup>

        <CellGroup inset class={styles.cellGroup}>
          <Cell title="事迹资料类型" center>
            {{
              value: () => (
                <RadioGroup
                  checked-color="#FF8057"
                  v-model={forms.storyType}
                  direction="horizontal"
                >
                  <Radio class={styles.radioItem} name={'IMAGE'}>
                    图片
                  </Radio>
                  <Radio class={styles.radioItem} name={'VIDEO'}>
                    视频
                  </Radio>
                </RadioGroup>
              )
            }}
          </Cell>
          {forms.storyType === 'IMAGE' && (
            <Cell center>
              {{
                title: () => (
                  <OUploadAll
                    style={{ marginBottom: '12px' }}
                    v-model:modelValue={forms.attachments}
                    maxCount={9}
                    uploadIcon={iconUpload}
                  />
                )
              }}
            </Cell>
          )}
          {forms.storyType === 'VIDEO' && (
            <Cell center titleStyle={{ display: 'flex' }}>
              {{
                title: () => (
                  <>
                    <OUploadAll
                      style={{ marginBottom: '12px' }}
                      v-model:modelValue={forms.video}
                      accept="video/*"
                      native={browser().isApp}
                      uploadType="VIDEO"
                      uploadIcon={iconUploadVideo}
                      deletable={false}
                    />

                    <OUploadAll
                      deletable={false}
                      style={{ marginBottom: '12px' }}
                      v-model:modelValue={forms.videoCover}
                      uploadIcon={iconUploadVideoCover}
                    />
                  </>
                )
              }}
            </Cell>
          )}
        </CellGroup>

        <OSticky position="bottom">
          <div class={'btnGroup'}>
            <Button round block type="primary" onClick={onSumbit}>
              保存
            </Button>
          </div>
        </OSticky>

        <Popup v-model:show={forms.createTimeStatus} position="bottom" round>
          <DatePicker
            maxDate={new Date()}
            v-model={forms.currentDate}
            onConfirm={(val: any) => {
              const selectedValues = val.selectedValues.join('-')
              forms.createTime = dayjs(selectedValues).toDate()
              forms.createTimeStatus = false
            }}
          />
        </Popup>

        <Popup v-model:show={forms.orchestraStatus} position="bottom" round>
          <Picker
            columns={forms.orchestraList}
            onCancel={() => (forms.orchestraStatus = false)}
            onConfirm={(val: any) => {
              forms.selectOrchestra = val.selectedOptions[0]
              forms.orchestraStatus = false
            }}
          />
        </Popup>

        <ODialog
          v-model:show={forms.delStatus}
          title="删除事迹"
          messageAlign="left"
          message="删除后学生将无法再看到本条事迹确认要删除吗？"
          showCancelButton
          onConfirm={onConfirm}
        ></ODialog>
      </div>
    )
  }
})
