import {
  computed,
  defineComponent,
  reactive,
  TransitionGroup,
  watch
} from 'vue';
import styles from './index.module.less';
import request from '@/helpers/request';
import { state } from '@/state';
import { useRoute, useRouter } from 'vue-router';
// import OLoading from '@/components/o-loading';
// import OEmpty from '@/components/o-empty';
import { Cell, Collapse, CollapseItem, Dialog } from 'vant';
import ChildNode, { getImage } from './child-node';
import iconMenu from './image/icon-menu.png';
import TheSticky from '@/components/the-sticky';
import ColHeader from '@/components/col-header';
import ColSearch from '@/components/col-search';
import { Vue3Lottie } from 'vue3-lottie';
import AstronautJSON from '../music-detail/animate/refresh_anim.json'
import ColResult from '@/components/col-result';
import { browser, getHttpOrigin } from '@/helpers/utils';
import { orderStatus } from '@/views/order-detail/orderStatus';
import { postMessage } from '@/helpers/native-message'

// import OSticky from '@/components/o-sticky';

export default defineComponent({
  name: 'course-list-search',
  setup() {
    const route = useRoute();
    const router = useRouter()
    const data = reactive({
      titleOpacity: 0,
      loading: true,
      detail: {} as Record<string, any>,
      list: [] as any,
      search: '' as string | undefined,
      parentCollapse: '' as any
      // childrenCollapse: '' as any
    });
    const formatDataList = (list: any = []) => {
      const tempList: any = [];
      list.forEach((item: any) => {
        let tempChild: any = {};
        item.collapse = '';
        tempChild = item;
        if (Array.isArray(item.children)) {
          tempChild.children = formatDataList(item.children);
        }
        tempList.push({
          ...tempChild
        });
      });
      return tempList;
    };

    const formatSelectFirstChild = (list: any = []): any => {
      for (let i = 0; i < list.length; i++) {
        if (
          Array.isArray(list[i].materialList) &&
          list[i].materialList.length > 0
        ) {
          const materialItem = list[i].materialList[0] || {};
          if (materialItem) {
            return materialItem;
          }
        } else {
          return formatSelectFirstChild(list[i].children || []);
        }
      }
    };

    //
    function selectFirstChild(pointList: any[], ids: any[]): any[] {
      return pointList.map(point => {
        if (point.children) {
          let id = '';
          point.children.map((item: any) => {
            if (!id) {
              id = ids.includes(item.id) ? item.id : '';
            }
          });
          point.collapse = id;
          return Object.assign(point, {
            children: selectFirstChild(point.children, ids)
          });
        } else {
          return Object.assign(point, {
            materialList: point.materialList
          });
        }
      });
    }

    function filterPointList(
      pointList: any[],
      parentData?: { ids: string[]; name: string }
    ): any[] {
      // 设置父级及以上id数组和父级name
      return pointList.map(point => {
        if (point.children) {
          return Object.assign(point, {
            children: filterPointList(point.children, {
              ids: [...(parentData?.ids || []), point.id],
              name: point.name
            })
          });
        } else {
          return Object.assign(point, {
            materialList: point.materialList.map((item: any) => {
              item.parentData = {
                ids: [...(parentData?.ids || []), point.id],
                name: point.name
              };
              return item;
            })
          });
        }
      });
    }

    const getList = async (search?: string) => {
      data.loading = true;
      try {
        const res: any = await request.get(
          state.platformApi +
            '/tenantAlbumMusic/getLessonCoursewareCourseList/' +
            route.query.id,
          {
            requestType: 'form',
            params: {
              search
            }
          }
        );
        if (Array.isArray(res?.data)) {
          data.search = search;
          res.data.forEach((item: any) => {
            item.children = item.knowledgePointList || [];
            item.id = item.coursewareDetailId;
            item.name = item.coursewareDetailName;
            formatDataList(item.children);
          });
          const firstItem = formatSelectFirstChild(res.data);
          let list = filterPointList(res.data);
          list = selectFirstChild(list, firstItem?.parentData?.ids || []);
          data.list = list;

          list.forEach((item: any) => {
            if (item.id === firstItem.parentData?.ids[0]) {
              data.parentCollapse = item.id;
            }
          });
        }
      } catch (error) {
        //
        console.log(error, 'error');
      }
      data.loading = false;
    };

    /** 获取课件详情 */
    const getDetail = async () => {
      try {
        const res: any = await request.post(
          state.platformApi + `/tenantAlbumMusic/getLessonCoursewareDetail`,
          {
            data: {
              lessonCoursewareId: route.query.id,
              albumId: route.query.albumId
            }
          }
        )
        data.detail = res?.data || {}
      } catch {
        //
      }
    }
    getDetail()
    getList();


    const handleClick = (item: any) => {
      if(data.detail.id && !data.detail.play) {
        if(route.query.buyStatus !== '1') {
          if (!browser().isApp) {
            onDownloadApp()
            return
          }
          onSubmit()
          return
        }
      }
      if (browser().isApp) {
        postMessage({
          api: 'openWebView',
          content: {
            url: `${getHttpOrigin()}${location.pathname}#/coursewarePlay?lessonId=${route.query.id}&source=search&kId=${item.id}&search=${encodeURIComponent(data.search || '')}`,
            orientation: 0,
            isHideTitle: true,
            statusBarTextColor: false,
            isOpenLight: true,
            showLoadingAnim: true
          }
        });
      } else {
        router.push({
          path: '/coursewarePlay',
          query: {
            lessonId: route.query.id,
            kId: item.id,
            search: data.search,
            source: 'search'
          }
        });
      }
    }

    const onSubmit = async () => {
      const url =
        state.platformApi + 
        '/tenantGroupAlbum/buyAlbumInfo?tenantGroupAlbumId=' +
        (route.query.taId || '')
      const { data } = await request.get(url)
      const details = data[0]
      orderStatus.orderObject.orderType = 'TENANT_ALBUM'
      orderStatus.orderObject.orderName = details.name
      orderStatus.orderObject.orderDesc = details.name
      orderStatus.orderObject.actualPrice = details.actualPrice
      orderStatus.orderObject.orderNo = ''
      orderStatus.orderObject.orderList = [
        {
          orderType: 'TENANT_ALBUM',
          goodsName: details.name,
          actualPrice: details.actualPrice,
          price: details.actualPrice,
          ...details
        }
      ]

      const res = await request.post(state.platformApi + '/userOrder/getPendingOrder', {
        data: {
          goodType: 'TENANT_ALBUM',
          bizId: details.id
        }
      })

      const result = res.data
      if (result) {
        Dialog.confirm({
          title: '提示',
          message: '您有一个未支付的订单，是否继续支付？',
          theme: 'round-button',
          className: 'confirm-button-group',
          cancelButtonText: '取消订单',
          confirmButtonText: '继续支付'
        })
          .then(async () => {
            orderStatus.orderObject.orderNo = result.orderNo
            orderStatus.orderObject.actualPrice = result.actualPrice
            orderStatus.orderObject.discountPrice = result.discountPrice
            orderStatus.orderObject.paymentConfig = {
              ...result.paymentConfig,
              paymentVendor: result.paymentVendor,
              paymentVersion: result.paymentVersion
            }

            routerToALBUM(details.id)
          })
          .catch(() => {
            Dialog.close()
            // 只用取消订单，不用做其它处理
            cancelPaymentALBUM(result.orderNo)
          })
      } else {
        routerToALBUM(details.id)
      }
    }
    const cancelPaymentALBUM = async (orderNo: string) => {
      try {
        await request.post('/api-student/userOrder/orderCancel/v2', {
          data: {
            orderNo
          }
        })
      } catch {
        //
      }
    }
    const routerToALBUM = (id: string) => {
      router.push({
        path: '/orderDetail',
        query: {
          orderType: 'ALBUM',
          album: id
        }
      })
    }
    const onDownloadApp = () => {
      Dialog.alert({
        title: '提示',
        message: '请在酷乐秀APP中使用',
        confirmButtonColor: '#2dc7aa'
      }).then(() => {
        window.location.href = getHttpOrigin() + '/student/#/download'
      })
    }

    return () => (
      <div class={styles.courseListSearch}>
        <TheSticky position="top">
          <ColHeader
            background={`rgba(255,255,255, ${data.titleOpacity})`}
            border={false}>
            {{
              title: () => (
                <div class={styles.title}>
                  <ColSearch
                    type="tenant"
                    background="transparent"
                    placeholder="请输入素材关键词"
                    onSearch={(val: string) => {
                      getList(val);
                    }}
                  />
                </div>
              )
            }}
          </ColHeader>
        </TheSticky>

        <div style="height: calc(100vh - var(--header-height)); overflow-x: hidden; overflow-y: auto;">
          <TransitionGroup name="van-fade">
            {!data.loading && (
              <Collapse
                key="courseListSearch"
                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
                    border={true}
                    name={item.coursewareDetailId}
                    clickable={false}
                    class={['parentCollapse__item']}>
                    {{
                      title: () => (
                        <div class={[styles.itemTitle]}>
                          <img src={iconMenu} class={styles.iconMenu} />
                          {item.coursewareDetailName}
                        </div>
                      ),
                      default: () => (
                        <>
                          {Array.isArray(item?.materialList) &&
                            item.materialList.map((n: any) => (
                              <Cell center isLink clickable={false}>
                                {{
                                  title: () => (
                                    <div class={styles.materialSection}>
                                      <img
                                        src={getImage(n)}
                                        class={styles.iconMaterial}
                                      />
                                      {n.name}
                                    </div>
                                  )
                                }}
                              </Cell>
                            ))}
                          {Array.isArray(item?.children) && (
                            <ChildNode
                              id={route.query.id as any}
                              search={data.search}
                              list={item.children}
                              collapse={item.collapse}
                              onUpdate:collapse={(val: any) => {
                                item.collapse = val;
                              }}
                              onHandleClick={(item: any) => {
                                handleClick(item)
                              }}
                            />
                          )}
                        </>
                      ),
                      'right-icon': () => (
                        <i
                          class={[
                            styles.arrow,
                            data.parentCollapse === item.coursewareDetailId
                              ? styles.arrowActive
                              : ''
                          ]}></i>
                      )
                    }}
                  </CollapseItem>
                ))}
              </Collapse>
            )}
          </TransitionGroup>
          {data.loading && <div>
              <Vue3Lottie
                animationData={AstronautJSON}
                class={styles.finch}
              ></Vue3Lottie>
              {/* <p class={styles.finchLoad}>加载中...</p> */}
            </div>}
          {!data.loading && !data.list.length && <ColResult projectType='tenant' btnStatus={false} tips="暂无搜索结果" />}
        </div>
      </div>
    );
  }
});
