<template>
  <NavBar :count="0" :title="'登录'"></NavBar>
  <LoginLayout>
    <template #form-box>
      <u-form
        labelPosition="left"
        :model="model1"
        :rules="rules"
        ref="loginForm"
        :labelWidth="0"
      >
        <u-form-item prop="userInfo.dpName" @click="state.isShow = true">
          <u-input
            v-model="model1.userInfo.dpName"
            :placeholder="`请选择基地名称`"
            clearable
            :customStyle="{}"
            border="none"
            :disabledColor="''"
            :disabled="true"
          >
            <!-- @change="(e:any) => {handleInput(e, item)}"
            @clear="handleClear(item)" -->
          </u-input>
          <template #right>
            <u-icon name="arrow-right" color="#dadbde"></u-icon>
          </template>
        </u-form-item>
        <u-form-item prop="userInfo.userName">
          <u-input
            v-model="model1.userInfo.userName"
            placeholder="请输入手机号"
            :shape="'circle'"
            clearable
            :customStyle="{
              'border-color':
                currentFocus === 'userName' ? '#00dcee !important' : '',
            }"
            border="none"
            type="number"
            @focus="handleFocus('userName')"
            @change="(e:any) => {handleInput(e, 'userName')}"
            @clear="handleClear({ key: 'userName' })"
          >
          </u-input>
        </u-form-item>
        <u-form-item prop="userInfo.password">
          <u-input
            v-model="model1.userInfo.password"
            placeholder="请输入密码"
            :shape="'circle'"
            type="text"
            :password="!isShowPwd"
            :customStyle="{
              'border-color':
                currentFocus === 'password' ? '#00dcee !important' : '',
            }"
            border="none"
            @focus="handleFocus('password')"
            clearable
            @change="(e:any) => {handleInput(e, 'password')}"
            @clear="handleClear({ key: 'password' })"
          >
            <template #suffix>
              <image
                v-if="!isShowPwd"
                :src="`https://backend-common.obs.cn-east-3.myhuaweicloud.com/static/pagesLogin/login/hide.png`"
                class="custom-icon"
                @click="isShowPwd = true"
              ></image>
              <image
                v-else
                :src="`https://backend-common.obs.cn-east-3.myhuaweicloud.com/static/pagesLogin/login/show.png`"
                class="custom-icon"
                @click="isShowPwd = false"
              ></image>
            </template>
          </u-input>
        </u-form-item>
      </u-form>
      <view class="remember-box">
        <view>
          <u-checkbox-group v-model="checkGroup.rememberCheck">
            <u-checkbox
              :customStyle="{}"
              :key="1"
              :label="'记住密码?'"
              :name="1"
              :size="'25rpx'"
              :activeColor="'#00dcee'"
              :labelSize="'25rpx'"
              :labelColor="'#000000'"
            ></u-checkbox>
          </u-checkbox-group>
        </view>
        <text @click="handleForgetPwd">忘记密码</text>
      </view>
      <view class="login-btn">
        <u-button
          @click="submit"
          type="primary"
          :customStyle="{
            'border-radius': '43rpx',
          }"
          >立即登录</u-button
        >
      </view>
      <view class="agree">
        <u-checkbox-group v-model="checkGroup.agreeCheck">
          <u-checkbox
            :key="1"
            :size="'25rpx'"
            :activeColor="'#00dcee'"
            :name="1"
          ></u-checkbox>
        </u-checkbox-group>
        <view>
          我已阅读并同意用户
          <text class="agree-item" @click="openDoc('爱梵达用户服务协议')"
            >《 服务协议 》</text
          >
          和
          <text class="agree-item" @click="openDoc('隐私政策')"
            >《 隐私政策 》</text
          >
          <view> 未开通服务站点无法登录 </view>
        </view>
      </view>
    </template>
  </LoginLayout>

  <u-action-sheet
    :actions="state.dpList"
    :title="'基地名称'"
    :show="state.isShow"
    @select="(v: any) => handleSelect(v)"
    @close="state.isShow = false"
    :closeOnClickAction="true"
  ></u-action-sheet>
</template>

<script setup lang="ts">
import { ProfileApi } from "@/services/index";
import LoginLayout from "./components/loginLayout.vue";
import { useMemberStore } from "@/store/index";
import valid from "@/utils/validate";
import pinia from "@/store";

const handleClear = (item: any) => {
  setTimeout(() => {
    (model1.userInfo as any)[item.key] = "";
  }, 100);
};
const store = useMemberStore(pinia);
const loginForm = ref(null);
const model1 = reactive({
  userInfo: {
    userName: "",
    password: "",
    dpName: "",
  },
});
// 控制focus 边框样式
const currentFocus = ref("");
// 控制密码显示隐藏
const isShowPwd = ref(false);
// 记住密码 // 同意协议
const checkGroup = reactive({
  rememberCheck: [],
  agreeCheck: [],
});

const rules = ref({
  "userInfo.dpName": {
    type: "string",
    required: true,
    message: "请选择基地名称",
    trigger: ["blur", "change"],
  },
  "userInfo.userName": {
    type: "string",
    required: true,
    message: "请输入手机号",
    trigger: ["blur", "change"],
  },
  "userInfo.password": {
    type: "string",
    required: true,
    message: "请输入密码",
    trigger: ["blur", "change"],
  },
});

const handleInput = (e: any, key: string) => {
  if (key === "userName") {
    const temp = e?.replace(valid.valid_number, "");
    setTimeout(() => {
      (model1.userInfo as any)[key] = temp;
    }, 10);
  }

  if (key === "password") {
    const temp = e?.replace(valid.valid_no_cn, "");
    setTimeout(() => {
      (model1.userInfo as any)[key] = temp;
    }, 10);
  }
};

const handleFocus = (attr: string) => {
  currentFocus.value = attr;
};
const submit = () => {
  if (model1.userInfo.userName) {
    if (!valid.mobile.pattern.test(model1.userInfo.userName)) {
      uni.showToast({ icon: "none", title: "请输入正确的手机号" });
      return;
    }
  }

  if (model1.userInfo.password) {
    if (!valid.valid_password.pattern.test(model1.userInfo.password)) {
      uni.showToast({
        icon: "none",
        title: valid.valid_password.message,
      });
      return;
    }
  }

  (loginForm.value as any).validate().then((res: any) => {
    if (res) {
      if (checkGroup.agreeCheck.length === 0) {
        uni.showToast({
          title: "请同意协议",
          icon: "none",
        });
        return;
      }
      ProfileApi.loginByAccount(model1.userInfo).then((res: any) => {
        if (res.code === 200) {
          store.setProfile(res.data);
          uni.reLaunch({
            url: "/pagesHome/index", // 要跳转到的页面路径
          });
        }
      });
    }
  });
};
const handleForgetPwd = () => {
  uni.navigateTo({
    url: "/pagesLogin/login/forgetPwd", // 要跳转到的页面路径
  });
};

const openDoc = (item: string) => {
  //文件预览

  uni.downloadFile({
    url: `https://backend-common.obs.cn-east-3.myhuaweicloud.com/static/pages/login/${item}.docx`,
    success: function (res) {
      setTimeout(
        () =>
          uni.openDocument({
            filePath: res.tempFilePath,
            showMenu: false,
            success: function () {
              console.log("打开文档成功");
            },
            fail: function () {
              uni.showToast({
                title: "暂不支持此类型",
                duration: 2000,
                icon: "none",
              });
            },
          }),
        100
      );
    },
    fail: function (res) {
      console.log(res); //失败
    },
  });

  // uni.openDocument({
  //   filePath: `https://backend-common.obs.cn-east-3.myhuaweicloud.com/static/pages/login/${item}.docx`,
  //   showMenu: true,
  //   success: function (res) {
  //     uni.showToast({ title: "打开成功" });
  //   },
  // });
};

const handleSelect = (v: any) => {
  state.isShow = false;
  state.dpObj = v;
  model1.userInfo.dpName = v.name;
  console.log(v.dbIp);
  store.setChildPath(v.dbIp);
};

const state = reactive({
  dpList: [],
  isShow: false,
  dpObj: {},
});

// 获取基地信息
ProfileApi.getDbInfo({}).then((res) => {
  if (res.code === 200) {
    state.dpList = res.data.map((item: any) => {
      return { name: item.dbName, ...item };
    });
  }
});
</script>

<style lang="scss" scoped>
::v-deep .u-form-item__body__right__content {
  border-radius: 100px;
  border: 1px solid #dadbde;
}
.custom-icon {
  width: 37.18rpx;
  height: 18.59rpx;
}
.remember-box {
  display: flex;
  font-size: 25rpx;
  font-family: Source Han Sans CN;
  font-weight: 400;
  justify-content: space-between;
  padding: 10rpx;
  color: $u-primary;
  align-items: center;
}
.login-btn {
  margin-top: 23.72rpx;
}
.agree {
  display: flex;
  font-size: 21rpx;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #000000;
  margin-top: 10rpx;
  align-items: flex-start;
  text-align: center;
  line-height: 41rpx;
  margin-top: 26.28rpx;
  .agree-item {
    color: $u-primary;
  }
}
</style>
