import {
  DataTableColumn,
  NButton,
  NCascader,
  NDataTable,
  NForm,
  NFormItem,
  NIcon,
  NImage,
  NInput,
  NModal,
  NSpace,
  useDialog,
  useMessage
} from 'naive-ui';
import { defineComponent, onMounted, reactive } 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
} from '../../api';
import AddTeacher from '../../modal/add-teacher';
import TheQrCode from '/src/components/TheQrCode';
import { stringifyQuery } from '/src/router';

export default defineComponent({
  name: 'school-info',
  setup() {
    const user = useUserStore();
    const formOptions = reactive({
      areaList: [] as any[]
    });
    const forms = reactive({
      name: user.info.schoolInfos?.[0]?.name,
      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,

      modal: false,
      qrModal: false
    });

    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '老师姓名',
          key: 'nickname'
        },
        {
          title: '手机号码',
          key: 'phone'
        },
        {
          title: '性别',
          key: 'questionTypeCode',
          render: (row: any) => {
            return <div>{row.gender ? '男' : '女'}</div>;
          }
        },
        {
          title: '状态',
          key: 'statusName',
          render: (row: any) => {
            return (
              <div>
                {row.status === 'ACTIVATION' ? (
                  <NButton text>{row.statusName}</NButton>
                ) : (
                  <NButton class={styles.errorBtn} text>
                    {row.statusName}
                  </NButton>
                )}
              </div>
            );
          }
        },
        {
          title: '操作',
          key: 'titleImg',
          render: (row: any) => (
            <NSpace>
              <NButton
                type="primary"
                quaternary
                size="small"
                onClick={() => onResetPassword(row)}>
                重置密码
              </NButton>

              {row.status === 'ACTIVATION' ? (
                <NButton
                  type="primary"
                  quaternary
                  size="small"
                  onClick={() => handleChange(row)}>
                  冻结
                </NButton>
              ) : (
                <NButton
                  class={styles.errorBtn}
                  quaternary
                  size="small"
                  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;
      }
    };
    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,
            password: 'ktyq' + row.phone.substr(7),
            clientType: 'TEACHER'
          });
          message.success('重置成功');
        }
      });
    };

    const changeSchoolInfo = async () => {
      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;
    };
    return () => (
      <div class={styles.schoolInfo}>
        <NSpace wrapItem={false} align="center">
          <div class={styles.logo}>
            <NImage
              previewDisabled={false}
              width={100}
              height={100}
              src={forms.logo}
            />
            <div
              style={{ display: data.disabled ? 'none' : '' }}
              class={styles.changeHead}>
              修改头像
              {data.schoolLoading && (
                <UploadFile
                  class={[styles.uploadFile]}
                  cropper
                  onUpdate:fileList={val => {
                    forms.logo = val;
                  }}
                />
              )}
            </div>
          </div>
          <NForm
            model={forms}
            style={{ paddingTop: '30px' }}
            disabled={data.disabled}>
            <NSpace>
              <NFormItem
                label="学校名称"
                path="name"
                showRequireMark={false}
                rule={[
                  { required: true, message: '请填写学习名称', trigger: 'blur' }
                ]}>
                <NInput
                  class={styles.input}
                  maxlength={20}
                  v-model:value={forms.name}
                />
              </NFormItem>
              <NFormItem label="城区" style={{ width: '300px' }}>
                <NCascader
                  options={formOptions.areaList}
                  labelField="name"
                  valueField="code"
                  childrenField="areas"
                  checkStrategy="child"
                  expandTrigger="hover"
                  defaultValue={
                    user.info.schoolInfos?.[0]?.regionCode ||
                    user.info.schoolInfos?.[0]?.cityCode
                  }
                  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.disabled = false)}>
                      修改信息
                    </NButton>
                  </NSpace>
                ) : (
                  <NSpace class={styles.btnList} align="center" justify="end">
                    <NButton
                      class={styles.btn}
                      onClick={() => (data.disabled = true)}>
                      取消
                    </NButton>
                    <NButton
                      class={styles.btn}
                      loading={!data.schoolLoading}
                      type="primary"
                      onClick={() => changeSchoolInfo()}>
                      完成
                    </NButton>
                  </NSpace>
                )}
              </NFormItem>
            </NSpace>
          </NForm>
        </NSpace>

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

        <NDataTable
          loading={data.loading}
          columns={columns()}
          data={data.dataList}></NDataTable>

        <NModal
          class={styles.addTeacher}
          v-model:show={data.modal}
          title="添加老师"
          preset="dialog"
          showIcon={false}>
          <AddTeacher
            onClose={() => {
              data.modal = false;
              getList();
            }}
          />
        </NModal>

        <NModal
          v-model:show={data.qrModal}
          title="二维码"
          preset="dialog"
          showIcon={false}>
          <div style={{ textAlign: 'center' }}>
            <TheQrCode text={registerUrl()} size={300} />
          </div>
        </NModal>
      </div>
    );
  }
});
