import { Cell, Checkbox, CheckboxGroup, Icon, Image, Sticky } from 'vant';
import { defineComponent, onMounted, reactive, ref, watch } from 'vue';
import styles from '../index.module.less';
import badge1 from '../images/badge-1.png';
import badge2 from '../images/badge-2.png';
import badge3 from '../images/badge-3.png';
import badge4 from '../images/badge-4.png';
import badge5 from '../images/badge-5.png';
import badge6 from '../images/badge-6.png';
import badge7 from '../images/badge-7.png';
import badge8 from '../images/badge-8.png';
import MSearch from '@/components/m-search';
import activeButtonIcon from '@/common/images/icon-check-active.png';
import inactiveButtonIcon from '@/common/images/icon-check.png';
import iconStudent from '@/common/images/icon-student-default.png';
import iconTeacher from '@/common/images/icon-teacher-default.png';
import request from '@/helpers/request';
import MEmpty from '@/components/m-empty';

export const formatterImage = (type: string) => {
  let image: any = badge3;
  switch (type) {
    case 'SCHOOLMASTER':
      image = badge5;
      break;
    case 'ORCHESTRA_LEADER':
      image = badge1;
      break;
    case 'SCHOOL_LEADER':
      image = badge6;
      break;
    case 'SCHOOL_TEACHER':
      image = badge7;
      break;
    case 'ORCHESTRA_MANAGER':
      image = badge4;
      break;
    case 'ORCHESTRA_TEACHER':
      image = badge2;
      break;
    case 'MAINTENANCE_TECHNICIAN':
      image = badge8;
      break;
    case 'STUDENT':
      image = badge3;
      break;
  }
  return image;
};

export default defineComponent({
  name: 'contacts-modal',
  props: {
    height: {
      type: [Number],
      default: 0
    },
    bottomHeight: {
      type: [String, Number],
      default: 0
    },
    headerHeight: {
      type: [Number],
      default: 0
    },
    selectItem: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:selectItem'],
  setup(props, { emit }) {
    const checkboxRefs = ref([] as any);
    const forms = reactive({
      keyword: '',
      height: props.height,
      list: [],
      check: [] as any,
      dataShow: true
    });

    const onToggle = (index: number) => {
      //
      checkboxRefs.value[index].toggle();
      // console.log(forms.list, forms.check, 'forms.check');
      const list: any = [];
      forms.list.forEach((item: any) => {
        if (forms.check.includes(item.friendId)) {
          list.push({
            id: item.friendId,
            value: item.friendNickname,
            text: item.memo,
            roleType: item.roleType,
            avatar:
              item.friend.avatar ||
              (item.friend.userType === 'TEACHER' ? iconTeacher : iconStudent)
          });
        }
      });
      emit('update:selectItem', list);
    };

    watch(
      () => props.height,
      () => {
        forms.height = props.height;
      }
    );

    watch(
      () => props.selectItem,
      () => {
        initSelectItem();
      },
      { deep: true }
    );

    const initSelectItem = () => {
      const selectItem = props.selectItem || [];
      const temp: any = [];
      selectItem.forEach((item: any) => {
        temp.push(item.id);
      });
      forms.check = temp;
    };

    const getList = async () => {
      try {
        const { data } = await request.post(
          '/api-web/imGroup/schoolQueryFriendList',
          {
            data: {
              lockFlag: false,
              keyword: forms.keyword
            }
          }
        );
        forms.list = data || [];
      } catch {
        //
      } finally {
        forms.dataShow = forms.list.length > 0 ? true : false;
      }
    };

    onMounted(() => {
      getList();
    });
    return () => (
      <div
        style={{
          'min-height': `calc(100vh - ${props.headerHeight}px - ${forms.height}px - ${props.bottomHeight}px )`
        }}>
        <Sticky
          position="top"
          offsetTop={props.headerHeight + forms.height}
          style={{ width: '100%' }}>
          <MSearch
            placeholder="请输入联系人名称"
            onSearch={async (val: string) => {
              forms.keyword = val;
              forms.dataShow = true;
              await getList();
            }}
          />
        </Sticky>
        <CheckboxGroup v-model={forms.check}>
          {forms.dataShow ? (
            forms.list.map((item: any, index: number) => (
              <Cell
                center
                onClick={() => onToggle(index)}
                class={styles.popupCell}>
                {{
                  icon: () => (
                    <Image
                      src={
                        item.friend.avatar ||
                        (item.friend.userType === 'TEACHER'
                          ? iconTeacher
                          : iconStudent)
                      }
                      class={styles.imgLogo}
                      fit="cover"
                    />
                  ),
                  title: () => (
                    <div class={styles.infos}>
                      <div class={styles.infoTitle}>
                        {item.friendNickname}
                        <img
                          src={formatterImage(item.roleType)}
                          class={[
                            styles.iconBadge,
                            item.roleType === 'SCHOOLMASTER'
                              ? styles.iconBadge2
                              : ''
                          ]}
                        />
                      </div>
                      <div class={styles.infoContent}>{item.memo}</div>
                    </div>
                  ),
                  'right-icon': () => (
                    <Checkbox
                      name={item.friendId}
                      ref={e => (checkboxRefs.value[index] = e)}
                      onClick={(e: MouseEvent) => {
                        e.stopPropagation();
                        e.stopPropagation();
                        onToggle(index);
                      }}
                      v-slots={{
                        icon: (props: any) => (
                          <Icon
                            class={styles.boxStyle}
                            name={
                              props.checked
                                ? activeButtonIcon
                                : inactiveButtonIcon
                            }
                          />
                        )
                      }}
                    />
                  )
                }}
              </Cell>
            ))
          ) : (
            <MEmpty
              style={{
                minHeight: `calc(100vh - ${props.headerHeight}px - ${forms.height}px - ${props.bottomHeight}px - 100px)`
              }}
              description="暂无数据"
            />
          )}
        </CheckboxGroup>
      </div>
    );
  }
});
