import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import {
  NImage,
  NForm,
  NFormItem,
  NInput,
  NGrid,
  NGi,
  NButton,
  NSelect,
  NSpace,
  SelectOption,
  useMessage,
  NModal,
  NCascader
} from 'naive-ui';
import headerD from '../images/headerD.png';
import defultHeade from '@/components/layout/images/teacherIcon.png';
// import maleIcon from '../images/maleIcon.png';
// import femaleIcon from '../images/femaleIcon.png';
import { useUserStore } from '/src/store/modules/users';
import { api_teacherUpdate } from '/src/api/user';
import UploadFile from '/src/components/upload-file';
import ForgotPassword from '../modal/forgotPassword';
import { api_sysAreaQueryAllProvince } from '../api';
import { modalClickMask } from '/src/state';
import { teacherJobType } from '/src/utils/contants';
export default defineComponent({
  name: 'setting-personInfo',
  setup() {
    const message = useMessage();
    const userStore = useUserStore();
    const formOptions = reactive({
      sexs: [
        { label: '男', value: 1, class: 'option' },
        { label: '女', value: 0, class: 'option' }
      ] as SelectOption[],
      areaList: [] as any[]
    });
    const formRef = ref();
    const teacherForm = reactive({
      provinceCode: userStore.info.provinceCode, // 省份编码
      cityCode: userStore.info.cityCode, // 城市编码
      regionCode: userStore.info.regionCode, // 区域编码
      nickname: userStore.info.nickname,
      phone: userStore.info.phone,
      gender: userStore.info.gender,
      schoolId: userStore.info.schoolInfos?.[0]?.id,
      tenantId: userStore.info.schoolInfos?.[0]?.tenantId,
      id: userStore.info.id,
      avatar: userStore.info.avatar
    });
    const data = reactive({
      disabled: true,
      openChangePwd: false,
      uploadShow: true,
      loading: false,
      oldTecherform: {} as any
    });

    const getAreaList = async () => {
      const res = await api_sysAreaQueryAllProvince();
      if (res?.code === 200) {
        formOptions.areaList = res.data;
      }
    };
    onMounted(() => {
      getAreaList();
    });

    const handleSave = () => {
      formRef.value.validate(async (err: any) => {
        if (err) {
          return;
        }
        if (!teacherForm.provinceCode || !teacherForm.cityCode) {
          message.error('请选择城区');
          return;
        }
        await api_teacherUpdate(teacherForm);
        console.log(teacherForm);
        userStore.getInfo();
        data.disabled = true;
        message.success('修改成功');
      });
    };
    return () => (
      <div class={styles.infoWrap}>
        <div class={styles.teacherInfoWrap}>
          <div class={styles.teacherHeadWrap}>
            <NImage
              previewDisabled
              class={styles.headerD}
              src={headerD}></NImage>
            <NImage
              previewDisabled
              class={styles.defultHeade}
              src={teacherForm.avatar || defultHeade}></NImage>
            <div
              // style={{ display: data.disabled ? 'none' : '' }}
              class={[styles.defultHeade, styles.changeHead, styles.hoverNone]}>
              修改头像
              {data.uploadShow && (
                <UploadFile
                  class={[styles.uploadFile]}
                  cropper
                  onUpdate:fileList={async val => {
                    teacherForm.avatar = val;
                    data.uploadShow = false;
                    setTimeout(() => {
                      data.uploadShow = true;
                    }, 100);

                    await api_teacherUpdate(teacherForm);
                    console.log(teacherForm);
                    userStore.getInfo();
                  }}
                />
              )}
            </div>
          </div>
          <div class={styles.headerInfo}>
            <p class={styles.headerTitle}>
              {userStore.info.nickname}
              {/* {userStore.info.gender !== null && (
                <NImage
                  previewDisabled
                  class={styles.sexIcon}
                  src={userStore.info.gender ? maleIcon : femaleIcon}></NImage>
              )} */}
              {userStore.info.teacherJobType && (
                <span class={styles.roleType}>
                  {teacherJobType[userStore.info.teacherJobType]}
                </span>
              )}
            </p>
            <p class={styles.headerSubTitle}>
              {userStore.info.schoolInfos?.[0]?.name}
              {/* | 音乐老师 */}
            </p>
          </div>
        </div>
        <div class={styles.setInfo}>
          <NForm ref={formRef} model={teacherForm} disabled={data.disabled}>
            <NGrid cols={3} x-gap="100">
              <NGi>
                <NFormItem
                  label="姓名"
                  path="nickname"
                  rule={[
                    {
                      required: true,
                      message: '请输入老师姓名',
                      trigger: 'blur'
                    },
                    {
                      pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/,
                      message: '请输入中文姓名,不要包含空格,及特殊符号',
                      trigger: 'blur'
                    }
                  ]}>
                  <NInput
                    maxlength={14}
                    bordered={!data.disabled}
                    placeholder="请填写老师姓名"
                    v-model:value={teacherForm.nickname}></NInput>
                </NFormItem>
              </NGi>
              <NGi>
                <NFormItem
                  label="手机号"
                  path="phone"
                  rule={[
                    {
                      required: true,
                      message: '请填写老师手机号',
                      trigger: 'blur'
                    },
                    {
                      pattern: /^1[3456789]\d{9}$/,
                      message: '手机号格式不正确',
                      trigger: 'blur'
                    }
                  ]}>
                  <NInput
                    bordered={!data.disabled}
                    placeholder="请填写老师手机号"
                    v-model:value={teacherForm.phone}></NInput>
                </NFormItem>
              </NGi>
              <NGi>
                <NFormItem
                  label="性别"
                  path="gender"
                  rule={[
                    {
                      required: true,
                      type: 'number',
                      message: '请选择性别',
                      trigger: 'blur'
                    }
                  ]}>
                  <NSelect
                    bordered={!data.disabled}
                    class={styles.select}
                    showArrow={!data.disabled}
                    placeholder="请选择性别"
                    options={formOptions.sexs}
                    v-model:value={teacherForm.gender}
                  />
                </NFormItem>
              </NGi>
              <NGi>
                <NFormItem
                  label="城区"
                  path="provinceCode"
                  rule={{
                    required: true,
                    type: 'number',
                    message: '请选择城区',
                    trigger: 'change'
                  }}>
                  {!data.loading && (
                    <NCascader
                      bordered={!data.disabled}
                      options={formOptions.areaList}
                      labelField="name"
                      valueField="code"
                      childrenField="areas"
                      checkStrategy="child"
                      expandTrigger="hover"
                      defaultValue={
                        userStore.info.regionCode ||
                        userStore.info.cityCode ||
                        userStore.info.provinceCode
                      }
                      onUpdate:value={(
                        val: any,
                        option: any,
                        pathValues: any
                      ) => {
                        teacherForm.provinceCode = pathValues[0]?.code;
                        teacherForm.cityCode = pathValues[1]?.code;
                        teacherForm.regionCode = pathValues[2]?.code;
                      }}
                    />
                  )}
                </NFormItem>
              </NGi>
            </NGrid>
          </NForm>
        </div>
        {data.disabled ? (
          <NSpace class={styles.btnList} align="center" justify="end">
            <NButton
              class={styles.btn}
              color="#198cfe"
              onClick={() => (data.openChangePwd = true)}>
              修改密码
            </NButton>
            <NButton
              class={styles.btn}
              color="#f24433"
              onClick={() => {
                data.oldTecherform = Object.assign({}, teacherForm);
                data.disabled = false;
              }}>
              修改信息
            </NButton>
          </NSpace>
        ) : (
          <NSpace class={styles.btnList} align="center" justify="end">
            <NButton
              class={styles.btn}
              onClick={() => {
                data.loading = true;
                userStore.getInfo();
                formRef.value?.restoreValidation();
                data.disabled = true;
                Object.assign(teacherForm, data.oldTecherform);
                nextTick(() => {
                  data.loading = false;
                });
              }}>
              取消
            </NButton>
            <NButton
              class={styles.btn}
              type="primary"
              onClick={() => handleSave()}>
              完成
            </NButton>
          </NSpace>
        )}
        <NModal
          maskClosable={modalClickMask}
          class={styles.changePwdModal}
          v-model:show={data.openChangePwd}
          preset="dialog"
          showIcon={false}
          title="修改密码">
          <ForgotPassword
            phone={userStore.info.phone}
            onClose={() => {
              data.openChangePwd = false;
            }}
          />
        </NModal>
      </div>
    );
  }
});
