import { sendEmail, sendSms } from "@/service/Api.service";
import { filterPhone } from "cqk-sy-ui";
import { iFormItem } from "cqk-sy-ui/sy/components/BusinessForm";
import { ElMessage } from "element-plus";

// 6~20位包含数字、大小写字母
export const validPassword = (pwd: string) => {
  const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
  return reg.test(pwd);
};

export const generateFormList = (
  data: { phone: string; email: string },
  submit: any
) => {
  return [
    {
      type: "text",
      label: data.phone ? "手机号" : "邮箱",
      defaultValue: data.phone ? filterPhone(data.phone) : data.email,
      showLabel: true,
    },
    {
      type: "passwordInput",
      showLabel: true,
      label: "输入密码",
      placeholder: "请输⼊6-20位数字、字⺟组合的密码",
      rule: [
        {
          validator(rule: any, value: any, callback: any) {
            const result = validPassword(value);
            if (!result)
              callback(new Error("请输⼊6-20位数字、字⺟组合的密码"));
            else callback();
          },
          trigger: "blur",
        },
      ],
    },
    {
      type: "codeInput",
      showLabel: true,
      placeholder: "请输入6位验证码",
      label: "验证码",
      maxLen: 6,
      rule: [
        {
          required: true,
          message: "请输入验证码",
          trigger: "blur",
        },
      ],
      async handleClickSendCode(roleForm: any, formEl) {
        let res = null;
        if (data.phone) {
          res = await sendSms({
            phone: data.phone,
            template_id: 1,
          });
        } else {
          // 邮箱
          res = await sendEmail({
            email: data.email,
            template_id: 1,
          });
        }
        if (res) {
          ElMessage({
            message: "发送成功",
            type: "success",
          });
          return true;
        } else return false;
      },
    },
    {
      type: "submitButton",
      text: "提交修改",
      btnProps: {
        type: "primary",
      },
      styles: "margin-top: 10px;margin-left: 50px;",
      async onSubmit(valid, data, setError) {
        data = {
          phone: data.手机号,
          email: data.邮箱,
          pwd: data.输入密码,
          code: data.验证码,
        };
        if (valid) {
          submit(data, setError);
        }
      },
    },
  ] as iFormItem[];
};
