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: true,
      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;
    };

    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 = () => {
      //
      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';
              }}
            />
          </div>
          <div class={[styles.btnItem, styles.block]}>
            <span class={[styles.btnTitle]}>
              <span>*</span>课件乐器
            </span>
            {/* <NSelect
              status={checkForms.value[1]}
              placeholder="请选择声部（可多选）"
              class={styles.btnSubjectList}
              options={prepareStore.getSubjectList}
              labelField="name"
              valueField="id"
              multiple
              maxTagCount={2}
              size="small"
              v-model:value={forms.subjects}
              clearable
              v-slots={{
                action: () => (
                  <>
                    <NButton
                      text
                      style=" --n-width: 100% "
                      size="small"
                      onClick={() => chioseAll(prepareStore.getSubjectList)}>
                      全选
                    </NButton>
                  </>
                )
              }}
              onUpdate:value={() => {
                checkForms.value[1] = forms.subjects?.length > 0 ? '' : 'error';
              }}
            /> */}
            <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';
              }}
              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} />
          </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}
                    />
                  ),
                  default: () =>
                    '为尊重课件原作者，在“相关课件”中添加的课件不支持公开'
                }}
              </NTooltip>
            ) : (
              <NSwitch
                v-model:value={forms.openFlag}
                disabled={!forms.openFlagEnable}
              />
            )}
          </div>
        </div>
      </>
    );
  }
});
