import OHeader from '@/components/o-header'
import OSticky from '@/components/o-sticky'
import { Form, Field, CellGroup, showToast, Icon, Popup, Picker, Button, Image } from 'vant'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import styles from './index.module.less'
import { useRouter } from 'vue-router'
import { state as globalState } from '@/state'
import logoIcon from './images/logo.png'
import locIcon from './images/loc-icon.png'
import request from '@/helpers/request'
import { areas } from '@/helpers/area'
import OUpload from '@/components/o-upload'
import { listenerMessage, postMessage } from '@/helpers/native-message'
export default defineComponent({
  name: 'school-detail',
  setup() {
    const router = useRouter()
    const state = reactive({
      list: [],
      info: {} as any,
      showArea: false,
      columns: [] as any,
      showProvince: ''
    })
    const forms = reactive({
      address: '',
      logo: '',
      email: '',
      emergencyContact: '',
      addressLongitudeLatitude: ''
    })
    const schoolImageRef = ref()
    console.log(schoolImageRef.value)
    const getSchoolDetail = async () => {
      const schoolId = (globalState.user.data.schoolInfos || [])
        .map((item) => {
          return item.id
        })
        .join(',')
      try {
        const { data } = await request.get(`/api-school/school/detail/${schoolId}`, {})
        state.info = data
        state.showProvince = data.provinceName + data.cityName

        forms.logo = data.logo
        forms.email = data.email
        ;(forms.emergencyContact = data.emergencyContact),
          (forms.addressLongitudeLatitude = data.addressLongitudeLatitude)
        forms.address = data.address
      } catch (e: any) {
        showToast(e.message)
      }
    }

    const submitInfo = async () => {
      // const schoolId = (globalState.user.data.schoolInfos || [])
      //   .map((item) => {
      //     return item.id
      //   })
      //   .join(',')
      // if (!forms.cityCode || !forms.provinceCode) {
      //   showToast('请选择省市')
      //   return
      // }
      if (!forms.address) {
        showToast('请输入详细地址')
        return
      }
      try {
        const { data } = await request.post('/api-school/school/update', {
          data: {
            ...forms
          }
        })
        showToast('修改成功')
        setTimeout(() => {
          router.go(-1)
        }, 500)
      } catch (e: any) {
        showToast(e.message)
      }
      console.log('submitInfo')
    }
    onMounted(() => {
      getSchoolDetail()
    })
    const setSchoolIcon = () => {
      schoolImageRef.value.startUpload()
    }
    // const onConfirmArea = (val) => {
    //   console.log(val)
    //   state.showProvince = val.selectedOptions[0].name + val.selectedOptions[1].name
    //   forms.provinceCode = val.selectedOptions[0].code
    //   forms.cityCode = val.selectedOptions[1].code
    //   state.showArea = false
    // }

    onMounted(() => {
      // console.log(areas)
      const tempareas: any = []
      areas.forEach((item) => {
        const temp = {
          name: item.name,
          code: item.code,
          areas: [] as any
        }
        if (item.areas && item.areas.length > 0) {
          item.areas.forEach((child) => {
            temp.areas.push({
              name: child.name,
              code: child.code
            })
          })
        }
        tempareas.push(temp)
      })
      state.columns = tempareas || []
    })
    const setAddress = async () => {
      try {
        postMessage(
          {
            api: 'sourseMapApi',
            content: { type: 'modify', orginPoint: forms.addressLongitudeLatitude }
          },
          (data: any) => {
            console.log(data.content.nowPoint, data.content.address, '------')
            forms.addressLongitudeLatitude = data.content.nowPoint
            forms.address = data.content.address
          }
        )
      } catch (e) {
        console.log(e)
      }
    }

    onMounted(() => {
      listenerMessage('sourseMapApi', (data: any) => {
        console.log(data.content.nowPoint, data.content.address)
        forms.addressLongitudeLatitude = data.content.nowPoint
        forms.address = data.content.address
      })
    })
    return () => (
      <>
        <div class={styles.schoolEidtWrap}>
          <div class={styles.eidtWrap}>
            <CellGroup inset>
              <div class={styles.schoolDtailWrap} onClick={setSchoolIcon}>
                <Image
                  width={50}
                  height={50}
                  fit="cover"
                  class={styles.schoolICon}
                  src={forms.logo ? forms.logo : logoIcon}
                ></Image>
                <div class={styles.schoolBtnWrap}>
                  <p>修改校徽</p>
                  <Icon name="arrow" size="20px" color="#aaa"></Icon>
                </div>
              </div>
            </CellGroup>
          </div>
          <div class={styles.eidtWrap}>
            <CellGroup inset>
              {/* <Field
                is-link
                readonly
                v-model={state.showProvince}
                name="area"
                label="地区选择"
                placeholder="点击选择省市"
                disabled
              ></Field> */}
              {/*    onClick={() => (state.showArea = true)} */}
              <Field
                label-align="top"
                rows={3}
                v-model={forms.address}
                maxlength={50}
                placeholder="请选择地址"
                type="textarea"
                disabled
                onClick={() => setAddress()}
              >
                {{
                  extra: () => (
                    <div class={styles.loctionIconWrap}>
                      <Image width={19} height={18} src={locIcon}></Image>
                    </div>
                  ),
                  label: () => <p class={styles.addP}>地址</p>
                }}
              </Field>
              <Field
                label-align="top"
                rows={3}
                v-model={forms.email}
                maxlength={50}
                placeholder="邮箱"
              >
                {{ label: () => <p class={styles.addP}>邮箱</p> }}
              </Field>
              <Field
                label-align="top"
                rows={3}
                v-model={forms.emergencyContact}
                maxlength={50}
                placeholder="负责人"
              >
                {{ label: () => <p class={styles.addP}>负责人</p> }}
              </Field>
            </CellGroup>
            <OUpload
              class={styles.upload}
              cropper
              v-model:modelValue={forms.logo}
              ref={schoolImageRef}
            />
          </div>
          <div class={styles.wall}></div>
          <div class={styles.bottomWrap}>
            <Button type="primary" size="large" onClick={submitInfo}>
              确认修改
            </Button>
          </div>
        </div>
      </>
    )
  }
})
