import {  hdHttp, HdResponse,BasicConstant } from '@itcast/basic'
import { promptAction, CommonModifier } from '@kit.ArkUI'
import { BusinessError } from '@kit.BasicServicesKit';
import HashMap from '@ohos.util.HashMap';
import { router } from '@kit.ArkUI'
import { emitter } from '@kit.BasicServicesKit'
@Component
export struct SelectedHospitalComp {
  scrollerForList: Scroller = new Scroller();

  @State provincerSelectedName:string = '请选择';
  @State provincerId:string = '';
  @State citySelectedName:string = '';
  @State cityId:string = '';
  @State districtsSelectedName:string = '';
  @State districtsId:string = '';
  @State hospitalSelectedName:string = '';
  @State inputSearch:string = '';
  @State tabBarModifier: CommonModifier = new CommonModifier();
  @State isHidenCity:boolean = false;
  @State isHiddenSearchView:boolean = false;
  // 当前选中的层级索引（0-省 1-市 2-区 3-医院）
  @State currentTabIndex: number = 0
  // 存储各层级选择状态
  @State selections: number[] = [0, 1,2 ,3]
  // 数据集合
  @State provinces: ProvinceOrCiry[] = []
  @State cities: ProvinceOrCiry[] = []
  @State districts: ProvinceOrCiry[] = []
  @State hospitals: Hospital[] = []
  @State searchHospitals: Hospital[] = []
  // 搜索关键词
  @Prop searchKey: string = ''
  private controller: TabsController = new TabsController();
  aboutToAppear() {
    this.loadProvinces(0,0)
    // this.controller.setTabBarTranslate({ x: 20, y: 0 })
  }


  // 加载省份数据
  private loadProvinces(type:number,provinceIdOrCity:number) {
    const areaListUrl:string = BasicConstant.urlExpertAPI+'areaList';
    const hashMap: HashMap<string, string> = new HashMap();

    hashMap.clear();
    if (type != 0) {
      hashMap.set('parent_id',provinceIdOrCity.toString())
    }
    hdHttp.httpReq<string>(areaListUrl,hashMap).then(async (res: HdResponse<string>) => {
      console.info(`Response areaList succeeded: ${res}`);
      let json:RequestProvinceCallData = JSON.parse(res+'') as RequestProvinceCallData;
      if(json.code=='200') {
        if (type == 0) {
          this.provinces = json.data;
          this.onTabChange(0)
        } else if (type == 1) {
          this.cities = json.data;
          this.onTabChange(1);
        } else if (type == 2) {
          this.onTabChange(2);
          if (json.data.length>0) {
            this.isHidenCity = false;
            this.districts = json.data;
          } else {
            this.isHidenCity = true;
            this.searchHospitalList('',false);
          }
        } else {
          this.searchHospitalList('',false);
        }
      } else {
        promptAction.showToast({ message: json.msg, duration: 1000 })
      }
    }).catch((err: BusinessError) => {
      console.info(`Response areaList fail: ${err}`);
    })
  }

  searchHospitalList(input:string,isSearchStatus:boolean) {
    const areaListUrl:string = BasicConstant.urlExpertAPI+'hospitalList';
    const hashMap: HashMap<string, string> = new HashMap();
    hashMap.clear();
    hashMap.set('name',input);
    hashMap.set('prov_id',this.provincerId);
    hashMap.set('city_id',this.cityId);
    hashMap.set('county_id',this.districtsId);
    hdHttp.httpReq<string>(areaListUrl,hashMap).then(async (res: HdResponse<string>) => {
      console.info(`Response hospitalList succeeded: ${res}`);
      let json:HospitalCallData = JSON.parse(res+'') as HospitalCallData;
      if(json.code=='200') {
        if (isSearchStatus) {
          if (json.data.length > 0) {
            this.isHiddenSearchView = true;
          } else  {
            this.isHiddenSearchView = false;
          }
          this.searchHospitals = json.data;
        } else {
          this.isHiddenSearchView = false;
          this.hospitalSelectedName = '请选择';
          this.hospitals = json.data;

          if (this.isHidenCity) {
            this.onTabChange(2);
          } else  {
            this.onTabChange(3);
          }
        }
      } else {
        promptAction.showToast({ message: json.msg, duration: 1000 })
      }
    }).catch((err: BusinessError) => {
      console.info(`Response hospitalList fail: ${err}`);
    })
  }

  // Tab切换事件
  private onTabChange(index: number) {
    if (index < this.currentTabIndex) { // 允许回退
      this.currentTabIndex = index
      return
    }
    // 验证数据完整性
    if (index === 1 && !this.selections[0]) return
    if (index === 2 && !this.selections[1]) return
    if (index === 3 && !this.selections[2]) return
    if (index === 4 && !this.selections[3]) return
    this.currentTabIndex = index
  }

  private handleSearchInput(value:string) {
    if (value.length<0) {
      return;
    }
    this.searchHospitalList(value,true);
  }
  backtoEdit(item: Hospital)
  {
    let eventData: emitter.EventData = {
      data: item
    };
    // 发送eventId为1的事件，事件内容为eventData。
    emitter.emit({ eventId: 250517 }, eventData);
    router.back({ url: 'pages/LoginPage/LoginSetInfoPage'})
    // router.back({ url: 'pages/LoginPage/LoginSetInfoPage',params: item})

  }
  otherHospitaltoBack()
  {
    let item={
      city_name: this.districtsSelectedName,
      county_id: this.districtsId,
      prov_id: this.provincerId,
      prov_name: this.provincerSelectedName,
      name:'其他医院',
      county_name:this.districtsSelectedName,
      uuid:'1',
      city_id:this.cityId
    } as Hospital
    this.backtoEdit(item)
  }
  build() {
    Column() {
      SearchInput((input:string)=>{
        this.handleSearchInput(input);
      })

      // 内容区域
      Tabs({ index:this.currentTabIndex, controller: this.controller,barModifier:this.tabBarModifier.align(Alignment.Start) }) {
        // 省份列表
        TabContent() {
          List() {
            ForEach(this.provinces, (item: ProvinceOrCiry) => {
              ListItem() {
                Text(item.name)
                  .fontColor(item.name == this.provincerSelectedName ? $r('app.color.main_color') : '#666666')
                  .fontSize(17)
                  .height(40)
                  .margin({ left: 20 })
                  .onClick(() => {
                    this.selections[0] = 1;
                    this.provincerSelectedName = item.name;
                    this.citySelectedName = '请选择'
                    this.districtsSelectedName = '';
                    this.hospitalSelectedName = '';
                    this.provincerId = item.id.toString();
                    this.loadProvinces(1, item.id);
                  })
              }
            })
          }
          .width('100%')
          .height('100%')
        }
        .customTabbar(this.provincerSelectedName)


        // 城市列表
        TabContent() {
          List() {
            ForEach(this.cities, (item : ProvinceOrCiry) => {
              ListItem() {
                Text(item.name)
                  .fontColor(item.name == this.citySelectedName?$r('app.color.main_color'):'#666666')
                  .fontSize(17)
                  .height(40)
                  .margin({left:20})
                  .onClick(() => {
                    this.selections[1] = 2;
                    this.citySelectedName = item.name;
                    this.districtsSelectedName = '请选择'
                    this.hospitalSelectedName = '';
                    this.cityId = item.id.toString();
                    this.loadProvinces(2,item.id)
                  })
              }
            })
          }
          .width('100%')
          .height('100%')
        }
        .customTabbar(this.citySelectedName)
        // 区县列表
        TabContent() {
          List() {
            if (this.isHidenCity) {
              ForEach(this.hospitals, (item: Hospital) => {
                ListItem() {
                  Text(item.name)
                    // .fontColor(item.name == this.districtsSelectedName?$r('app.color.main_color'):'#666666')
                    .fontSize(17)
                    .height(40)
                    .margin({left:20})
                    .onClick(() => {
                      // this.districtsSelectedName = item.name;
                      this.selections[2] = 3;
                      //医院点击
                      this.backtoEdit(item)
                    })
                }
              })
              ListItem() {
                Text('其他医院')
                  .fontSize(17)
                  .height(40)
                  .margin({left:20})
                  .onClick(()=>{
                    //医院点击
                    this.otherHospitaltoBack()
                  })
              }
            } else {
              ForEach(this.districts, (item: ProvinceOrCiry) => {
                ListItem() {
                  Text(item.name)
                    .fontColor(item.name == this.districtsSelectedName?$r('app.color.main_color'):'#666666')
                    .fontSize(17)
                    .height(40)
                    .margin({left:20})
                    .onClick(() => {
                      this.districtsSelectedName = item.name;
                      this.selections[3] = 4;
                      this.districtsId = item.id.toString();
                      this.searchHospitalList('',false);
                    })
                }
              })
            }
          }
          .width('100%')
          .height('100%')
        }
        .customTabbar(this.districtsSelectedName)
        if (!this.isHidenCity) {
          // 医院列表
          TabContent() {
            List() {
              ForEach(this.hospitals, (item:Hospital) => {
                ListItem() {
                  Text(item.name)
                    .fontSize(17)
                    .height(40)
                    .margin({left:20})
                    .onClick(()=>{
                      //医院点击
                      this.backtoEdit(item)
                    })
                }
              })
              ListItem() {
                Text('其他医院')
                  .fontSize(17)
                  .height(40)
                  .margin({left:20})
                  .onClick(()=>{
                    //医院点击
                    this.otherHospitaltoBack()
                  })
              }
            }
            .width('100%')
            .height('100%')
          }
          .customTabbar(this.hospitalSelectedName)

        }
      }
      .onChange(index => {
        this.onTabChange(index)
      })
      .barMode(BarMode.Scrollable)
      .height('100%')
      .divider( {
        strokeWidth: 1,
        color: $r('app.color.common_gray_border'),
      })
      .layoutWeight(1)
      .padding({ bottom:100 })

      if (this.isHiddenSearchView) {
        Column() {
          List() {
            ForEach(this.searchHospitals, (item: Hospital) => {
              ListItem() {
                Text(item.name)
                  .fontSize(17)
                  .height(40)
                  .margin({ left: 20 })
                  .onClick(() => {
                    //医院点击
                  })
              }
            })
          }
          .width('100%')
          .height('100%')
        }
        .position({ y: 60 })
        .width('100%')
        .height('82%')
        .backgroundColor(Color.White)
      }
    }
    .height('100%')
  }


}

@Builder
function SearchInput(onSearchInput:(input:string)=>void) {
  // inputText:String = ;
  Row() {
    // 返回按钮
    Image($r('app.media.selected_hospital_ws'))
      .width(20)
      .height(20)
      .margin({left:10})

    TextInput({ placeholder: '搜索医院标准名别名' })
      .width('80%')
      .backgroundColor('#EEEEEE')
      .onChange((value:string)=>{
        onSearchInput(value);
      })
      // .onEditChange((isEditing: boolean) => {
      //   if (!isEditing) {
      //     onSearchInput(value);
      //   }
      // })
      // .onSubmit(() => {
      //   onSearchInput(value);
      // })
  }
  .borderRadius(20)
  .width('90%')
  .height(40)
  .margin({top:10})
  .backgroundColor('#EEEEEE')
  .justifyContent(FlexAlign.Start)

}

@Extend(TabContent)
function customTabbar(name:string)
{
  .tabBar(SubTabBarStyle.of(name)
    .labelStyle({ unselectedColor: '#848284', selectedColor:'#8D2316' ,  font: { size: 17 }})
    .indicator({
      color: '#8D2316', //下划线颜色
      height: 1, //下划线高度
      marginTop:16 //下划线与文字间距
    }))
  .height('100%')
}

interface RequestProvinceCallData {
  msg:string,
  code:string,
  data:ProvinceOrCiry[]
}

interface HospitalCallData {
  msg:string,
  code:string,
  data:Hospital[]
}

// DataModel.ts
interface ProvinceOrCiry {
  treePath: string
  name: string,
  parent:number,
  id:number,
  fullName:string
}

interface Hospital {
  city_name: string
  county_id: string
  prov_id: string
  prov_name: string
  name:string
  county_name:string
  uuid:string
  city_id:string
}
