import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import {
  NImage,
  NForm,
  NFormItem,
  NInput,
  NGrid,
  NGi,
  NButton,
  NSelect,
  NSpace,
  SelectOption,
  useMessage,
  NModal,
  NCalendar,
  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';
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: 0, // 省份编码
      cityCode: 0, // 城市编码
      regionCode: 0, // 区域编码
      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
    });

    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]}>
              修改头像
              {data.uploadShow && (
                <UploadFile
                  class={[styles.uploadFile]}
                  cropper
                  onUpdate:fileList={val => {
                    teacherForm.avatar = val;
                    data.uploadShow = false;
                    setTimeout(() => {
                      data.uploadShow = true;
                    }, 100);
                  }}
                />
              )}
            </div>
          </div>
          <div class={styles.headerInfo}>
            <p class={styles.headerTitle}>
              {userStore.info.nickname}
              <NImage
                previewDisabled
                class={styles.sexIcon}
                src={userStore.info.gender ? maleIcon : femaleIcon}></NImage>
            </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="sex">
                  <NSelect
                    bordered={!data.disabled}
                    class={styles.select}
                    showArrow={!data.disabled}
                    placeholder="请选择性别"
                    options={formOptions.sexs}
                    v-model:value={teacherForm.gender}
                  />
                </NFormItem>
              </NGi>
            </NGrid>
            <NFormItem
              label="城区"
              style={{ maxWidth: '30%' }}>
              <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>
          </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.disabled = false)}>
              修改信息
            </NButton>
          </NSpace>
        ) : (
          <NSpace class={styles.btnList} align="center" justify="end">
            <NButton
              class={styles.btn}
              onClick={() => {
                data.disabled = true;
                formRef.value?.restoreValidation();
              }}>
              取消
            </NButton>
            <NButton
              class={styles.btn}
              type="primary"
              onClick={() => handleSave()}>
              完成
            </NButton>
          </NSpace>
        )}
        <NModal
          class={styles.changePwdModal}
          v-model:show={data.openChangePwd}
          preset="dialog"
          showIcon={false}
          title="修改密码">
          <ForgotPassword
            phone={userStore.info.phone}
            onClose={() => {
              data.openChangePwd = false;
            }}
          />
        </NModal>
      </div>
    );
  }
});
