import {
  NForm,
  NFormItem,
  NInput,
  NSpace,
  NButton,
  useMessage,
  NAlert,
  NCascader
} from 'naive-ui';
import { Prop, PropType, defineComponent, reactive, ref } from 'vue';
import { api_teacherAdd } from '../../api';
import { useUserStore } from '/src/store/modules/users';
export default defineComponent({
  name: 'teacher-operation',
  emits: ['close'],
  props: {
    areaList: {
      type: Array as PropType<any[]>,
      default: () => []
    }
  },
  setup(props, { emit }) {
    const user = useUserStore();
    const forms = reactive({
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      tenantId: user.info.schoolInfos?.[0]?.tenantId,
      phone: null,
      schoolId: user.info.schoolInfos?.[0]?.id,
      nickname: null,
      gender: 1
    });
    const btnLoading = ref(false);
    const formsRef = ref();
    const message = useMessage();
    // 提交记录
    const onSubmit = async () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return;
        try {
          btnLoading.value = true;
          await api_teacherAdd({ ...forms });
          message.success('添加成功');
        } catch (e) {
          console.log(e);
        }
        setTimeout(() => {
          btnLoading.value = false;
          emit('close');
        }, 100);
      });
    };

    // const formatParentAreaId = (id: any, list: any, ids = [] as any) => {
    //   for (const item of list) {
    //     if (item.code === id) {
    //       return [...ids, id];
    //     }
    //     if (item.areas && item.areas.length > 0) {
    //       const cIds: any = formatParentAreaId(id, item.areas, [
    //         ...ids,
    //         item.code
    //       ]);
    //       if (cIds.includes(id)) {
    //         return cIds;
    //       }
    //     }
    //   }
    //   return ids;
    // };

    return () => (
      <div>
        <NForm
          model={forms}
          ref={formsRef}
          showRequireMark={false}
          label-placement="left"
          label-width="126">
          <NFormItem
            label="老师姓名"
            path="nickname"
            rule={[
              {
                required: true,
                message: '请输入老师姓名'
              }
            ]}>
            <NInput
              v-model:value={forms.nickname}
              placeholder="请输入老师姓名"
              clearable
              maxlength={14}
            />
          </NFormItem>
          <NFormItem
            label="老师性别"
            path="gender"
            rule={[
              {
                required: true,
                message: '请选择老师性别'
              }
            ]}>
            <NSpace>
              <n-button
                class="genderBtn"
                type={forms.gender ? 'info' : undefined}
                tertiary={forms.gender ? false : true}
                onClick={() => {
                  forms.gender = 1;
                }}>
                男
              </n-button>
              <n-button
                class="genderBtn"
                type={!forms.gender ? 'info' : undefined}
                tertiary={!forms.gender ? false : true}
                onClick={() => {
                  forms.gender = 0;
                }}>
                女
              </n-button>
            </NSpace>
          </NFormItem>
          <NFormItem label="城区">
            <NCascader
              to="body"
              placeholder="请选择城区"
              options={props.areaList}
              labelField="name"
              valueField="code"
              childrenField="areas"
              checkStrategy="child"
              expandTrigger="hover"
              onUpdate:value={(val: any, option: any, pathValues: any) => {
                forms.provinceCode = pathValues[0]?.code;
                forms.cityCode = pathValues[1]?.code;
                forms.regionCode = pathValues[2]?.code;
              }}
            />
          </NFormItem>
          <NFormItem
            label="手机号"
            path="phone"
            rule={[
              {
                required: true,
                message: '手机号码',
                trigger: 'blur'
              },
              {
                pattern:
                  /^((13[0-9])|(14(0|[5-7]|9))|(15([0-3]|[5-9]))|(16(2|[5-7]))|(17[0-8])|(18[0-9])|(19([0-3]|[5-9])))\d{8}$/,
                message: '请输入正确的手机号',
                trigger: 'blur'
              }
            ]}>
            <NInput
              maxlength={11}
              v-model:value={forms.phone}
              placeholder="请输入手机号"
              clearable
            />
          </NFormItem>

          <div class="nalert">
            <NAlert type="error" showIcon={false} bordered={false}>
              默认密码为ktyq+手机号后四位
            </NAlert>
          </div>
        </NForm>

        <NSpace style={{ padding: '20px 0 32px 0' }} justify="center">
          <NButton
            class="actionBtn"
            round
            type="default"
            onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton
            class="actionBtn"
            round
            type="primary"
            onClick={() => onSubmit()}
            loading={btnLoading.value}>
            确定
          </NButton>
        </NSpace>
      </div>
    );
  }
});
