<template>
	<el-form ref="login" :model="ruleForm" :rules="state.rules" size="large" @keyup.enter.native="handlelogin">
		<el-form-item prop="username">
			<el-input v-model="ruleForm.username" placeholder="登录 ID" ref="txtUserName">
				<template #prefix>
					<el-icon class="el-input__icon">
						<user />
					</el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input type="password" v-model="ruleForm.password" placeholder="登录密码" show-password
				autocomplete="new-password" ref="txtPwd">
				<template #prefix>
					<el-icon class="el-input__icon">
						<lock />
					</el-icon>
				</template>
			</el-input>
		</el-form-item>
    <el-form-item style="margin-top: -30px;">
      <div style="position: absolute; right: 0%;">
        <el-switch v-model="ruleForm.logintype" inline-prompt="true" active-value="0" inactive-value="1" style="margin-left: 10px;"
        active-text="内部" inactive-text=""/>
      </div>    
		</el-form-item>
	</el-form>
	<div class="login-btn">
		<el-button :icon="CircleClose" round @click="resetForm()" size="large">重置</el-button>
    <el-button :icon="CircleClose" round @click="register()" size="large">注册</el-button>
		<el-button :icon="UserFilled" round @click="handlelogin" size="large" type="primary">
			登录
		</el-button>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElForm, ElMessage } from "element-plus";
import { useStore } from "../../../store";
import { setToken,getToken } from "../../../until/auth";
import FacUserApi from '../../../api/usermanagement/facuser';
import CusTomerUserApi from '../../../api/customermanagement/customuser';
import { FacUserModel, CustomUserModel, TAffiliatedunitModel } from "../../../types";
import TAffiliatedunitAction from '../../../api/customermanagement/taffiliatedunit'
import tool from "../../../until/tool";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import { use } from "echarts";

const register=()=>{
  router.push('/userRegister');
}

type FormInstance = InstanceType<typeof ElForm>;
const txtUserName=ref();
const txtPwd=ref();

const store = useStore();
const router = useRouter();
const state = reactive({
  ruleForm: {
    username: "",
    password: "",
    logintype: "1"
  },
  options: [
    {
      value: '0',
      label: '内部',
    },
    {
      value: '1',
      label: '客户',
    },
  ],
  rules: {
    username: [{ required: true, message: "请输入用户名", trigger: "blur", },],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    logintype: [{ required: true, message: "请选择登陆类型", trigger: "blur", },],
  },
});
//const ruleForm = ref<FormInstance>();
const { ruleForm, options } = toRefs(state);

const login: any = ref(null);
const handlelogin = () => {
  login.value.validate((valid: any) => {
    if (valid) {
      if (state.ruleForm.logintype === "0") {
        FacUserApi.Login(state.ruleForm.username, state.ruleForm.password).then(result => {

          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              if (res) {
                //setToken("admin");
                let user = res as FacUserModel;
                setToken(user.accessToken);
                
                localStorage.setItem("UserName", user.userName);
                localStorage.setItem("CustomerId", user.userId);
                localStorage.setItem("UserType", "0");
                localStorage.setItem("LoginId", user.loginId);
                localStorage.setItem("AdminFlag", user.adminFlag);
                localStorage.setItem("UnitCode", "");               //不置空会导致从客户切换到内部用户时,仍然有UnitCode
                document.title='水务感知装备研发运营管理平台';
                router.push({
                  path: "/",
                });
              }
            } else {
              ElMessage.error(error);
            }
          }
        }).catch(error => {
          //请求失败时的操作     
          ElMessage.error(error);
        })
      } else {
        CusTomerUserApi.Login(state.ruleForm.username, state.ruleForm.password).then(result => {

          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              if (res) {
                //setToken("admin");
                let user = res as CustomUserModel;
                setToken(user.accessToken);
                localStorage.setItem("CustomerId", user.userId);
                localStorage.setItem("UserType", "1");
                localStorage.setItem("UnitCode", user.unitCode);
                localStorage.setItem("UserName", user.userName);
                localStorage.setItem("LoginId", user.loginId);
                localStorage.setItem("AdminFlag", user.adminFlag);
                getUnitInfo(user.unitCode);
                router.push({
                  path: "/",
                });
                //如果登陆账户属于太原煤气单位,则修改Title(临时办法,后续仍有此需求,将名称存放在数据库中) 2023-04-25 guozhao
                if(user.unitCode==='39ec081ceb9740afad8fe14c4ea1349f'){
                  document.title='太原天然气有限公司边缘AI抄表器查询系统';
                }
              }
            } else {
              ElMessage.error(error);
            }
          }
        }).catch(error => {
          //请求失败时的操作     
          ElMessage.error(error);
        })
      }
    }
  });
};

onMounted(() => {
  setToken("admin");

  let userType = localStorage.getItem("UserType");
  if (userType) {
    state.ruleForm.logintype = userType;
  }
  let loginId = localStorage.getItem("LoginId") + "";
  if (!tool.stringIsNullOrEmpty(loginId)&&loginId!=='null') {
    state.ruleForm.username = loginId;
  txtPwd.value.focus();
  }else{
    txtUserName.value.focus();
  }
});

const getUnitInfo = (unitCode: string) => {
  TAffiliatedunitAction.FindTAffiliatedunit(unitCode).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        if (res) {
          let unitModel = res as TAffiliatedunitModel;
          localStorage.setItem("UnitType", unitModel.unitType);
          localStorage.setItem("CreateUnitFalg", unitModel.createUnitFalg === null ? "0" : unitModel.createUnitFalg);
        }
      } else {
        ElMessage.error(error);
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
  })
}

// resetForm
const resetForm = () => {
	ruleForm.value.username='';
	ruleForm.value.password='';
};
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
