import { defineComponent, onMounted, reactive } from 'vue';
import styles from './site-settings.module.less';
import MSticky from '@/components/m-sticky';
import MHeader from '@/components/m-header';
import {
  Button,
  Cell,
  CellGroup,
  Field,
  Icon,
  Image,
  List,
  Picker,
  Popup,
  showToast
} from 'vant';
import iconMusic from '@/common/images/icon-music.png';
import iconTeacher from '@/common/images/icon-teacher-default.png';
import iconEdit from '@/common/images/icon-edit.png';
import SkeletonSettingsModal from './skeleton-settings-modal';
import MFullRefresh from '@/components/m-full-refresh';
import request from '@/helpers/request';
import MEmpty from '@/components/m-empty';

export default defineComponent({
  name: 'site-setting',
  setup() {
    const forms = reactive({
      showPopup: false,
      showOrchestraPopup: false,
      siteName: '',
      orchestraName: '全部乐团',
      orchestraColumns: [{ text: '全部乐团', value: '' }], //
      listState: {
        dataShow: true, // 判断是否有数据
        loading: true,
        finished: false,
        refreshing: false
      },
      params: {
        musicGroupId: null,
        page: 1,
        rows: 20
      },
      isClick: false,
      list: [],
      selectSite: {} as any //
    });

    const onEdit = (item: any) => {
      forms.selectSite = item;
      forms.siteName = item.teachingPoint;
      forms.showPopup = true;
    };

    const onSubmitUpdateSite = async () => {
      try {
        if (!forms.siteName) {
          showToast('请输入场地名称');
          return;
        }
        await request.post('/api-web/classGroup/teachingPoint', {
          hideLoading: false,
          data: {
            classGroupId: forms.selectSite.classGroupId,
            teachingPoint: forms.siteName
          }
        });
        forms.showPopup = false;
        forms.list = [];
        onRefresh();
      } catch {
        //
      }
    };

    const getList = async () => {
      try {
        if (forms.isClick) return;
        forms.isClick = true;
        const { data } = await request.post(
          '/api-web/classGroup/teachingPointClass',
          {
            data: forms.params
          }
        );
        const result = data || {};
        // 判断是否有数据
        if (forms.listState.refreshing) {
          forms.list = result.rows || [];
        } else {
          forms.list = forms.list.concat(result.rows || []);
        }
        forms.listState.finished = result.pageNo >= result.totalPage;
        forms.params.page = result.pageNo + 1;
      } catch {
        forms.listState.finished = true;
      } finally {
        forms.listState.dataShow = forms.list.length > 0;
        forms.listState.refreshing = false;
        forms.listState.loading = false;
        forms.isClick = false;
      }
    };

    const onRefresh = () => {
      forms.params.page = 1;
      getList();
    };

    // 乐团列表
    const musicGroupPage = async () => {
      try {
        const { data } = await request.get(
          '/api-web/cooperationOrgan/musicGroupPage'
        );
        (data || []).forEach((item: any) => {
          forms.orchestraColumns.push({
            text: item.name,
            value: item.id
          });
        });
      } catch {
        //
      }
    };

    onMounted(() => {
      musicGroupPage();
      getList();
    });
    return () => (
      <div class={styles.siteSetting}>
        <MSticky position="top">
          <MHeader />

          <div class={styles.searchGroup}>
            <div
              class={styles.searchItem}
              onClick={() => (forms.showOrchestraPopup = true)}>
              <span>{forms.orchestraName}</span>
            </div>
          </div>
        </MSticky>

        <SkeletonSettingsModal v-model:show={forms.listState.loading}>
          <MFullRefresh
            v-model:modelValue={forms.listState.refreshing}
            onRefresh={() => onRefresh()}
            style={{
              minHeight: `calc(100vh - var(--header-height))`
            }}>
            <List
              finished={forms.listState.finished}
              finishedText=" "
              style={{ overflow: 'hidden' }}
              onLoad={getList}
              immediateCheck={false}>
              {forms.listState.dataShow ? (
                forms.list.map((item: any) => (
                  <CellGroup class={styles.cellGroup} border={false}>
                    <Cell border={false} center>
                      {{
                        title: () => (
                          <div class={styles.orchestraName}>
                            <img src={iconMusic} class={styles.iconMusic} />
                            <p class={styles.overhide}>{item.musicGroupName}</p>
                          </div>
                        ),
                        default: () => (
                          <div
                            class={styles.address}
                            onClick={() => onEdit(item)}>
                            <p
                              class={[
                                styles.overhide,
                                item.teachingPoint ? '' : styles.red
                              ]}>
                              {item.teachingPoint || '未设置场地'}
                            </p>
                            <Icon name={iconEdit} class={styles.iconEdit} />
                          </div>
                        )
                      }}
                    </Cell>
                    <Cell center class={styles.username}>
                      {{
                        icon: () => (
                          <Image
                            src={item.teacherAvatar || iconTeacher}
                            class={styles.iconTeacher}
                            fit="cover"
                          />
                        ),
                        title: () => (
                          <div>
                            <div class={styles.classname}>
                              {item.classGroupName}
                            </div>
                            <div class={styles.name}>{item.teacherName}</div>
                          </div>
                        )
                      }}
                    </Cell>
                  </CellGroup>
                ))
              ) : (
                <MEmpty
                  style={{
                    minHeight: `calc(100vh - var(--header-height))`
                  }}
                  description="暂无数据"
                />
              )}
            </List>
          </MFullRefresh>
        </SkeletonSettingsModal>

        <Popup
          v-model:show={forms.showPopup}
          round
          onClose={() => {
            forms.siteName = '';
            forms.selectSite = {};
          }}>
          <div class={styles.popupContainer}>
            <h2>设置场地</h2>
            <Field
              placeholder="请输入场地名称"
              v-model={forms.siteName}
              border={false}
              class={styles.field}
              maxlength={15}
            />
            <div class={['btnGroupPopup']}>
              <Button
                round
                onClick={() => {
                  forms.showPopup = false;
                }}>
                取消
              </Button>
              <Button type="primary" round onClick={onSubmitUpdateSite}>
                确定
              </Button>
            </div>
          </div>
        </Popup>

        <Popup v-model:show={forms.showOrchestraPopup} round position="bottom">
          <Picker
            columns={forms.orchestraColumns}
            onCancel={() => (forms.showOrchestraPopup = false)}
            onConfirm={({ selectedOptions }: any) => {
              forms.showOrchestraPopup = false;
              const option = selectedOptions[0];
              forms.orchestraName = option.text;
              forms.params.musicGroupId = option.value;
              forms.list = [];
              forms.listState.dataShow = true;
              onRefresh();
            }}
          />
        </Popup>
      </div>
    );
  }
});
