import OPopup from '@/components/o-popup'
import { sendType } from '@/constant'
import request from '@/helpers/request'
import { getOssUploadUrl } from '@/state'
import dayjs from 'dayjs'
import umiRequest from 'umi-request'
import {
  ActionSheet,
  Button,
  Cell,
  CellGroup,
  closeToast,
  DatePicker,
  Field,
  Icon,
  Image,
  PickerGroup,
  Popup,
  showLoadingToast,
  showToast,
  TimePicker,
  Uploader
} from 'vant'
import { computed, defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import SelectSned from './select-sned'
import iconStudent from '@common/images/icon_student.png'
import iconTeacher from '@common/images/icon_teacher.png'
import iconJiaoFu from '@common/images/icon_jiaofu.png'
import ODialog from '@/components/o-dialog'
import OSticky from '@/components/o-sticky'
import { useRoute, useRouter } from 'vue-router'

export default defineComponent({
  name: 'create-message',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const forms = reactive({
      id: route.query.id,
      type: 'ADD',
      bucket: 'daya',
      sendStatus: false,
      sendType: 'IMMEDIATELY' as any,
      textMessage: null,
      sendTime: null as any,
      sendTimeStatus: false,
      maxDate: dayjs(new Date()).add(60, 'day').toDate(),
      currentDate: [],
      currentTime: [dayjs().format('HH'), dayjs().format('mm')],
      attachments: [] as any, //群发消息附件
      receives: [] as any, // 群发消息对象
      selectStatus: false,
      selectList: {} as any, // 选中发送的信息
      delSelectItem: {} as any,
      delStatus: false,
      sureLoading: false,
      updateLoading: false,
      closeLoading: 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 = tempName && tempName.replace(/ /gi, '_')
        const key = new Date().getTime() + fileName
        showLoadingToast({
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0
        })
        const res = await request.post(signUrl, {
          hideLoading: true,
          data: {
            filename: fileName,
            bucketName: forms.bucket,
            postData: {
              filename: fileName,
              acl: 'public-read',
              key: key,
              unknowValueField: []
            }
          }
        })
        // setTimeout(() => {

        // }, 100)
        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(forms.bucket), {
          method: 'POST',
          data: formData
        })
        // console.log(getOssUploadUrl(state.bucket) + key)
        const uploadUrl = getOssUploadUrl(forms.bucket) + key
        closeToast()

        // state.fileList.push({ url: uploadUrl })
        files.url = uploadUrl
        files.status = 'done'
      } catch (error) {
        files.status = 'failed'
        closeToast()
        console.log(error, 'uploadFile')
      }
    }

    const onSubmit = async () => {
      try {
        if (!forms.sendType) {
          showToast('请选择发送方式')
          return
        }

        if (!forms.textMessage) {
          showToast('请输入发送内容')
          return
        }

        if (forms.receives.length <= 0) {
          showToast('请选择发送对象')
          return
        }
        const tempAttachments: any = []
        forms.attachments.forEach((item: any) => {
          tempAttachments.push({
            imgUrl: item.url,
            imgMessage: item.url
          })
        })

        const tempReceives: any = []
        forms.receives.forEach((item: any) => {
          tempReceives.push({
            receiveType: item.receiveType,
            receiveId: item.receiveId
          })
        })

        const params: any = {
          sendType: forms.sendType,
          textMessage: forms.textMessage,
          attachments: tempAttachments,
          receives: tempReceives,
          sendTime: forms.sendTime
        }

        console.log(params, 'params')
        if (forms.id) {
          forms.updateLoading = true
        } else {
          forms.sureLoading = true
        }

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

        setTimeout(() => {
          showToast(forms.id ? '修改成功' : '添加成功')
        }, 100)
        setTimeout(() => {
          router.replace('/mass-message')
          forms.sureLoading = false
          forms.updateLoading = false
        }, 1100)
      } catch {
        //
        forms.sureLoading = false
        forms.updateLoading = false
      }
    }

    const getDetails = async () => {
      try {
        if (!forms.id) return
        const { data } = await request.get('/api-school/imMessageBatchSending/detail/' + forms.id)
        forms.sendType = data.sendType
        forms.textMessage = data.textMessage
        forms.sendTime = data.sendTime
        forms.type = data.sendStatus
        const receives = data.receives || []
        const tempList: any = {
          class: [] as any,
          teacher: [] as any,
          student: [] as any,
          school: [] as any
        }
        receives.forEach((item: any) => {
          const temp = {
            receiveType: item.receiveType,
            receiveId: item.receiveId,
            receiveName: item.receiveName,
            avatar: item.avatar
          }
          forms.receives.push(temp)
          const temp2 = {
            id: item.receiveId,
            value: item.receiveName,
            avatar: item.avatar
          }
          if (item.receiveType === 'CLASS') {
            tempList.class.push(temp2)
          } else if (item.receiveType === 'STUDENT') {
            tempList.student.push(temp2)
          } else if (item.receiveType === 'TEACHER') {
            tempList.teacher.push(temp2)
          } else if (item.receiveType === 'SCHOOL') {
            tempList.school.push(temp2)
          }
        })
        forms.selectList = tempList
        const attachments = data.attachments || []
        const tempAtt: any = []
        attachments.forEach((item: any) => {
          tempAtt.push({
            url: item.imgUrl || item.imgMessage
          })
        })
        forms.attachments = tempAtt
      } catch (e: any) {
        //
        console.log(e, 'e')
      }
    }

    // 判断是否是查看
    const formDisabled = computed(() => forms.type === 'SEND')

    const onClose = async () => {
      try {
        forms.closeLoading = true
        await request.post('/api-school/imMessageBatchSending/remove', {
          requestType: 'form',
          data: {
            id: forms.id
          }
        })
        setTimeout(() => {
          showToast('撤销成功')
        }, 100)
        setTimeout(() => {
          router.replace('/mass-message')
          forms.closeLoading = false
        }, 1100)
      } catch {
        //
        forms.closeLoading = false
      }
    }

    onMounted(() => {
      getDetails()
    })

    return () => (
      <div class={styles['create-message']}>
        {/* <OHeader /> */}
        <CellGroup inset class={styles.cellGroup}>
          <Field
            inputAlign="right"
            label="发送方式"
            modelValue={sendType[forms.sendType]}
            placeholder="请选择发送方式"
            onClick={() => {
              if (formDisabled.value) return
              forms.sendStatus = true
            }}
            readonly
            isLink={!formDisabled.value}
          />
          {/* 定时发送才会有时间 */}
          {forms.sendType === 'SCHEDULED' && (
            <Field
              inputAlign="right"
              label="发送时间"
              modelValue={forms.sendTime}
              placeholder="请选择发送时间"
              onClick={() => {
                if (formDisabled.value) return
                forms.sendTimeStatus = true
              }}
              readonly
              isLink
            />
          )}
          <Cell title="发送内容">
            {{
              label: () => (
                <Field
                  style={{ padding: '0', marginTop: '12px' }}
                  placeholder="请输入发送内容"
                  v-model={forms.textMessage}
                  type="textarea"
                  rows={3}
                  showWordLimit
                  maxlength={400}
                  readonly={formDisabled.value}
                />
              )
            }}
          </Cell>
          <Cell title="上传附件">
            {{
              label: () => (
                <Uploader
                  style={{ marginTop: '12px' }}
                  v-model={forms.attachments}
                  afterRead={afterRead}
                  beforeRead={beforeRead}
                  beforeDelete={beforeDelete}
                  accept="image/*"
                  maxCount={9}
                  disabled={formDisabled.value}
                />
              )
            }}
          </Cell>

          <Field
            label="发送对象"
            readonly
            inputAlign="right"
            placeholder={formDisabled.value ? '' : '请选择发送对象'}
            isLink={!formDisabled.value}
            border={false}
            onClick={() => {
              if (formDisabled.value) return
              forms.selectStatus = true
            }}
          />
          {forms.receives.map((item: any) => {
            let img: any = iconStudent
            if (item.receiveType === 'CLASS') {
              img = iconJiaoFu
            } else if (item.receiveType === 'STUDENT') {
              img = iconStudent
            } else if (item.receiveType === 'TEACHER' || item.receiveType === 'SCHOOL') {
              img = iconTeacher
            }
            return (
              <Cell class={styles.receives} title={item.receiveName} center border={false}>
                {{
                  icon: () => <Image class={styles.img} src={item.avatar || img} />,
                  extra: () =>
                    !formDisabled.value && (
                      <Icon
                        name="clear"
                        color="#d7d7d7"
                        size={20}
                        onClick={() => {
                          forms.delSelectItem = item
                          forms.delStatus = true
                        }}
                      />
                    )
                }}
              </Cell>
            )
          })}
        </CellGroup>

        <OSticky position="bottom">
          {forms.type === 'ADD' && (
            <div class={'btnGroup'}>
              <Button round block type="primary" onClick={onSubmit} disabled={forms.sureLoading}>
                确认发送
              </Button>
            </div>
          )}

          {forms.type === 'WAIT' && (
            <div class={['btnGroup', 'btnMore']}>
              <Button round type="primary" onClick={onSubmit} disabled={forms.updateLoading}>
                修改
              </Button>
              <Button round color="#64A9FF" onClick={onClose} disabled={forms.closeLoading}>
                撤销
              </Button>
            </div>
          )}
        </OSticky>

        <ActionSheet
          v-model:show={forms.sendStatus}
          cancelText="取消"
          actions={
            [
              { name: '即时发送', value: 'IMMEDIATELY' },
              { name: '定时发送', value: 'SCHEDULED' }
            ] as any
          }
          onSelect={(val: any) => {
            console.log(val)
            forms.sendType = val.value
            forms.sendStatus = false
          }}
        />

        <Popup v-model:show={forms.sendTimeStatus} position="bottom" round>
          <PickerGroup
            title="发送时间"
            tabs={['选择日期', '选择时间']}
            onCancel={() => (forms.sendTimeStatus = false)}
            onConfirm={(val: any) => {
              const first = val[0].selectedValues.join('-')
              const second = val[1].selectedValues.join(':')
              forms.sendTime = dayjs(first + ' ' + second).format('YYYY-MM-DD HH:mm:ss')
              forms.sendTimeStatus = false
            }}
          >
            <DatePicker minDate={new Date()} maxDate={forms.maxDate} v-model={forms.currentDate} />
            <TimePicker v-model={forms.currentTime} />
          </PickerGroup>
        </Popup>

        <OPopup v-model:modelValue={forms.selectStatus}>
          <SelectSned
            v-model:selectList={forms.selectList}
            onClose={() => (forms.selectStatus = false)}
            onConfirm={(val: any) => {
              const classList = val.class || []
              const studentList = val.student || []
              const teacherList = val.teacher || []
              const schoolList = val.school || []

              const tempList: any = []
              classList.forEach((item: any) => {
                tempList.push({
                  receiveType: 'CLASS',
                  receiveId: item.id,
                  receiveName: item.value,
                  avatar: item.avatar
                })
              })
              studentList.forEach((item: any) => {
                tempList.push({
                  receiveType: 'STUDENT',
                  receiveId: item.id,
                  receiveName: item.value,
                  avatar: item.avatar
                })
              })
              teacherList.forEach((item: any) => {
                tempList.push({
                  receiveType: 'TEACHER',
                  receiveId: item.id,
                  receiveName: item.value,
                  avatar: item.avatar
                })
              })
              schoolList.forEach((item: any) => {
                tempList.push({
                  receiveType: 'SCHOOL',
                  receiveId: item.id,
                  receiveName: item.value,
                  avatar: item.avatar
                })
              })

              forms.receives = tempList
            }}
          />
        </OPopup>

        <ODialog
          v-model:show={forms.delStatus}
          showCancelButton
          message="您是否删除该数据"
          onConfirm={() => {
            const selectList = forms.selectList
            if (forms.delSelectItem.receiveType === 'CLASS') {
              const tempClass = selectList.class || []
              const sIndex = tempClass.findIndex(
                (item: any) => item.id === forms.delSelectItem.receiveId
              )
              tempClass.splice(sIndex, 1)
            } else if (forms.delSelectItem.receiveType === 'SCHOOL') {
              const tempSchool = selectList.school || []
              const sIndex = tempSchool.findIndex(
                (item: any) => item.id === forms.delSelectItem.receiveId
              )
              tempSchool.splice(sIndex, 1)
            } else if (forms.delSelectItem.receiveType === 'TEACHER') {
              const tempTeacher = selectList.teacher || []
              const sIndex = tempTeacher.findIndex(
                (item: any) => item.id === forms.delSelectItem.receiveId
              )
              tempTeacher.splice(sIndex, 1)
            } else if (forms.delSelectItem.receiveType === 'STUDENT') {
              const tempStudent = selectList.student || []
              const sIndex = tempStudent.findIndex(
                (item: any) => item.id === forms.delSelectItem.receiveId
              )
              tempStudent.splice(sIndex, 1)
            }
            forms.selectList = selectList
            console.log(forms.selectList, 'forms.selectList')

            const index = forms.receives.findIndex(
              (item: any) => item.receiveId === forms.delSelectItem.receiveId
            )
            forms.receives.splice(index, 1)
          }}
        />
      </div>
    )
  }
})
