import { defineComponent, reactive } from 'vue';
import styles from './index.module.less';
import MHeader from '@/components/m-header';
import {
  Button,
  Cell,
  CellGroup,
  Field,
  Icon,
  Image,
  Popup,
  showConfirmDialog,
  showToast
} from 'vant';
import { postMessage } from '@/helpers/native-message';
import MUploader from '@/components/m-uploader';
import MPopup from '@/components/m-popup';
import SelectSend from './select-send';
import iconUploader from './images/icon-uploader.png';
import iconClose from '@/common/images/icon-upload-close2.png';
import iconContent from './images/icon-content.png';
import iconFile from './images/icon-file.png';
import iconUsers from './images/icon-users.png';

// import badge1 from './images/badge-1.png';
// import class1 from './images/1.png';
import MSticky from '@/components/m-sticky';
import request from '@/helpers/request';
import { useRouter } from 'vue-router';
import { formatterImage } from './components/contacts';

export default defineComponent({
  name: 'mass-message',
  setup() {
    const router = useRouter();
    const forms = reactive({
      messageContent: '',
      fileUrl: [] as any,
      selectStatus: false,
      receives: [] as any[],
      selectObject: {} as any,
      deleteStatus: false,
      deleteObject: {} as any
    });

    const onClose = (item: any) => {
      // showConfirmDialog({
      //   title: '提示',
      //   message: '您是否删除该数据'
      // }).then(() => {
      //
      const selectList = forms.selectObject;
      if (item.receiveType === 'GROUPCHAT') {
        const tempClass = selectList.groupChat || [];
        const sIndex = tempClass.findIndex(
          (child: any) => child.id === item.receiveId
        );
        tempClass.splice(sIndex, 1);
      } else if (item.receiveType === 'CONTACTS') {
        const tempSchool = selectList.contacts || [];
        const sIndex = tempSchool.findIndex(
          (child: any) => child.id === item.receiveId
        );
        tempSchool.splice(sIndex, 1);
      }
      forms.selectObject = selectList;

      const index = forms.receives.findIndex(
        (child: any) => child.receiveId === item.receiveId
      );
      forms.receives.splice(index, 1);

      forms.deleteStatus = false;
      // });
    };

    const checkForms = () => {
      if (!forms.messageContent) {
        showToast('请输入消息内容');
        return false;
      }

      if (
        forms.messageContent.length < 3 &&
        forms.messageContent.length > 150
      ) {
        showToast('消息内容长度为3~150个字');
        return false;
      }

      if (forms.receives.length <= 0) {
        showToast('请选择发送对象');
        return;
      }
      return true;
    };
    const onSubmit = async () => {
      try {
        if (!checkForms()) return;
        const targetIds = forms.selectObject.groupChat?.map(
          (item: any) => item.id
        );
        const userTargetIds = forms.selectObject.contacts?.map(
          (item: any) => item.id
        );
        await request.post('/api-web/imSendGroupMessage/schoolSend', {
          hideLoading: false,
          data: {
            messageContent: forms.messageContent,
            messageType: forms.fileUrl.length > 0 ? 'IMG' : 'TXT',
            sendType: 'NOW',
            fileUrl: forms.fileUrl.join(','),
            targetIds: targetIds.join(','),
            userTargetIds: userTargetIds.join(',')
          }
        });

        postMessage({ api: 'back' });
      } catch {
        //
      }
    };

    return () => (
      <div class={styles['mass-message']}>
        <MHeader />

        <CellGroup inset class={styles.cellGroup}>
          <Cell title="群发内容">
            {{
              title: () => (
                <div class={styles.title}>
                  <Icon name={iconContent} class={styles.iconImg} />
                  群发内容
                </div>
              ),
              label: () => (
                <Field
                  class={styles.content}
                  placeholder="请输入您的消息内容"
                  v-model={forms.messageContent}
                  type="textarea"
                  rows={3}
                  showWordLimit
                  maxlength={150}
                />
              )
            }}
          </Cell>
        </CellGroup>

        <CellGroup inset class={styles.cellGroup}>
          <Cell title="上传附件">
            {{
              title: () => (
                <div class={styles.title}>
                  <Icon name={iconFile} class={styles.iconImg} />
                  上传附件
                </div>
              ),
              label: () => (
                <MUploader
                  v-model:modelValue={forms.fileUrl}
                  maxCount={1}
                  native
                  uploadIcon={iconUploader}
                />
              )
            }}
          </Cell>
        </CellGroup>
        <CellGroup inset class={styles.cellGroup}>
          <Field
            label="发送对象"
            readonly
            inputAlign="right"
            class={styles.sendObjPlaceholder}
            placeholder={'请选择发送对象'}
            isLink
            border={false}
            onClick={() => {
              forms.selectStatus = true;
            }}>
            {{
              label: () => (
                <div class={styles.title} style={{ paddingBottom: '0' }}>
                  <Icon name={iconUsers} class={styles.iconImg} />
                  发送对象
                </div>
              )
            }}
          </Field>

          {forms.receives.map((item: any) => (
            <Cell center border={false}>
              {{
                icon: () => (
                  <Image src={item.avatar} class={styles.imgLogo} fit="cover" />
                ),
                title: () => (
                  <div class={styles.infos}>
                    <div class={styles.infoTitle}>
                      {item.receiveName}
                      {item.roleType && (
                        <img
                          src={formatterImage(item.roleType)}
                          class={[
                            styles.iconBadge,
                            item.roleType === 'SCHOOLMASTER'
                              ? styles.iconBadge2
                              : ''
                          ]}
                        />
                      )}
                    </div>
                    <div class={styles.infoContent}>{item.receiveText}</div>
                  </div>
                ),
                'right-icon': () => (
                  <Icon
                    name={iconClose}
                    class={styles.infoClose}
                    onClick={() => {
                      forms.deleteStatus = true;
                      forms.deleteObject = item || {};
                    }}
                  />
                )
              }}
            </Cell>
          ))}
        </CellGroup>

        <MSticky position="bottom">
          <div class={['btnGroupFixed', styles.bottonGroup]}>
            <Button type="primary" round block onClick={onSubmit}>
              发送
            </Button>
          </div>
        </MSticky>

        <MPopup v-model:modelValue={forms.selectStatus}>
          <SelectSend
            v-model:selectObject={forms.selectObject}
            onClose={() => (forms.selectStatus = false)}
            onConfirm={(val: any) => {
              const groupChat = val.groupChat;
              const contacts = val.contacts;
              const tempList: any = [];
              // console.log(groupChat, contacts, tempList);
              groupChat.forEach((item: any) => {
                tempList.push({
                  receiveType: 'GROUPCHAT',
                  receiveId: item.id,
                  receiveName: item.value,
                  receiveText: item.text,
                  roleType: item.roleType,
                  avatar: item.avatar
                });
              });

              contacts.forEach((item: any) => {
                tempList.push({
                  receiveType: 'CONTACTS',
                  receiveId: item.id,
                  receiveName: item.value,
                  receiveText: item.text,
                  roleType: item.roleType,
                  avatar: item.avatar
                });
              });
              forms.receives = tempList;
            }}
          />
        </MPopup>

        {/* 剔除对象提示 */}
        <Popup v-model:show={forms.deleteStatus} round style={{ width: '82%' }}>
          <div class={styles.popupContainer}>
            <h2 class={styles.popupTitle}>剔除对象</h2>
            <div class={styles.popupContent}>
              <p class={styles.tipContent}>
                请确认是否剔除{forms.deleteObject.receiveName}
              </p>
            </div>
            <div class={['btnGroupPopup']}>
              <Button round onClick={() => (forms.deleteStatus = false)}>
                取消
              </Button>
              <Button
                type="primary"
                round
                onClick={() => {
                  onClose(forms.deleteObject);
                }}>
                确定
              </Button>
            </div>
          </div>
        </Popup>
      </div>
    );
  }
});
