<script setup>
import { ref, reactive, watch } from "vue";
import { post, get } from "@/utils/request";
import { useRequest } from "@/composables/useRequest";

const SendCodeByPhone = (params) => post("/Common/SendCodeByPhone", params);
const PhoneLoginReg = (params) => post("/Login/PhoneLoginReg", params);

// 响应式表单数据
const form = ref({
  mobile: "",
  code: "",
  password: "",
  agentId: null,
  agentValue: "",
  userType: 4,
  userTypeName: "全民营销",
  readName: "",
});
const columnsAgent = ref([]);
const columnsType = ref([
  {
    text: "中介",
    value: 3,
  },
  {
    text: "全民营销",
    value: 4,
  },
]);
// 校验规则
const rules = {
  mobile: [
    {
      required: true,
      message: "请输入用户名或手机号",
      trigger: ["change", "blur"],
    },
    {
      // 自定义验证函数，见上说明
      validator: (rule, value, callback) => {
        // 上面有说，返回true表示校验通过，返回false表示不通过
        // uni.$u.test.mobile()就是返回true或者false的
        return uni.$u.test.mobile(value);
      },
      message: "手机号码不正确",
      // 触发器可以同时用blur和change
      trigger: ["change", "blur"],
    },
  ],
  code: [
    {
      required: true,
      message: "请输入验证码",
      trigger: ["change", "blur"],
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["change", "blur"],
    },
  ],
  readName: [
    {
      required: true,
      message: "请输入真实姓名",
      trigger: ["change", "blur"],
    },
  ],
  agentValue: [
    {
      required: true,
      message: "请选择中介",
      trigger: ["change", "blur"],
    },
  ],
};

const tips = ref("");
const value = ref("");
const seconds = ref(60);
const uCodeRef = ref(null);

watch(value, (newValue, oldValue) => {
  // console.log('v-model', newValue);
});

const codeChange = (text) => {
  tips.value = text;
};

const getCode = async () => {
  console.log("uCodeRef.canGetCode: ", uCodeRef.value);
  if (!form.value.mobile) {
    return uni.$u.toast("请先输入手机号");
  }
  if (uCodeRef.value.canGetCode) {
    // 模拟向后端请求验证码
    uni.showLoading({
      title: "正在获取验证码",
    });
    const data = await SendCodeByPhone({ phone: form.value.mobile });
    console.log("data: ", data);
    if (data) {
      setTimeout(() => {
        uni.hideLoading();
        // 这里此提示会被start()方法中的提示覆盖
        uni.$u.toast("验证码已发送");
        // 通知验证码组件内部开始倒计时
        uCodeRef.value.start();
      }, 2000);
    } else {
      uni.hideLoading();
    }
  } else {
    uni.$u.toast("倒计时结束后再发送");
  }
};

const change = (e) => {
  console.log("change", e);
};
const showAgent = ref(false);
const confirmAgent = (e) => {
  console.log("e: ", e);
  form.value.agentValue = e.value[0].text;
  form.value.agentId = e.value[0].value;
  showAgent.value = false;
};

const showType = ref(false);
const confirmType = (e) => {
  console.log("e: ", e);
  form.value.userTypeName = e.value[0].text;
  form.value.userType = e.value[0].value;
  if (form.value.userType == 4) {
    form.value.agentValue = "";
    form.value.agentId = "";
  }
  showType.value = false;
};

const uFormRef = ref(null);
function submit() {
  uFormRef.value
    .validate()
    .then(async (valid) => {
      if (valid) {
        if (!aloneChecked.value) {
          return uni.$u.toast("请同意用户协议与隐私政策");
        }
        // uni.$u.toast('校验通过');
        let res = await PhoneLoginReg({
          phone: form.value.mobile,
          code: form.value.code,
          password: form.value.password,
          agencyId: form.value.agentId || null,
          userType: form.value.userType,
          name: form.value.readName,
        });
        console.log("res: ", res);
        if (res) {
          uni.$u.toast("注册并登录成功");
          uni.setStorageSync("token", res);
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/index/index",
            });
          }, 1500);
        }
      } else {
        // uni.$u.toast('校验失败');
      }
    })
    .catch(() => {
      // 处理验证错误
      // uni.$u.toast('校验失败');
    });
}
const customStyle = {
  height: "84px",
  "border-radius": "8px",
  background: "#f7f8fa",
  padding: "0 20px !important",
  position: "relative",
};
const aloneChecked = ref(false);
const getRichText = (url) => {
  uni.navigateTo({
    url,
  });
};
const GetAgencys = (params) => get("/Buss/GetAgencys", params);
const { data, loading, error, refresh } = useRequest(GetAgencys, {
  initialParams: {},
  immediate: true, // 默认立即执行
});
watch([loading, error], () => {
  if (!loading.value) {
    // 加载完成
    if (error.value) {
      console.log("请求失败: ", error.value); // 打印错误信息
    } else {
      console.log("请求成功: ", data.value); // 成功时获取数据
      columnsAgent.value = data.value.map((item) => {
        return {
          text: item.name,
          value: item.id,
        };
      });
    }
  }
});
</script>
<template>
  <view>
    <view class="company u-flex u-flex-y-center">
      <image src="/static/images/logo.png" class="company-icon" mode="widthFix"></image>
      <view class="company-head">
        <view class="name">华都渠道管家</view>
        <view class="into">专业的房产销售管理平台</view>
      </view>
    </view>
    <view class="account">
      <view>
        <up-form :model="form" :rules="rules" ref="uFormRef">
          <up-form-item label="" @click.prevent="showType = true">
            <up-input :customStyle="customStyle" v-model="form.userTypeName" border="none" :disabled="true"
              placeholder="请选择身份">
              <template #suffix>
                <up-icon name="arrow-down" color="#222222" size="12"></up-icon>
              </template>
            </up-input>
          </up-form-item>
          <up-picker :show="showType" @confirm="confirmType" @close="showType = false" @cancel="showType = false"
            :columns="[columnsType]" valueKey="value" labelKey="text"></up-picker>
          <up-form-item label="" prop="readName">
            <up-input :customStyle="customStyle" v-model="form.readName" border="none" placeholder="请输入真实姓名" />
          </up-form-item>
          <up-form-item label="" prop="mobile">
            <up-input :customStyle="customStyle" v-model="form.mobile" border="none" placeholder="请输入用户名或手机号" />
          </up-form-item>
          <up-form-item label="" prop="code">
            <up-input :customStyle="customStyle" v-model="form.code" border="none" placeholder="请输入验证码">
              <template #suffix>
                <up-code ref="uCodeRef" @change="codeChange" :seconds="seconds"></up-code>
                <up-text :text="tips" @click="getCode" class="code-text"></up-text>
              </template>
            </up-input>
          </up-form-item>

          <up-form-item label="" prop="password">
            <up-input :customStyle="customStyle" v-model="form.password" type="password" border="none"
              placeholder="设置密码" />
          </up-form-item>
          <up-form-item label="" prop="agentValue" @click.prevent="showAgent = true" v-if="form.userType == 3">
            <up-input :customStyle="customStyle" v-model="form.agentValue" border="none" :disabled="true"
              placeholder="所属中介">
              <template #suffix>
                <up-icon name="arrow-down" color="#222222" size="12"></up-icon>
              </template>
            </up-input>
          </up-form-item>
          <up-picker :show="showAgent" @confirm="confirmAgent" @close="showAgent = false" @cancel="showAgent = false"
            :columns="[columnsAgent]" valueKey="value" labelKey="text"></up-picker>
        </up-form>
      </view>
    </view>
    <view class="">
      <up-checkbox :customStyle="{ marginBottom: '8px' }" name="agree" usedAlone v-model:checked="aloneChecked"
        size="14" labelSize="14" labelColor="#666666">
        <template #label>
          <view class="account-tip">
            请阅读并同意
            <text @click.prevent="getRichText('/pages/mine/richtext?type=1')">用户协议</text>
            与
            <text @click.prevent="getRichText('/pages/mine/richtext?type=2')">隐私政策</text>
          </view>
        </template>
      </up-checkbox>
    </view>

    <button type="primary" class="regiset-btn" @click="submit">注册</button>
    <navigator url="/pages/login/index" class="account-tip">
      已有账号？
      <text>立即登录</text>
    </navigator>
  </view>
</template>

<style>
page {
  padding: px2rpx(10) px2rpx(52);
  box-sizing: border-box;
}
</style>
<style lang="scss" scoped>
@import "@/uni.scss";

button {
  background-color: #ea002a;
  font-size: px2rpx(14);
  font-weight: normal;
  height: px2rpx(84);
  line-height: px2rpx(84);
}

.company {
  padding: px2rpx(40) 0;
}

.company-icon {
  width: px2rpx(104);
  height: px2rpx(104);
  margin-right: px2rpx(14);
}

.company-head {
  .name {
    font-size: px2rpx(20);
    font-weight: 500;
    color: #ea002a;
    margin-bottom: px2rpx(2);
  }

  .into {
    font-size: px2rpx(13);
    font-weight: 350;
    color: #222222;
  }
}

.account {
  .input {
    height: px2rpx(84);
    border-radius: px2rpx(8);
    background: #f7f8fa;
    padding: 0 px2rpx(20) !important;
  }
}

.regiset-btn {
  margin: px2rpx(20) 0;
}

.account-tip {
  color: #666666;
  font-size: px2rpx(13);
  text-align: center;

  text {
    color: #ea002a;
  }
}

.code-text {
  padding-right: px2rpx(20);
}

:deep(.u-text__value) {
  color: #ea002a !important;
  font-size: px2rpx(14) !important;
}
</style>
