/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import HashMap from '@ohos.util.HashMap';
import { hdHttp, HdResponse ,logger,BasicConstant,ChangeUtil} from '@itcast/basic/Index'
import { BusinessError } from '@kit.BasicServicesKit';
import { VideoTypeModel,TypeList,VideoType } from '../model/VideoTypeModel'
import { ArrayList } from '@kit.ArkTS';
import { ListCompGandan } from '../components/ListCompGandan'
import { TagListModel,TagList } from '../model/TagListModel'
import { promptAction } from '@kit.ArkUI'
@Component
export struct SecondaryLink {
  @State currentTagIndex: number = 0; // 一级列表焦点索引值
  @State currentTagIndex2: number = -1; // 2级列表焦点索引值
  @State private tagLists:VideoType[] = []; // 一级列表数据
  @State contentData:TypeList[]=[]; // 二级列表数据
  @State videoImg:ResourceStr=$r('app.media.video_all')
  @State videoImgt:ResourceStr=$r('app.media.all_video')
  @State videoText:ResourceStr=$r('app.color.848284')
  @State videoTitle:string='全部视频'
  @State videoSort:string='最新'
  @State videoImgs:ResourceStr=$r('app.media.cb_new')
  @State videoImgSe:ResourceStr=$r('app.media.cb_screen_no')
  @State videoSelect:ResourceStr=$r('app.color.848284')
  @State sort:string='2'
  @State type_uuid:string=''
   arrayList: ArrayList<TypeList[]> = new ArrayList();
  @State isOpenSelect:boolean=false
  @State isOpenSelect1:boolean=false//筛选
  @State private tags:TagList[] = [];
  @State tagPosition: TagList[] = [];
  @State tagPositiontmp: TagList[] = [];
  @State keywords:string=''
  /**
   * 生命周期函数
   */
  aboutToAppear(): void {
    // 构造数据
    this.initList()

  }

  build() {
    Column() {
      Row()
      {
        Row() {
          Image(this.videoImg).width(15).height(15).margin({ left:15 })
          Text(this.videoTitle).maxLines(1).fontSize(14).fontColor(this.videoText).textAlign(TextAlign.Start)
            .textOverflow({ overflow: TextOverflow.Ellipsis }).margin({ left:5 })
          Image(this.videoImgt).width(15).height(15).margin({ left:5 })

        }.layoutWeight(1).height(36)
        .onClick(()=>{
          this.isOpenSelect1=false
          this.isOpenSelect=!this.isOpenSelect
        })
        Text().width(60).height(10)
        Row()
        {
          Text(this.videoSort).fontSize(14).fontColor($r('app.color.top_title')).textAlign(TextAlign.Start)
            .margin({ left:5 })
          Image(this.videoImgs).width(15).height(15).margin({ left:5 })
        }

        .onClick(()=>{
          if(this.videoSort=='最新')
          {
            this.sort='1'
            this.videoSort='最热'
            this.videoImgs=$r('app.media.cb_hot')
          }
          else
          {
            this.sort='2'
            this.videoSort='最新'
            this.videoImgs=$r('app.media.cb_new')
          }
        })
        Text('').backgroundColor($r('app.color.848284')).width(0.5).height(10)
          .margin({ left:5 })
        Row()
        {
          Text('筛选').fontSize(14).fontColor(this.videoSelect).textAlign(TextAlign.Start)
            .margin({ left:5 })
          Image(this.videoImgSe).width(15).height(15).margin({ left:5,right:10 })
        }

        .onClick(()=>{

          this.tagPosition = [...this.tagPositiontmp];
          this.isOpenSelect=false
          this.isOpenSelect1=!this.isOpenSelect1

        })
      }
      .backgroundColor(Color.White)
      .width('100%')
      Row().height(10).width('100%') .backgroundColor('#efefef')
      Stack({alignContent:Alignment.Top})
      {
        ListCompGandan({ sort:this.sort,type_uuid:this.type_uuid,keywords:this.keywords})
        if(this.isOpenSelect1)
        {
          Column()
          {
            Grid() {
              ForEach(this.tags, (item: TagList, index: number) => {
                GridItem() {
                  Text(item.NAME)
                    .height(25)
                    .width('100%')
                    .padding({left:5,right:5})
                    .fontWeight(FontWeight.Regular)
                    .fontSize(13)
                    .fontColor(this.tagPosition.indexOf(item)!=-1 ? $r('app.color.top_title'): $r('app.color.848284'))
                    .textAlign(TextAlign.Center)
                    .border({ width: 1, color:this.tagPosition.indexOf(item)!=-1 ? $r('app.color.top_title'):  '#999999' })
                    .borderRadius(30)

                    .onClick(() => {


                      if(this.tagPosition.indexOf(item)!=-1)
                      {
                        const newSelected = [...this.tagPosition];
                        newSelected.splice(this.tagPosition.indexOf(item), 1);
                        this.tagPosition = newSelected;

                      }
                      else
                      {
                        if (this.tagPosition.length >= 3) {
                          promptAction.showToast({ message: '最多选择三个标签!', duration: 1000 });
                          return;
                        }
                        this.tagPosition.push(item)
                      }

                    })
                }
              })
            }
            .padding(10)
            .columnsTemplate('1fr 1fr 1fr 1fr')
            .columnsGap(10)
            .rowsGap(10)
            .backgroundColor(Color.White)
            .height('calc(100% - 175vp)')
            .width('100%')
            .layoutWeight(1)
            Row()
            {
              Text('重置').height(40)
                .textAlign(TextAlign.Center)
                .fontColor($r('app.color.top_title') )
                .border({ width: 1, color: $r('app.color.top_title') })
                .borderRadius(5)
                .layoutWeight(1)
                .margin({left:15})
                .onClick(()=>{
                  this.tagPosition= [];
                })
              Text('确定')
              .height(40)
              .fontColor(Color.White).textAlign(TextAlign.Center)
              .border({ width: 1, color: $r('app.color.top_title') })
              .borderRadius(5)
              .layoutWeight(1)
                .backgroundColor($r('app.color.top_title'))
                .margin({left:10,right:15})
                .onClick(()=>{
                  this.tagPositiontmp = [...this.tagPosition];
                  this.keywords=''
                  if(this.tagPosition.length>0)
                  {
                    this.videoImgSe=$r('app.media.cb_screen_yes')
                    this.videoSelect=$r('app.color.top_title')
                    this.tagPosition.forEach(element => {
                      this.keywords+=element.NAME+ ","
                    });

                  }
                  else
                  {

                    this.videoSelect=$r('app.color.848284')
                    this.videoImgSe=$r('app.media.cb_screen_no')
                  }

                  this.isOpenSelect1=false
                })
            }.width('100%')
            .height(60)
            .backgroundColor(Color.White)

          }
          .height('calc(100% - 175vp)')

        }
        if(this.isOpenSelect)
        {
          Row() {
            // TODO:知识点: 2.一级列表绑定Scroller对象
            List() {
              // 性能知识点：此处为横向列表，列表项确定且数量较少，使用了ForEach，在列表项多的情况下，推荐使用LazyForeEach
              ForEach(this.tagLists, (item: VideoType, index: number) => {
                ListItem() {
                  Text(item.name)
                    .width('100%')
                    .padding(10)
                    .fontWeight(FontWeight.Regular)
                    .fontSize(15)
                    .fontColor(this.currentTagIndex === index ? $r('app.color.top_title'): $r('app.color.848284'))
                    .textAlign(TextAlign.Center)
                    .backgroundColor(this.currentTagIndex === index ? $r('sys.color.ohos_id_color_background') : '')

                    .onClick(() => {
                      this.currentTagIndex = index;
                      this.contentData=this.arrayList[index];

                    })
                }
              })
            }
            .backgroundColor('#efefef')
            .width('27%')
            .height('calc(100% - 175vp)')
            // 二级列表
            List() {
              if(this.currentTagIndex==0)
              {
                ListItem() {
                  Row() {
                    Text('全部视频')
                      .fontSize(15)
                      .padding(10)
                      .fontColor(this.currentTagIndex2 === -2 ? $r('app.color.top_title'): $r('app.color.848284'))
                  }
                }.onClick(()=>{
                  this.videoTitle='全部视频'
                  this.currentTagIndex2=-2
                  this.changeSelectRescourse()
                  this.type_uuid=''
                })
              }
              ForEach(this.contentData, (item: TypeList,index: number) => {
                ListItem() {
                  Row() {
                    Text(item.name)
                      .fontSize(15)
                      .padding(10)
                      .fontColor(this.currentTagIndex2 === index ? $r('app.color.top_title'): $r('app.color.848284'))
                  }
                }.onClick(()=>{
                  this.currentTagIndex2=index
                  this.videoTitle=item.name
                  this.type_uuid=item.uuid
                  this.changeSelectRescourse()
                })
              })
            }
            .backgroundColor(Color.White)
            .layoutWeight(1)
            .divider({
              strokeWidth: 1,
              color: $r('app.color.common_gray_border'),
              startMargin:10,
              endMargin:10
            })
            .height('calc(100% - 175vp)')
          }.width('100%').alignItems(VerticalAlign.Top)
        }

      }
      .layoutWeight(1)
    }
  }

  changeSelectRescourse()
  {
    this.videoImg=$r('app.media.video_select')
    this.videoImgt=$r('app.media.select_video')
    this.videoText=$r('app.color.top_title')
    this.isOpenSelect=false
  }

  initList()
  {
    let hashMap: HashMap<string, string> = new HashMap();
    hdHttp.httpReq<string>(BasicConstant.expertVideoTypeList,hashMap).then(async (res: HdResponse<string>) => {

      let json:VideoTypeModel = JSON.parse(res+'') as VideoTypeModel;
      this.tagLists=json.data
      for (let i  = 0;i<this.tagLists.length;i++){
        let datatagname=json.data[i].list;
        let  k:number[]=[];
        for(let j=0;j<datatagname.length;j++)
        {
          let s:string;
          if ("z-BMS专家端"==(datatagname[j].name)){
            k.push(j);
          }
          let title:string = datatagname[j].name
          let digit:boolean = ChangeUtil.isFirstDigit(title.charAt(0));//判断首位是否是数字
           let asciiAlpha :boolean= ChangeUtil.isLetter(title.charAt(0));//字母
          if(digit||asciiAlpha){
            let substring:string = '';
            if (title.length>=4){
              substring = title.substring(0, 4);//取出来前4位
            }else if(title.length>=3){
              substring = title.substring(0, 3);//取出来前3位
            }else if (title.length>=2){
              substring = title.substring(0, 2);//取出来前2位
            }
            if (substring.includes("-")){//含有-
               let split: string[] = substring.split("-");
              if (split.length>1){
                s = split[split.length - 1] + title.substring(4, title.length);
              }else {
                s  = title.substring(4, title.length);
              }
              datatagname[j].name=s;
            }
          }
        }
        const indexesToRemove = new Set(k); // 使用 Set 提高查找效率
        const newArr = datatagname.filter((_, index) => !indexesToRemove.has(index));
        this.arrayList.add(newArr)
        k=[]
      }
      this.contentData=this.arrayList[0];

    }).catch((err: BusinessError) => {


    })
    let hashMap1: HashMap<string, string> = new HashMap();
    hashMap1.set("type", "2")
    hdHttp.post<string>(BasicConstant.tagList,{
      type:'2'
    } as TagModel).then(async (res: HdResponse<string>) => {
      let json:TagListModel = JSON.parse(res+'') as TagListModel;
      this.tags=json.data


    }).catch((err: BusinessError) => {


    })
  }
}

interface TagModel
{
  type:string
}
