import {
  DataTableColumn,
  NButton,
  NCascader,
  NDataTable,
  NForm,
  NFormItem,
  NIcon,
  NImage,
  NInput,
  NModal,
  NSpace,
  useDialog,
  useMessage
} from 'naive-ui';
import { defineComponent, nextTick, 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 {
  api_schoolUpdate,
  api_sysAreaQueryAllProvince,
  api_teacherPage,
  api_tenantInfoUpdateStatus,
  api_userResetPassword,
  updateAdmin
} from '../../api';
import AddTeacher from '../../modal/add-teacher';
import TheQrCode from '/src/components/TheQrCode';
import logo from '@/common/images/logo.png';
import { stringifyQuery } from '/src/router';
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';
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,
      activeRow: {} as any,

      modal: false,
      qrModal: false,
      oldTecherform: {} as any,
      oldLoading: false
    });
    const showGuide = ref(false);
    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '老师姓名',
          key: 'nickname',
          render: (row: any) => {
            return (
              <div
                style={{ userSelect: 'all', cursor: 'pointer' }}
                onClick={() => copyTo(row.nickname)}>
                {row.nickname}
              </div>
            );
          }
        },
        {
          title: '手机号码',
          key: 'phone',
          render: (row: any) => {
            return (
              <div
                style={{ userSelect: 'all', cursor: 'pointer' }}
                onClick={() => copyTo(row.phone)}>
                {row.phone}
              </div>
            );
          }
        },
        {
          title: '性别',
          key: 'questionTypeCode',
          render: (row: any) => {
            return <div>{row.gender ? '男' : '女'}</div>;
          }
        },
        {
          title: '状态',
          key: 'statusName',
          render: (row: any) => {
            return (
              <div>
                {row.status === 'ACTIVATION' ? (
                  <NButton text>启用</NButton>
                ) : (
                  <NButton class={styles.errorBtn} text>
                    冻结
                  </NButton>
                )}
              </div>
            );
          }
        },
        {
          title: '操作',
          key: 'titleImg',
          render: (row: any) => (
            <NSpace>
              <NButton type="primary" text onClick={() => onResetPassword(row)}>
                重置密码
              </NButton>

              {row.status === 'ACTIVATION' ? (
                <>
                  <NButton
                    disabled={row.jobType === 'ADMIN'}
                    type="primary"
                    text
                    onClick={() => handleChange(row)}>
                    冻结
                  </NButton>
                  {row.jobType === 'TEACHER' && (
                    <NButton
                      type="primary"
                      text
                      onClick={() => {
                        data.changeVisiable = true;
                        data.activeRow = row;
                      }}>
                      转交管理
                    </NButton>
                  )}
                </>
              ) : (
                <NButton
                  class={styles.errorBtn}
                  text
                  onClick={() => handleChange(row)}>
                  解冻
                </NButton>
              )}
            </NSpace>
          )
        }
      ];
    };
    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 () => {
      console.log('111');

      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: '取消',
        onPositiveClick: async () => {
          await api_tenantInfoUpdateStatus({
            ids: [row.id],
            status: row.status === 'LOCKED' ? 'ACTIVATION' : 'LOCKED'
          });
          getList();
          message.success(statuStr + '成功');
        }
      });
    };
    // 重置密码
    const onResetPassword = (row: any): void => {
      dialog.warning({
        title: '警告',
        content: `重置"${row.nickname}"的密码，是否继续？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          await api_userResetPassword({
            userId: row.id,
            clientType: 'TEACHER'
          });
          message.success('重置成功');
        }
      });
    };
    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('修改成功');
        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 =
        `${location.origin}/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;
                    }}
                  />
                )}
              </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>

        <NModal
          class={styles.addTeacher}
          v-model:show={data.modal}
          title="添加老师"
          preset="dialog"
          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
          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>
      </div>
    );
  }
});
