import OPopup from '@/components/o-popup'
import { sendType } from '@/constant'
import request from '@/helpers/request'
import { getOssUploadUrl, state } from '@/state'
import dayjs from 'dayjs'
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'
import OActionSheet from '@/components/o-action-sheet'
import { formatterDatePicker } from '@/helpers/utils'
import OUploadAll from '@/components/o-upload-all'
import OHeader from '@/components/o-header'

export default defineComponent({
  name: 'create-message',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const forms = reactive({
      id: route.query.id,
      type: 'ADD',
      bucket: 'i-m',
      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,
      actions: [
        { name: '即时发送', value: 'IMMEDIATELY', selected: true },
        { name: '定时发送', value: 'SCHEDULED' }
      ]
    })

    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,
            imgMessage: item
          })
        })

        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', {
            hideLoading: false,
            data: params
          })
        } else {
          await request.post('/api-school/imMessageBatchSending/save', {
            hideLoading: false,
            data: params
          })
        }

        router.back()
        forms.sureLoading = false
        forms.updateLoading = false
      } 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(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',
          hideLoading: false,
          data: {
            id: forms.id
          }
        })
        setTimeout(() => {
          showToast('撤销成功')
        }, 100)
        setTimeout(() => {
          // router.replace('/mass-message')
          router.back()
          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}
            class={styles.inputForm}
          />
          {/* 定时发送才会有时间 */}
          {forms.sendType === 'SCHEDULED' && (
            <Field
              inputAlign="right"
              label="发送时间"
              modelValue={forms.sendTime}
              placeholder="请选择发送时间"
              onClick={() => {
                if (formDisabled.value) return
                forms.sendTimeStatus = true
              }}
              readonly
              isLink
              class={styles.inputForm}
            />
          )}
          <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: () => (
                <OUploadAll
                  v-model:modelValue={forms.attachments}
                  maxCount={9}
                  bucket={forms.bucket}
                  disabled={formDisabled.value}
                />
              )
            }}
          </Cell>

          <Field
            label="发送对象"
            readonly
            inputAlign="right"
            class={styles.sendObjPlaceholder}
            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>

        <OActionSheet
          v-model:show={forms.sendStatus}
          actions={forms.actions}
          onSelect={(val: any) => {
            forms.actions.forEach((child: any) => {
              child.selected = false
            })
            val.selected = true
            forms.sendType = val.value
            forms.sendStatus = false
          }}
        />

        <Popup
          v-model:show={forms.sendTimeStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}
        >
          <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}
              formatter={formatterDatePicker}
            />
            <TimePicker
              v-model={forms.currentTime}
              formatter={(type: any, option: any) => {
                if (type === 'hour') {
                  option.text += '时'
                }
                if (type === 'minute') {
                  option.text += '分'
                }
                return option
              }}
            />
          </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>
    )
  }
})
