import {
  DataTableColumn,
  NButton,
  NCascader,
  NDataTable,
  NForm,
  NFormItem,
  NIcon,
  NImage,
  NInput,
  NModal,
  NSpace,
  useMessage
} from 'naive-ui';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import { useUserStore } from '/src/store/modules/users';
import UploadFile from '/src/components/upload-file';
import { Add } from '@vicons/ionicons5';
import { teacherJobType } from '/src/utils/contants';
import {
  api_schoolUpdate,
  api_sysAreaQueryAllProvince,
  api_teacherPage,
  api_tenantInfoUpdateStatus,
  api_userResetPassword,
  updateAdmin
} from '../../api';
import AddTeacher from '../../modal/add-teacher';
import AddteacherModel from '../../modal/addteacherModel';
// import TeacherGuide from '@/custom-plugins/guide-page/teacher-guide';
import TheEmpty from '/src/components/TheEmpty';
import TheMessageDialog from '/src/components/TheMessageDialog';
import { modalClickMask } from '/src/state';
import { getHttpOrigin } from '/src/helpers/utils';
export default defineComponent({
  name: 'school-info',
  emits: ['changeTab'],
  setup(props, { emit }) {
    const user = useUserStore();
    const formOptions = reactive({
      areaList: [] as any[]
    });
    const forms = reactive({
      name: user.info.schoolInfos?.[0]?.name,
      schoolId: user.info.schoolInfos?.[0]?.id,
      userId: user.info.id,
      logo: user.info.schoolInfos?.[0]?.logo || user.info.avatar,
      provinceCode: user.info.schoolInfos?.[0]?.provinceCode || '', // 省份编码
      cityCode: user.info.schoolInfos?.[0]?.cityCode || '', // 城市编码
      regionCode: user.info.schoolInfos?.[0]?.regionCode || '' // 区域编码
    });
    const data = reactive({
      loading: false,
      schoolLoading: true,
      dataList: [] as any[],
      disabled: true,
      changeVisiable: false,
      messageLoading: false,
      resetVisiable: false,
      resetLoading: false,
      resetMessage: '',
      resetMessageType: 'reset',
      activeRow: {} as any,

      modal: false,
      qrModal: false,
      oldTecherform: {} as any,
      oldLoading: false
    });
    // const showGuide = ref(false);
    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '老师姓名',
          key: 'nickname',
          width: '15%',
          render: (row: any) => {
            return (
              <div
                style={{ userSelect: 'all', cursor: 'pointer' }}
                onClick={() => copyTo(row.nickname)}>
                {row.nickname}
              </div>
            );
          }
        },
        {
          title: '角色',
          key: 'jobType',
          width: '15%',
          render: (row: any) => {
            return teacherJobType[row.jobType];
          }
        },
        {
          title: '手机号码',
          key: 'phone',
          width: '15%',
          render: (row: any) => {
            return (
              <div
                style={{ userSelect: 'all', cursor: 'pointer' }}
                onClick={() => copyTo(row.phone)}>
                {row.phone}
              </div>
            );
          }
        },
        {
          title: '性别',
          key: 'questionTypeCode',
          width: '15%',
          render: (row: any) => {
            return <div>{row.gender ? '男' : '女'}</div>;
          }
        },
        {
          title: '状态',
          key: 'statusName',
          width: '15%',
          render: (row: any) => {
            return (
              <div>
                {row.status === 'ACTIVATION' ? (
                  '启用'
                ) : (
                  <div class={styles.errorBtn}>冻结</div>
                )}
              </div>
            );
          }
        },
        {
          title: '操作',
          key: 'titleImg',
          width: '25%',
          render: (row: any) => (
            <NSpace>
              <NButton
                type="primary"
                text
                disabled={row.id !== user.info.id && btnStatus(row)}
                onClick={() => {
                  data.resetMessage = `重置"${row.nickname}"的密码，是否继续？`;
                  data.resetVisiable = true;
                  data.resetMessageType = 'reset';
                  data.activeRow = row;
                }}>
                重置密码
              </NButton>

              {row.status === 'ACTIVATION' ? (
                <>
                  <NButton
                    disabled={row.id === user.info.id || btnStatus(row)}
                    type="primary"
                    text
                    onClick={() => handleChange(row)}>
                    冻结
                  </NButton>
                  {user.info.isSuperAdmin && !row.manageAdmin && (
                    <NButton
                      type="primary"
                      text
                      onClick={() => {
                        data.changeVisiable = true;
                        data.activeRow = row;
                      }}>
                      转交管理
                    </NButton>
                  )}
                </>
              ) : (
                <NButton
                  class={styles.errorBtn}
                  text
                  onClick={() => handleChange(row)}>
                  解冻
                </NButton>
              )}
            </NSpace>
          )
        }
      ];
    };

    const btnStatus = (row: any, type?: string) => {
      // 管理员
      if (
        user.info.teacherJobType === 'ADMIN' &&
        ['ADMIN', 'HEADMASTER'].includes(row.jobType)
      ) {
        return true;
      }
      return false;
    };

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

    const getList = async () => {
      data.loading = true;
      const res = await api_teacherPage({
        schoolId: user.info.schoolInfos?.[0]?.id,
        // jobType: 'TEACHER',
        // jobType: 'ADMIN',
        page: 1,
        rows: 1000
      });
      data.loading = false;
      if (res?.code === 200 && Array.isArray(res?.data?.rows)) {
        data.dataList = res.data.rows;
      }
      // setTimeout(() => {
      //   showGuide.value = true;
      // }, 500);
    };

    const onChangeManage = async () => {
      data.messageLoading = true;
      try {
        await updateAdmin({
          school: forms.schoolId,
          newAdminId: data.activeRow.id,
          oldAdminId: forms.userId
        });
        message.success('转交成功');
        emit('changeTab', 'person');
        await user.getInfo();
      } catch {
        //
      }
      data.messageLoading = false;
    };

    onMounted(() => {
      getAreaList();
      getList();
    });

    // const dialog = useDialog();
    const message = useMessage();
    const handleChange = (row: any) => {
      const statuStr = row.status === 'LOCKED' ? '解冻' : '冻结';
      // dialog.warning({
      //   title: '温馨提示',
      //   content: `是否${statuStr}"${row.nickname}"？`,
      //   positiveText: '确定',
      //   negativeText: '取消',
      //   maskClosable: false,
      //   onPositiveClick: async () => {
      //     await api_tenantInfoUpdateStatus({
      //       ids: [row.id],
      //       status: row.status === 'LOCKED' ? 'ACTIVATION' : 'LOCKED'
      //     });
      //     getList();
      //     message.success(statuStr + '成功');
      //   }
      // });
      data.resetMessageType = 'locked';
      data.resetVisiable = true;
      data.resetMessage = `是否${statuStr}"${row.nickname}"？`;
      data.activeRow = row;
    };
    // 重置密码
    const onResetPassword = async () => {
      data.resetLoading = true;
      try {
        if (data.resetMessageType === 'locked') {
          const statuStr = data.activeRow.status === 'LOCKED' ? '解冻' : '冻结';
          await api_tenantInfoUpdateStatus({
            ids: [data.activeRow.id],
            status: data.activeRow.status === 'LOCKED' ? 'ACTIVATION' : 'LOCKED'
          });
          getList();
          message.success(statuStr + '成功');
        } else {
          await api_userResetPassword({
            userId: data.activeRow.id,
            clientType: 'TEACHER'
          });
          message.success('重置成功');
        }

        data.resetVisiable = false;
      } catch {
        //
      }
      data.resetLoading = false;
    };
    const formRef = ref();
    const changeSchoolInfo = () => {
      formRef.value?.validate(async (err: any) => {
        if (err) {
          return;
        }
        data.schoolLoading = false;
        await api_schoolUpdate({ ...user.info.schoolInfos?.[0], ...forms });
        data.schoolLoading = true;
        message.success('修改成功');
        await user.getInfo();
        data.disabled = true;
      });
    };

    const registerUrl = () => {
      const queryStr = `tenantId=${user.info.schoolInfos?.[0]?.tenantId}&schoolId=${user.info.schoolInfos?.[0]?.id}&schoolName=${user.info.schoolInfos?.[0]?.name}`;
      const url =
        `${getHttpOrigin()}/classroom-app/#/teaher-register?` + queryStr;
      console.log(url);
      return url;
    };

    const copyTo = (text: string) => {
      const input = document.createElement('input');
      input.value = text;
      document.body.appendChild(input);
      input.select();
      input.setSelectionRange(0, input.value.length);
      document.execCommand('Copy');
      document.body.removeChild(input);
      message.success('复制成功');
    };
    return () => (
      <div class={styles.schoolInfo}>
        <NForm
          ref={formRef}
          class={styles.formWrap}
          model={forms}
          style={{ padding: '30px 0' }}
          disabled={data.disabled}>
          <NSpace size={[30, 20]}>
            <div class={styles.logo}>
              <NImage
                previewDisabled={false}
                src={forms.logo}
                objectFit="contain"
              />
              <div
                // style={{ display: data.disabled ? 'none' : '' }}
                class={styles.changeHead}>
                修改头像
                {data.schoolLoading && (
                  <UploadFile
                    class={[styles.uploadFile]}
                    cropper
                    onUpdate:fileList={val => {
                      forms.logo = val;
                      changeSchoolInfo();
                    }}
                  />
                )}
              </div>
            </div>
            <NFormItem
              label="学校名称"
              path="name"
              showRequireMark={false}
              rule={[
                { required: true, message: '请填写学校名称', trigger: 'blur' }
              ]}>
              <NInput
                bordered={!data.disabled}
                maxlength={20}
                v-model:value={forms.name}
              />
            </NFormItem>
            <NFormItem label="城区">
              {!data.oldLoading && (
                <NCascader
                  placeholder="请选择城区"
                  bordered={!data.disabled}
                  options={formOptions.areaList}
                  labelField="name"
                  valueField="code"
                  childrenField="areas"
                  checkStrategy="child"
                  expandTrigger="hover"
                  defaultValue={
                    user.info.schoolInfos?.[0]?.regionCode ||
                    user.info.schoolInfos?.[0]?.cityCode ||
                    user.info.schoolInfos?.[0]?.provinceCode
                  }
                  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>
              {/* {data.disabled ? (
                <NSpace class={styles.btnList} align="center" justify="end">
                  <NButton
                    class={styles.btn}
                    color="#f24433"
                    onClick={() => {
                      data.oldTecherform = Object.assign({}, forms);
                      data.disabled = false;
                    }}>
                    修改信息
                  </NButton>
                </NSpace>
              ) : (
                <NSpace class={styles.btnList} align="center" justify="end">
                  <NButton
                    class={styles.btn}
                    onClick={() => {
                      Object.assign(forms, data.oldTecherform);
                      data.disabled = true;
                      data.oldLoading = true;
                      nextTick(() => {
                        data.oldLoading = false;
                      });
                    }}>
                    取消
                  </NButton>
                  <NButton
                    class={styles.btn}
                    loading={!data.schoolLoading}
                    type="primary"
                    onClick={() => changeSchoolInfo()}>
                    完成
                  </NButton>
                </NSpace>
              )} */}
            </NFormItem>
          </NSpace>
        </NForm>

        <NSpace style={{ padding: '0 0 32px' }}>
          <NButton
            focusable={false}
            {...{ id: 'teacher-0' }}
            type="primary"
            renderIcon={() => <NIcon component={<Add />} />}
            onClick={() => (data.modal = true)}>
            添加老师
          </NButton>
          <NButton
            focusable={false}
            {...{ id: 'teacher-1' }}
            type="primary"
            onClick={() => (data.qrModal = true)}>
            老师注册二维码
          </NButton>
        </NSpace>

        <NDataTable
          v-slots={{
            empty: () => <TheEmpty></TheEmpty>
          }}
          loading={data.loading}
          columns={columns()}
          data={data.dataList}></NDataTable>

        {/* class={styles.addTeacher} */}
        <NModal
          maskClosable={modalClickMask}
          class={['modalTitle background', styles.addTeacher]}
          v-model:show={data.modal}
          title="添加老师"
          preset="card"
          showIcon={false}>
          <AddTeacher
            areaList={formOptions.areaList}
            onClose={() => {
              data.modal = false;
              getList();
            }}
          />
        </NModal>

        {data.qrModal ? (
          <div v-model:show={data.qrModal} class="n-modal-mask">
            <AddteacherModel
              onClose={() => {
                data.qrModal = false;
              }}></AddteacherModel>
          </div>
        ) : null}
        {/* {showGuide.value ? <TeacherGuide></TeacherGuide> : null} */}

        <NModal
          maskClosable={modalClickMask}
          v-model:show={data.changeVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={'转交管理员'}>
          <TheMessageDialog
            content={`<p style="text-align: left;">转交管理员后，您当前账号将无法查看和更改学校信息，请确认是否转交给<span style="color: #198CFE">【${data.activeRow.nickname}】</span></p>`}
            cancelButtonText="取消"
            confirmButtonText="确认"
            loading={data.messageLoading}
            onClose={() => (data.changeVisiable = false)}
            onConfirm={onChangeManage}
          />
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={data.resetVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={data.resetMessageType === 'reset' ? '重置密码' : '温馨提示'}>
          <TheMessageDialog
            content={data.resetMessage}
            cancelButtonText="取消"
            confirmButtonText="确认"
            loading={data.resetLoading}
            onClose={() => (data.resetVisiable = false)}
            onConfirm={onResetPassword}
          />
        </NModal>
      </div>
    );
  }
});
