<template>
  <s-layout title="新用户注册" :bgStyle="{ color: '#fff' }">
    <view class="content-block">
      <uni-forms
        ref="registerRef"
        v-model="state.model"
        :rules="state.rules"
        validateTrigger="bind"
        labelWidth="140"
        labelAlign="left"
        labelPosition="top"
      >
        <uni-forms-item name="shopName" label="店铺名" required>
          <uni-easyinput
            placeholder="请输入店铺名"
            v-model="state.model.shopName"
            paddingLeft="15"
          >
          </uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="shopkeeperName" label="店主姓名" required>
          <uni-easyinput
            placeholder="请输入店主姓名"
            v-model="state.model.shopkeeperName"
            paddingLeft="15"
          >
          </uni-easyinput>
        </uni-forms-item>
        <uni-forms-item
          name="fullArea"
          label="省市区"
          required
          @tap="state.showRegion = true"
        >
          <uni-easyinput
            placeholder="点击选择"
            v-model="state.fullArea"
            type="number"
            paddingLeft="15"
            :styles="{ disableColor: 'transparent', borderColor: '#e5e5e5' }"
            disabled
          >
            <template #right>
              <image
                style="width: 24rpx; height: 15rpx; margin-right: 30rpx"
                :src="sheep.$url.static('/static/icons/arrow-down-icon.png')"
                mode=""
              ></image>
            </template>
          </uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="address" label="详细地址" required @tap="chooseAddress">
          <uni-easyinput
            placeholder="请输入详细地址"
            v-model="state.model.address"
            paddingLeft="15"
						disabled
          >
            <template #right>
							<view class="right-box" >
								<image
								  style="width: 32rpx; height: 30rpx; margin-right: 30rpx"
								  :src="sheep.$url.static('/static/icons/address-icon.png')"
								  mode=""
								></image>
							</view>
            </template>
          </uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="images" label="门头照片" required>
          <s-uploader
            v-model:url="state.images"
            fileMediatype="image"
            limit="5"
            mode="grid"
            :imageStyles="{ width: '200rpx', height: '200rpx' }"
          />
        </uni-forms-item>
        <uni-forms-item
          name="businessTime"
          label="营业时间"
          required
          @tap="showTime('businessTime')"
        >
          <uni-easyinput
            placeholder="请选择营业时间"
            v-model="state.model.businessTime"
            paddingLeft="15"
            :styles="{ disableColor: 'transparent', borderColor: '#e5e5e5' }"
            disabled
          >
            <template #right>
              <image
                style="width: 32rpx; height: 32rpx; margin-right: 30rpx"
                :src="sheep.$url.static('/static/icons/calendar-icon.png')"
                mode=""
              ></image>
            </template>
          </uni-easyinput>
        </uni-forms-item>
        <uni-forms-item
          name="deliveryTime"
          label="送货时间"
          required
          @tap="showTime('deliveryTime')"
        >
          <!-- 时间弹窗 -->
          <uni-easyinput
            placeholder="请选择送货时间"
            v-model="state.model.deliveryTime"
            paddingLeft="15"
            :styles="{ disableColor: 'transparent', borderColor: '#e5e5e5' }"
            disabled
          >
            <template #right>
              <image
                style="width: 32rpx; height: 32rpx; margin-right: 30rpx"
                :src="sheep.$url.static('/static/icons/calendar-icon.png')"
                mode=""
              ></image>
            </template>
          </uni-easyinput>
        </uni-forms-item>
				<uni-forms-item label="邀请码">
				  <uni-easyinput
				    placeholder="请输入邀请码"
				    v-model="state.model.inviteCode"
				    paddingLeft="15"
						type="number"
				  >
				  </uni-easyinput>
				</uni-forms-item>
      </uni-forms>
      <button class="toLoginBtn ss-reset-button" @tap="toRegister">注册</button>
      <view class="agreement-box ss-flex">
       <!-- <radio-group @change="onChange" class="ss-flex ss-col-center">
          <label class="radio ss-flex"> -->
            <radio
              :checked="protocol"
              color="var(&#45;&#45;ui-BG-Main)"
              style="transform: scale(0.8)"
							@tap.top="onChange"
            />
            <view class="agreement-text ss-flex ss-col-center ss-m-l-8" :class="{'isAgreement': protocol}">
              我已阅读并同意
              <view
                class="tcp-text"
                @tap.stop="
                  onProtocol(1, '用户协议', 'small:program:user:agreement')
                "
              >
                《用户协议》
              </view>
            </view>
        <!--  </label>
        </radio-group> -->
      </view>
    </view>
		<view class="safe-box"></view>

    <uni-popup
      ref="timePopupRef"
      background-color="#fff"
      :mask-click="false"
      borderRadius="24rpx"
    >
      <su-toolbar
        cancelColor="#6666"
        confirmColor="var(--ui-BG-Main)"
        cancelText="取消"
        confirmText="确定"
        @cancel="timePopupRef.close()"
        @confirm="confirm"
      ></su-toolbar>
      <picker-view
        @change="bindChange"
        class="picker-view"
        :value="defaultIndex"
      >
        <picker-view-column>
          <view class="item" v-for="(item, index) in columns[0]" :key="index">{{
            item
          }}</view>
        </picker-view-column>
        <picker-view-column>
          <view class="item" v-for="(item, index) in columns[1]" :key="index">{{
            item
          }}</view>
        </picker-view-column>
      </picker-view>
    </uni-popup>
    <!-- 省市区弹窗 -->
    <su-region-picker
      v-if="state.showRegion"
      :show="state.showRegion"
      @cancel="state.showRegion = false"
      @confirm="onRegionConfirm"
    >
    </su-region-picker>

    <!-- 注册成功提示 -->
    <uni-popup
      ref="popupRef"
      background-color="#fff"
      :mask-click="false"
      borderRadius="24rpx"
    >
      <view class="popup-box">
        <view class="ss-flex ss-row-center">
          <image
            class="scuss-img"
            :src="sheep.$url.static('/static/registerScu-img.png')"
            mode=""
          ></image>
        </view>
        <view class="scuss-text"
          >您的注册申请已经提交，审核通过之后我们将会短信通知您</view
        >
        <button class="toHomeBtn ss-reset-button" @tap="toHome">
          返回主页
        </button>
      </view>
    </uni-popup>
    <!-- 	<up-popup :show="registerScuShow" mode="center" :round="12" :closeOnClickOverlay="false" :safeAreaInsetBottom="false">
		</up-popup> -->
  </s-layout>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import sheep from "@/sheep";
import _ from "lodash";
import {
  shopName,
  shopkeeperName,
  fullArea,
  businessTime,
  deliveryTime,
  address,
  images,
} from "@/sheep/validate/form";
import { reactive, ref, unref } from "vue";
const state = reactive({
  showRegion: false,
  codeText: "获取验证码",
  model: {
    phone: "",
    shopName: "",
    shopkeeperName: "",
    province: "",
    city: "",
    area: "",
    address: "",
    businessTime: "",
    deliveryTime: "",
		inviteCode:"",
		latitude:"",//纬度
		longitude:"",//经度
  },
  fullArea: "",
  images: [],
  rules: {
    shopName,
    shopkeeperName,
    fullArea,
    businessTime,
    deliveryTime,
    address,
    images,
  },
});
const protocol = ref(false);
const popupRef = ref(null);
const timePopupRef = ref(null);

const registerScuShow = ref(false);
const defaultIndex = ref([0, 0]);
const timeType = ref();
const timeShow = ref(true);
const timeValue = ref([0, 0]);
const columns = reactive([
  [
    "00:00",
    "01:00",
    "02:00",
    "03:00",
    "04:00",
    "05:00",
    "06:00",
    "07:00",
    "08:00",
    "09:00",
    "10:00",
    "11:00",
    "12:00",
    "13:00",
    "14:00",
    "15:00",
    "16:00",
    "17:00",
    "18:00",
    "19:00",
    "20:00",
    "21:00",
    "22:00",
    "23:00",
  ],
  [
    "00:00",
    "01:00",
    "02:00",
    "03:00",
    "04:00",
    "05:00",
    "06:00",
    "07:00",
    "08:00",
    "09:00",
    "10:00",
    "11:00",
    "12:00",
    "13:00",
    "14:00",
    "15:00",
    "16:00",
    "17:00",
    "18:00",
    "19:00",
    "20:00",
    "21:00",
    "22:00",
    "23:00",
  ],
]);

onLoad((e) => {
  state.model.phone = e.mobile;
  getAreaData();
});
// 获取省市区
const getAreaData = () => {
  if (_.isEmpty(uni.getStorageSync("areaData"))) {
    sheep.$api.data.area().then((res) => {
      if (res.code === 200) {
        uni.setStorageSync("areaData", res.data);
      }
    });
  }
};
const chooseAddress = ()=>{
	uni.chooseLocation({
		success:(res)=> {
			state.model.address = res.name
			state.model.latitude = res.latitude
			state.model.longitude = res.longitude
			// console.log('位置名称：' + res.name);
			// console.log('详细地址：' + res.address);
			// console.log('纬度：' + res.latitude);
			// console.log('经度：' + res.longitude);
		},
		fail:(err)=>{
			console.log(err,'err')
		}
	});
}
// 时间选择
const showTime = (type) => {
  timeType.value = type;
  defaultIndex.value = [0, 0];
  timePopupRef.value.open("bottom");
};
const confirm = () => {
  state.model[timeType.value] =
    columns[0][timeValue.value[0]] + "-" + columns[1][timeValue.value[1]];
  timePopupRef.value.close();
};
const bindChange = (e) => {
  timeValue.value = e.detail.value;
};
//勾选协议
function onChange() {
  protocol.value = !protocol.value;
}

const onRegionConfirm = (e) => {
  const { city_name, district_name, province_name } = e;
  state.fullArea = `${province_name}-${city_name}-${district_name}`;
  state.model = {
    ...state.model,
    province: province_name,
    city: city_name,
    area: district_name,
  };
  state.showRegion = false;
};

const toHome = () => {
  popupRef.value.close();
  uni.switchTab({
    url: "/pages/index/index",
  });
};

// async function onSelect({ type, data }) {
// 	console.log(data,'data')
//   let msg = '';
// 	const { data } = await sheep.$api.app.upload(data.tempFiles[0].path, 'default');
// 	msg = {
// 		from: 'customer',
// 		mode: 'image',
// 		date: new Date().getTime(),
// 		content: {
// 			url: fullurl,
// 			path: path,
// 		},
// 	};
// 	console.log(msg)
//   // if (msg) {
//   //   socketSendMsg(msg, () => {
//   //     scrollBottom();
//   //   });
//   //   // scrollBottom();
//   //   chat.showTools = false;
//   //   chat.showSelect = false;
//   //   chat.selectMode = '';
//   // }
// }

// 查看协议
function onProtocol(id, title, key) {
  sheep.$router.go("/pages/public/richtext", {
    id,
    title,
    key,
  });
}

// 注册
const registerRef = ref(null);
const toRegister = async () => {
  if (!protocol.value) {
    sheep.$helper.toast("请先阅读并勾选协议");
    return;
  }
  const validate = await unref(registerRef)
    .validate()
    .catch((error) => {
      console.log("error: ", error);
    });
  if (!validate) return;
  if (state.images.length == 0) {
    return sheep.$helper.toast("请上传门头照片");
  }
  let params = {
    ...state.model,
    picture: state.images.toString(),
  };
  sheep.$api.user
    .addShopRegistration(params)
    .then((res) => {
      console.log(res, "res");
      if (res.code == 200) {
        // registerScuShow.value = true
        popupRef.value.open("center");
      } else {
        sheep.$helper.toast(res.msg);
      }
    })
    .catch((err) => {
      sheep.$helper.toast(res.msg);
    });
};
</script>

<style lang="scss" scoped>
.picker-view {
  height: 400rpx;
  margin-top: 20rpx;
}
.item {
  line-height: 34px;
  text-align: center;
}
.content-block {
  padding: 0 60rpx;
}
::v-deep .is-disabled {
  color: #333;
}
.icon {
  width: 199rpx;
  height: 199rpx;
}
.toLoginBtn {
  height: 88rpx;
  background: #f39801;
  border-radius: 16rpx;
  color: #fff;
  margin-bottom: 32rpx;
  margin-top: 30rpx;
}

.agreement-box {
  .tcp-text {
    color: #f49700;
  }

  .agreement-text {
    color: #adb5bd;
    font-size: 24rpx;
  }
	.isAgreement {
		color: #333;
	}
}

.safe-box {
		width: 100%;
    height: calc(constant(safe-area-inset-bottom) / 5 * 3);
    height: calc(env(safe-area-inset-bottom) / 5 * 3);
  }

.popup-box {
  width: 590rpx;
  padding: 40rpx;
  .scuss-img {
    width: 240rpx;
    height: 240rpx;
  }
  .scuss-text {
    color: #17191c;
    text-align: center;
    font-size: 28rpx;
    font-weight: bold;
    margin: 10rpx 0 28rpx;
    padding: 0 28rpx;
  }
  .toHomeBtn {
    height: 80rpx;
    background: #f39801;
    border-radius: 16rpx;
    color: #fff;
    font-size: 32rpx;
  }
}

.right-box {
	height: 100%;
}

</style>
