<script lang="ts" setup>
import Taro from '@tarojs/taro';
import { ref } from 'vue';
import { applyMer, getMerTypeList, getVerifyCode } from '@/api/user';
import Upload from '@/components/Upload.vue';

const visible = ref(false);

const merGooType = ref(false);

// 验证码按钮文字
const smsStr = ref('获取验证码');

// 验证码按钮是否禁用
const smsDisabled = ref(false);

// 表单数据
const formValue = ref<{
  name: string;
  userName: string;
  phone: string;
  mobile: string;
  code: string;
  classId: string;
  merGooTypeStr: string;
  license: any[];
  front: any[];
  back: any[];
  head_photo: any[];
  img: any[];
  bank: string;
  bank_card: string;
  bank_name: string;
  bank_user: string;
  address: string;
}>({
  name: '',
  userName: '',
  phone: '',
  mobile: '',
  code: '',
  classId: '',
  merGooTypeStr: '',
  license: [],
  front: [],
  back: [],
  head_photo: [],
  img: [],
  bank: '',
  bank_card: '',
  bank_name: '',
  bank_user: '',
  address: '',
});

const merGooList = ref([]);

// 表单校验
const ruleForm = ref<any>(null);

Taro.useLoad(() => {
  getMerType();
});

// 获取商户类型
const getMerType = async () => {
  try {
    const res = await getMerTypeList();
    merGooList.value = res.data.class.map((item: any) => ({
      text: item.name,
      value: item.ID,
    }));
  } catch (e) {
    Taro.showToast({
      title: e.msg,
      icon: 'none',
    });
  }
};

// 关闭弹窗
const onOk = async () => {
  try {
    const data = {
      ...formValue.value,
      license: formValue.value.license[0]?.url,
      front: formValue.value.front[0]?.url,
      back: formValue.value.back[0]?.url,
      head_photo: formValue.value.head_photo[0]?.url,
      img: formValue.value.img.map((item: any) => item.url).join(','),
    };
    const res = await applyMer(data);
    Taro.showToast({
      title: res.msg,
      icon: 'none',
    });
    setTimeout(() => {
      Taro.switchTab({
        url: '/pages/index/index',
      });
    }, 3000);
  } catch (e) {
    Taro.showToast({
      title: e.msg,
      icon: 'none',
    });
  }
  visible.value = false;
};

// 打开弹窗
// const open = () => {
//     console.log("open");
//     visible.value = true;
// };

// 获取验证码
const getSmsCode = () => {
  ruleForm.value.validate('phone').then(async ({ valid }: any) => {
    if (valid) {
      try {
        await getVerifyCode({
          phone: formValue.value.phone.toString(),
        });
        smsDisabled.value = true;
        let time = 60;
        const timer = setInterval(() => {
          time--;
          smsStr.value = `${time}s`;
          if (time === 0) {
            clearInterval(timer);
            smsDisabled.value = false;
            smsStr.value = '获取验证码';
          }
        }, 1000);
      } catch (e) {
        Taro.showToast({
          title: e.message,
          icon: 'none',
        });
      }
    }
  });
};

// 选择经营类目
const confirmGooType = (e: any) => {
  formValue.value.merGooTypeStr = e.selectedOptions[0].text;
  formValue.value.classId = e.selectedOptions[0].value;
  merGooType.value = false;
};

// 提交
const submit = () => {
  ruleForm.value.validate().then(({ valid, errors }: any) => {
    if (valid) {
      console.log('success', formValue.value);
      visible.value = true;
    } else {
      console.log('error submit!!', errors);
    }
  });
};
</script>

<template>
  <view>
    <nut-form ref="ruleForm" class="form" :model-value="formValue">
      <nut-form-item
        required
        label="商户名称"
        prop="name"
        :rules="[
          {
            required: true,
            message: '请输入商户名称',
          },
        ]">
        <input
          type="text"
          v-model="formValue.name"
          placeholder="请输入商户名称" />
      </nut-form-item>
      <nut-form-item
        required
        label="用户姓名"
        prop="userName"
        :rules="[
          {
            required: true,
            message: '请输入用户姓名',
          },
        ]">
        <input
          type="text"
          v-model="formValue.userName"
          placeholder="请输入真实姓名" />
      </nut-form-item>
      <nut-form-item
        required
        label="联系电话"
        prop="phone"
        :rules="[
          {
            required: true,
            message: '请输入正确的电话号码',
            regex: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
          },
        ]">
        <input
          type="text"
          :maxlength="11"
          v-model="formValue.phone"
          placeholder="请输入联系电话" />
      </nut-form-item>
      <nut-form-item
        :rules="[
          {
            required: true,
            message: '请输入正确的店铺号码',
            regex: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
          },
        ]"
        label="店铺号码"
        prop="phone"
        required>
        <input
          v-model="formValue.mobile"
          :maxlength="11"
          placeholder="请输入店铺号码"
          type="text" />
      </nut-form-item>
      <nut-form-item
        required
        label="验证码"
        prop="code"
        :rules="[
          {
            required: true,
            message: '请输入验证码',
          },
        ]">
        <view class="yanCode">
          <input
            type="text"
            :maxlength="6"
            v-model="formValue.code"
            placeholder="请输入验证码" />
          <nut-button
            style="width: 100px; padding: 3px"
            plain
            type="primary"
            size="mini"
            :disabled="smsDisabled"
            round
            @click="getSmsCode">
            {{ smsStr }}
          </nut-button>
        </view>
      </nut-form-item>
      <nut-form-item
        required
        label="店铺地址"
        prop="address"
        :rules="[
          {
            required: true,
            message: '请输入店铺详细地址',
          },
        ]">
        <input
          type="text"
          v-model="formValue.address"
          placeholder="请输入店铺详细地址" />
      </nut-form-item>
      <nut-form-item
        required
        label="法人"
        prop="bank_user"
        :rules="[
          {
            required: true,
            message: '请输入法人',
          },
        ]">
        <input
          type="text"
          v-model="formValue.bank_user"
          placeholder="请输入法人" />
      </nut-form-item>
      <nut-form-item
        required
        label="账户名称"
        prop="bank_name"
        :rules="[
          {
            required: true,
            message: '请输入账户名称',
          },
        ]">
        <input
          type="text"
          v-model="formValue.bank_name"
          placeholder="请输入账户名称" />
      </nut-form-item>
      <nut-form-item
        required
        label="开户银行"
        prop="bank"
        :rules="[
          {
            required: true,
            message: '请输入银行名称',
          },
        ]">
        <input
          type="text"
          v-model="formValue.bank"
          placeholder="请输入银行名称" />
      </nut-form-item>
      <nut-form-item
        required
        label="银行卡号"
        prop="bank_card"
        :rules="[
          {
            required: true,
            message: '请输入银行卡号',
          },
        ]">
        <input
          type="text"
          v-model="formValue.bank_card"
          placeholder="请输入银行卡号" />
      </nut-form-item>
      <nut-form-item
        required
        label="经营类目"
        prop="merGooTypeStr"
        :rules="[
          {
            required: true,
            message: '请选择经营类目',
          },
        ]">
        <input
          type="text"
          :disabled="true"
          v-model="formValue.merGooTypeStr"
          placeholder="请选择经营类目"
          @click="merGooType = true" />
        <nut-popup
          position="bottom"
          v-model:visible="merGooType"
          :safe-area-inset-bottom="true"
          :catch-move="true">
          <nut-picker
            v-model:columns="merGooList"
            title="商户类型"
            @confirm="confirmGooType"
            @cancel="merGooType = false"></nut-picker>
        </nut-popup>
      </nut-form-item>
      <nut-form-item
        required
        label="营业执照"
        prop="license"
        :rules="[
          {
            required: true,
            message: '请上传营业执照',
            validator: value => {
              return value.length > 0;
            },
          },
        ]">
        <Upload v-model:list="formValue.license" />
      </nut-form-item>
      <nut-form-item
        required
        label="法人身份证（正面）"
        prop="front"
        :rules="[
          {
            required: true,
            message: '法人身份证（正面）',
            validator: value => {
              return value.length > 0;
            },
          },
        ]">
        <Upload v-model:list="formValue.front" />
      </nut-form-item>
      <nut-form-item
        required
        label="法人身份证（反面）"
        prop="back"
        :rules="[
          {
            required: true,
            message: '法人身份证（反面）',
            validator: value => {
              return value.length > 0;
            },
          },
        ]">
        <Upload v-model:list="formValue.back" />
      </nut-form-item>
      <nut-form-item
        required
        label="门头照"
        prop="head_photo"
        :rules="[
          {
            required: true,
            message: '请上传门头照',
            validator: value => {
              return value.length > 0;
            },
          },
        ]">
        <Upload v-model:list="formValue.head_photo" />
      </nut-form-item>
      <nut-form-item
        required
        label="店内照"
        prop="img"
        :rules="[
          {
            required: true,
            message: '请上传店内照至少3张',
            validator: value => {
              return value.length >= 3;
            },
          },
        ]">
        <Upload v-model:list="formValue.img" :max="5" multiple />
      </nut-form-item>

      <view class="btn">
        <nut-button block type="primary" round @click="submit()"
          >提交
        </nut-button>
      </view>
    </nut-form>
    <!--  入驻协议弹窗  -->
    <nut-dialog
      no-cancel-btn
      title="入驻协议"
      ok-text="已阅读并且同意"
      v-model:visible="visible"
      @ok="onOk">
      <view>入驻协议</view>
    </nut-dialog>
  </view>
</template>

<style lang="scss">
page {
  background-image: url('~@/static/merchantBg.jpg');
  background-size: 100%;
  background-color: #e93423;
  background-repeat: no-repeat;
}

.form {
  position: relative;
  top: 200px;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  .btn {
    padding: 20px;
    margin-top: 20px;
    text-align: center;
  }
}

.yanCode {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
