import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NCascader,
  NInput,
  NSelect,
  NSwitch,
  NTooltip
} from 'naive-ui';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import { eventGlobal } from '/src/utils';
import { useCatchStore } from '/src/store/modules/catchData';
import deepClone from '/src/helpers/deep-clone';

export default defineComponent({
  name: 'courseware-head',
  setup(props, { emit, expose }) {
    const prepareStore = usePrepareStore();
    // 第一个课件名称，第二个课件声部
    const checkForms = ref<any[]>(['', '']);
    const subjectList = ref([] as any);
    const forms = reactive({
      subjects: [] as any,
      openFlagEnable: true, // 是否支持修改公开状态
      autoPlay: false,
      name: '',
      openFlag: false
    });

    // 全选
    const chioseAll = (list: any) => {
      // 全选
      const ids = [] as any;
      list.map((item: any) => {
        if (Array.isArray(item.instruments)) {
          item.instruments.forEach((c: any) => {
            ids.push(c.value);
          });
        }
      }) as any;
      // item.instrumentIds = ids;
      forms.subjects = ids;
      eventGlobal.emit('coursewareSubjectChange', forms.subjects)

      checkForms.value[1] = forms.subjects?.length > 0 ? '' : 'error';
    };

    const getForms = () => {
      return forms;
    };

    const updateDefaultInfo = (item: any) => {
      forms.subjects = item.subjects;
      forms.openFlagEnable = item.openFlagEnable;
      forms.autoPlay = item.autoPlay;
      forms.name = item.name;
      forms.openFlag = item.openFlag;
      updateSubjectList(item.subjects || []);
    };

    const checkCoursewareForm = (type: string = 'ALL') => {
      //
      if(type === 'name') {
        checkForms.value[0] = forms.name ? '' : 'error';
      } else if(type === "subject") {
        checkForms.value[1] = forms.subjects?.length > 0 ? '' : 'error';
      } else {
        checkForms.value[0] = forms.name ? '' : 'error';
        checkForms.value[1] = forms.subjects?.length > 0 ? '' : 'error';
      }
    };

    const updateSubjectList = (ids?: any[]) => {
      // 获取适用乐器编号 ，修改的乐器编号，集合
      ids = ids || [];
      const courseIds: any = [];
      prepareStore.getInstrumentList.forEach((item: any) => {
        if (Array.isArray(item.instruments)) {
          item.instruments.forEach((child: any) => {
            courseIds.push(child.id);
          });
        }
      });
      const allIds = [...new Set([...courseIds, ...ids])];

      const tempList: any = [];
      useCatchStore().getSubjectList.forEach((item: any) => {
        const temp = deepClone(item);
        temp.enableFlag = false;
        if (Array.isArray(temp.instruments)) {
          temp.instruments.forEach((child: any) => {
            child.enableFlag = false;
            if (allIds.includes(child.id)) {
              child.enableFlag = true;
              temp.enableFlag = true;
            }
          });
        }
        tempList.push(temp);
      });
      const tempSubjects: any[] = [];
      tempList.forEach((subject: any) => {
        if (subject.enableFlag) {
          const { instruments, ...r } = subject;

          if (instruments && instruments.length > 0) {
            const tempChild: any[] = [];
            instruments?.forEach((instrument: any) => {
              if (instrument.enableFlag) {
                tempChild.push(instrument);
              }
            });

            if (tempChild.length > 0)
              tempSubjects.push({ ...r, instruments: tempChild });
          }
        }
      });
      subjectList.value = tempSubjects;
    };

    onMounted(async () => {
      await useCatchStore().getSubjects();
      updateSubjectList();
      eventGlobal.on('updateCoursewareHeadInfo', updateDefaultInfo);

      eventGlobal.on('checkCoursewareForm', checkCoursewareForm);
    });

    expose({
      getForms
    });

    return () => (
      <>
        <div class={styles.headerTitle}>
          <i class={styles.iconBook}></i>
          <span>{prepareStore.getSelectName}</span>
        </div>

        <div class={styles.formContainer}>
          <div class={[styles.btnItem, styles.block]}>
            <span class={[styles.btnTitle]}>
              <span>*</span>课件名称
            </span>
            <NInput
              placeholder="请输入课件名称"
              v-model:value={forms.name}
              maxlength={20}
              clearable
              status={checkForms.value[0]}
              onUpdate:value={() => {
                checkForms.value[0] = forms.name ? '' : 'error';
                eventGlobal.emit('coursewareHeadSyncData', getForms())
              }}
            />
          </div>
          <div class={[styles.btnItem, styles.block]}>
            <span class={[styles.btnTitle]}>
              <span>*</span>适用乐器
            </span>
            <NCascader
              status={checkForms.value[1]}
              placeholder="请选择乐器（可多选）"
              class={styles.btnSubjectList}
              options={subjectList.value}
              checkStrategy="child"
              showPath={false}
              childrenField="instruments"
              expandTrigger="hover"
              labelField="name"
              valueField="id"
              clearable
              filterable
              multiple
              maxTagCount={1}
              v-model:value={forms.subjects}
              onUpdate:value={() => {
                checkForms.value[1] = forms.subjects?.length > 0 ? '' : 'error';
                // console.log(form)
                eventGlobal.emit('coursewareSubjectChange', forms.subjects)
              }}
              v-slots={{
                action: () => (
                  <>
                    <NButton
                      text
                      style=" --n-width: 100% "
                      size="small"
                      onClick={() => chioseAll(subjectList.value)}>
                      全选
                    </NButton>
                  </>
                )
              }}
            />
          </div>
          <div class={styles.btnItem}>
            <span class={styles.btnTitle}>
              自动播放
              <NTooltip style={{ maxWidth: '200px' }} showArrow={false}>
                {{
                  trigger: () => <i class={styles.iconQuestion}></i>,
                  default: () =>
                    '开启自动播放后，课件内视频、音频资源将自动播放'
                }}
              </NTooltip>
            </span>

            <NSwitch v-model:value={forms.autoPlay} onUpdate:value={() => {
              eventGlobal.emit('coursewareHeadSyncData', getForms())
            }} />
          </div>
          <div class={styles.btnItem}>
            <span class={styles.btnTitle}>
              公开课件
              <NTooltip style={{ maxWidth: '200px' }} showArrow={false}>
                {{
                  trigger: () => <i class={styles.iconQuestion}></i>,
                  default: () => '公开课件后，其它老师可以使用该课件上课'
                }}
              </NTooltip>
            </span>
            {!forms.openFlagEnable ? (
              <NTooltip style={{ maxWidth: '200px' }} showArrow={false}>
                {{
                  trigger: () => (
                    <NSwitch
                      v-model:value={forms.openFlag}
                      disabled={!forms.openFlagEnable}
                      onUpdate:value={() => {
                        eventGlobal.emit('coursewareHeadSyncData', getForms())
                      }}
                    />
                  ),
                  default: () =>
                    '为尊重课件原作者，在“相关课件”中添加的课件不支持公开'
                }}
              </NTooltip>
            ) : (
              <NSwitch
                v-model:value={forms.openFlag}
                disabled={!forms.openFlagEnable}
                onUpdate:value={() => {
                  eventGlobal.emit('coursewareHeadSyncData', getForms())
                }}
              />
            )}
          </div>
        </div>
      </>
    );
  }
});
