import request from '@/helpers/request';
import { state } from '@/state';
import { Button, Cell, Collapse, CollapseItem, Popup, showToast } from 'vant';
import { defineComponent, onMounted, reactive, TransitionGroup } from 'vue';
import styles from './index.module.less';
import { useRoute } from 'vue-router';
import { postMessage } from '@/helpers/native-message';
import iconQuestion from './image/icon-question.png';
import iconNoCheck from './image/icon-nocheck.png';
import iconImm from './image/icon-imm.png';
import iconCheck from './image/icon-check.png';
import iconCheckDisabled from './image/icon-check-disabled.png';

import OEmpty from '@/components/o-empty';
import iconList from './image/icon-list.png';
import OHeader from '@/components/o-header';
import { useEventListener } from '@vant/use';
import OLoading from '@/components/o-loading';
import OSticky from '@/components/o-sticky';
import ChildNode, { onMenuChange, onParentChangeStatus } from './child-node';
export default defineComponent({
  name: 'courseList',
  setup() {
    const route = useRoute();
    // const router = useRouter();
    // const browserInfo = browser();
    const data = reactive({
      titleOpacity: 0,
      catchStatus: false,
      catchItem: {} as any,
      loading: true,
      detail: {
        cover: '',
        name: '',
        des: ''
      },
      maxAddCourseware: 0,
      list: [] as any,
      ruleStatus: false,
      isDownloading: false, // 是否在下载资源
      parentCollapse: '' as any,
      childrenCollapse: '' as any,
      disabledIds: [] as any
    });

    /** 获取课件详情 */
    const getDetail = async () => {
      const res: any = await request.get(
        `${state.platformApi}/lessonCourseware/getLessonCoursewareDetail/${route.query.id}`
      );
      if (res?.data) {
        data.detail.cover = res.data.coverImg;
        data.detail.name = res.data.name;
        data.detail.des = res.data.lessonTargetDesc;
      }
    };
    const getList = async () => {
      data.loading = true;
      try {
        const res: any = await request.get(
          state.platformApi +
            '/lessonCourseware/getLessonCoursewareCourseList/' +
            route.query.id
        );
        if (Array.isArray(res?.data)) {
          // data.disabledIds = [1082460, 1082461, 1082462, 1082463];
          res.data.forEach((item: any) => {
            item.status = 'nochecked';
            item.children = item.knowledgePointList || [];
            item.id = item.coursewareDetailId;
            item.name = item.coursewareDetailName;
            formatDataList(item.children);
          });

          data.list = res.data;
          console.log(data.list, 'data.list', data.disabledIds);

          const allIds = {} as any;
          data.disabledIds.forEach((item: any) => {
            allIds[item] = formatGetIds(item, data.list);
          });
          console.log(allIds, 'allIds');

          for (const item in allIds) {
            const ids = allIds[item];
            for (let i = ids.length - 2; i >= 0; i--) {
              const listItem = getFormatIdList(ids[i], data.list);
              onParentChangeStatus(listItem);
            }
          }
        }
      } catch (error) {
        //
      }
      data.loading = false;
    };
    const formatDataList = (list: any = []) => {
      const tempList: any = [];
      list.forEach((item: any) => {
        let tempChild: any = {};
        item.status = 'nochecked';
        item.collapse = '';
        if (Array.isArray(item.materialList)) {
          item.materialList.forEach((item: any) => {
            if (
              state.vIds.includes(item.id + '') ||
              item.typeCode !== 'VIDEO'
            ) {
              item.status = 'disabled';
              data.disabledIds.push(item.id);
            } else {
              item.status = 'nochecked';
            }
          });
        }
        tempChild = item;
        if (Array.isArray(item.children)) {
          tempChild.children = formatDataList(item.children);
        }

        tempList.push({
          ...tempChild
        });
      });
      return tempList;
    };

    // 获取数据的编号
    const formatGetIds = (id: any, list: any[], ids = [] as any) => {
      for (const item of list) {
        if (item.id === id) {
          return [...ids, id];
        } else {
          if (Array.isArray(item.materialList)) {
            for (const material of item.materialList) {
              if (material.id === id) {
                return [...ids, item.id, id];
              }
            }
          }
        }
        if (item.children && item.children.length > 0) {
          const cIds: any = formatGetIds(id, item.children, [...ids, item.id]);
          if (cIds.includes(id)) {
            return cIds;
          }
        }
      }
      return ids;
    };

    // 获取编号对应的数组
    const getFormatIdList = (id: any, list: any[]) => {
      let tempI: any = {};
      for (const item of list) {
        if (item.id === id) {
          console.log(item, id);
          tempI = item;
        }
        if (item.children && item.children.length > 0 && !tempI.id) {
          tempI = getFormatIdList(id, item.children);
        }
      }
      return tempI;
    };

    const getKnowledgeMaterialIds = (list: any = []) => {
      const tempList: any = [];
      list.forEach((item: any) => {
        if (Array.isArray(item.materialList)) {
          item.materialList.forEach((item: any) => {
            if (item.status === 'checked') {
              tempList.push({
                id: item.id,
                name: item.name
              });
            }
          });
        }
        if (Array.isArray(item.children)) {
          tempList.push(...getKnowledgeMaterialIds(item.children));
        }
      });
      return tempList;
    };

    onMounted(async () => {
      try {
        const res = await request.get(
          state.platformApi + '/sysConfig/queryByParamName',
          {
            params: {
              paramName: 'upper_limit_homework_courseware'
            }
          }
        );
        data.maxAddCourseware = res.data.paranValue || 0;
      } catch {
        //
      }
      getDetail();
      getList();
    });

    // const handleClick = async (item: any) => {
    //   if (!item.knowledgePointList) {
    //     showConfirmDialog({
    //       message: '该课件暂无知识点'
    //     });
    //     return;
    //   }

    //   if (!item.hasCache) {
    //     // const hasFree = String(item.accessScope) === '0';
    //     // if (!hasFree) {

    //     // 下载中不提示
    //     if (item.downloadStatus == 1) {
    //       // 取消下载
    //       postMessage({ api: 'cancelDownloadCourseware' });
    //       setTimeout(() => {
    //         postMessage({ api: 'cancelDownloadCourseware' });
    //         item.downloadStatus = 0;
    //         data.isDownloading = false;
    //       }, 1000);
    //       showLoadingToast({
    //         message: '取消中...',
    //         forbidClick: false,
    //         loadingType: 'spinner',
    //         duration: 1000
    //       });
    //       return;
    //     }

    //     data.catchStatus = true;
    //     data.catchItem = item;
    //     return;
    //   }
    // };

    useEventListener('scroll', () => {
      const height =
        window.scrollY ||
        window.pageYOffset ||
        document.documentElement.scrollTop;
      data.titleOpacity = height > 100 ? 1 : height / 100;
    });

    // const onChangeCheck = () => {
    // data.list.forEach((item: any) => {});
    // };

    // watch(
    //   () => data.list,
    //   () => {
    //     //

    //     onChangeCheck();
    //   },
    //   {
    //     immediate: true,
    //     deep: true
    //   }
    // );
    return () => (
      <div class={styles.courseList}>
        <OHeader
          border={false}
          background={`rgba(255,255,255, ${data.titleOpacity})`}
          title="教材详情"
        />
        <div class={styles.periodContent}>
          <div class={styles.cover}>
            <img
              src={data.detail.cover}
              onLoad={(e: Event) => {
                if (e.target) {
                  (e.target as any).style.opacity = 1;
                }
              }}
            />
          </div>
          <div>
            <div class={styles.contentTitle}>{data.detail.name}</div>
            <div class={styles.contentLabel}>教学目标：{data.detail.des}</div>
          </div>
        </div>

        <TransitionGroup name="van-fade">
          {!data.loading && (
            <>
              <div key="periodTitle" class={styles.periodTitle}>
                <div class={styles.left}>
                  <img class={styles.pIcon} src={iconList} />
                  <div class={styles.pTitle}>课程列表</div>
                  <div class={styles.pNum}>共{data.list.length}课</div>
                </div>
                <div class={styles.right}>
                  <img
                    src={iconQuestion}
                    class={styles.iconQuestion}
                    onClick={() => (data.ruleStatus = true)}
                  />
                </div>
              </div>

              <div key="list" class={styles.periodList}>
                <Collapse
                  modelValue={data.parentCollapse}
                  onUpdate:modelValue={(val: any) => {
                    data.parentCollapse = val;
                    data.childrenCollapse = ''; // 重置子项选择
                  }}
                  class={styles.collapseParent}
                  border={false}
                  accordion>
                  {data.list.map((item: any) => (
                    <CollapseItem
                      center
                      name={item.coursewareDetailId}
                      clickable={false}>
                      {{
                        title: () => (
                          <div
                            class={[
                              styles.itemTitle,
                              data.parentCollapse === item.coursewareDetailId
                                ? styles.itemTitleActive
                                : ''
                            ]}>
                            <i class={[styles.arrow]}></i>
                            {item.coursewareDetailName}
                          </div>
                        ),
                        default: () => (
                          <>
                            {Array.isArray(item?.materialList) &&
                              item.materialList.map((n: any) => (
                                <Cell>
                                  {{
                                    title: () => n.name,
                                    value: () => (
                                      <img
                                        src={iconCheck}
                                        class={[styles.radioBtn]}
                                      />
                                    )
                                  }}
                                </Cell>
                              ))}
                            {Array.isArray(item?.children) && (
                              <ChildNode
                                list={item.children}
                                collapse={item.collapse}
                                onUpdate:collapse={val => {
                                  item.collapse = val;
                                }}
                                onMenuChange={() => {
                                  onParentChangeStatus(item);
                                }}
                              />
                            )}
                          </>
                        ),
                        'right-icon': () => (
                          <img
                            src={
                              item.status === 'indeterminate'
                                ? iconImm
                                : item.status === 'disabled'
                                ? iconCheckDisabled
                                : item.status === 'checked'
                                ? iconCheck
                                : iconNoCheck
                            }
                            class={[styles.radioBtn]}
                            onClick={(e: any) => {
                              e.stopPropagation();
                              if (item.status === 'disabled') {
                                return;
                              }
                              if (item.status === 'checked') {
                                item.status = 'nochecked';
                              } else {
                                item.status = 'checked';
                              }
                              if (Array.isArray(item.knowledgePointList)) {
                                item.knowledgePointList.forEach(
                                  (knowledgePoint: any) => {
                                    onMenuChange(knowledgePoint, item.status);
                                  }
                                );
                              }
                            }}
                          />
                        )
                      }}
                    </CollapseItem>
                  ))}
                </Collapse>
              </div>
            </>
          )}
        </TransitionGroup>
        {data.loading && <OLoading />}
        {!data.loading && !data.list.length && <OEmpty tips="暂无内容" />}

        <OSticky position="bottom">
          <div class={styles.btnGroup}>
            <Button
              block
              type="primary"
              color="linear-gradient( 132deg, #60DBC7 0%, #01C1B5 100%)"
              onClick={() => {
                const ids = getKnowledgeMaterialIds(data.list);
                if (state.max !== -1) {
                  if (ids.length > state.max) {
                    showToast(`当前练习组只可添加${state.max}条练习内容`);
                    return;
                  }
                }

                const body = {
                  api: 'onCoursewareSelectResult',
                  content: {
                    result: ids
                  }
                };
                postMessage(body);
              }}>
              确定
            </Button>
          </div>
        </OSticky>

        <Popup v-model:show={data.ruleStatus} class={styles.popupRule}>
          <div class={styles.title}>温馨提示</div>
          <div class={styles.content}>
            1、作业只能选择视频资源布置
            <br />
            2、单个练习组最大可添加{data.maxAddCourseware}个练习
            <br />
            3、同练习组单个视频资源不可多次添加
          </div>
          <div class={styles.popupBtnGroup}>
            <Button
              block
              color="linear-gradient( 132deg, #60DBC7 0%, #01C1B5 100%)"
              onClick={() => (data.ruleStatus = false)}>
              我知道了
            </Button>
          </div>
        </Popup>
      </div>
    );
  }
});
