import { CoreConst, IPortalMessage } from '@ibiz-template/core';
import { useNamespace } from '@ibiz-template/vue3-util';
import { computed, defineComponent, reactive, Ref, ref } from 'vue';
import { useRoute } from 'vue-router';
import './login-view.scss';
import { getCookie } from 'qx-util';

export const LoginView = defineComponent({
  setup() {
    const loading = ref(false);

    const formRef = ref<IData | null>(null);

    const route = useRoute();
    const ru = (route.query.ru as string) || '/';

    const loginData = reactive({
      username: '',
      password: '',
    });

    const login = async () => {
      try {
        if (!loginData.username) {
          ibiz.notification.error({
            desc: '请填写用户名',
          });
          return;
        }
        if (!loginData.password) {
          ibiz.notification.error({
            desc: '请填写密码',
          });
          return;
        }
        loading.value = true;
        const bol = await ibiz.auth.login(
          loginData.username,
          loginData.password,
        );
        if (bol) {
          window.location.hash = ru;
          window.location.reload();
        }
        loading.value = false;
      } catch (error) {
        ibiz.notification.error({
          desc: (error as IData)?.response?.data?.message || '登录失败',
        });
        loading.value = false;
      }
    };

    const title = computed(() => {
      return ibiz.env.AppTitle;
    });

    // 请求头
    const headers: Ref<IData> = ref({
      Authorization: `Bearer ${getCookie(CoreConst.TOKEN)}`,
    });
    ibiz.mc.command.asyncAction.on((msg: IPortalMessage) => {
      console.log(msg, 'login');
    });
    const uploadFile = (file: IData) => {
      console.log(file);
      // 创建一个空对象实例
      const formData = new FormData();
      // 调用append()方法添加数据
      formData.append('file', file.file);
      return new Promise((resolve, reject) => {
        ibiz.net
          .axios({
            url: '/api/demosys__mobvue3/viewtests/asyncimportdata2?srfimporttag=DataImport',
            method: 'POST',
            data: formData,
            headers: headers.value,
          })
          .then(res => {
            if (res.status === 200) {
              console.log(88, res);
              resolve(true);
            } else {
              reject();
            }
          })
          .catch(() => {
            reject();
          });
      });
    };
    const test = (data: IData) => {
      let systemId = ibiz.env.dcSystem;
      const { orgData } = ibiz;
      if (orgData) {
        if (orgData.systemid) {
          systemId = orgData.systemid;
        }
        if (orgData.orgid) {
          headers.value.srforgid = orgData.orgid;
        }
      }
      headers.value.srfsystemid = systemId;
      uploadFile(data);
    };
    return { loginData, login, title, loading, formRef, test };
  },
  render() {
    const ns = useNamespace('login-view');
    return (
      <div class={ns.b()}>
        <div class={ns.b('logo')}>
          <img class={ns.b('logo-img')} src='./assets/img/login-logo.png' />
          <div class={ns.b('title')}>{this.title}</div>
        </div>
        <van-form class={ns.b('form')} ref='formRef'>
          <div class={ns.b('user')}>
            <ion-icon name='person'></ion-icon>
            <van-field
              placeholder='请输入用户名'
              name='用户名'
              v-model={this.loginData.username}
              rules={[{ required: true, message: '请填写用户名' }]}
            ></van-field>
          </div>
          <div class={ns.b('password')}>
            <ion-icon name='lock-closed'></ion-icon>
            <van-field
              placeholder='请输入密码'
              name='密码'
              type='password'
              v-model={this.loginData.password}
              rules={[{ required: true, message: '请填写密码' }]}
            ></van-field>
          </div>
        </van-form>
        <div class={ns.b('btns')}>
          <van-button
            loading={this.loading}
            class={ns.b('login-btn')}
            onClick={this.login}
          >
            登录
          </van-button>
          <van-uploader after-read={this.test}>测试导入</van-uploader>
        </div>
      </div>
    );
  },
});
