import { useState } from "react";
import { Image, Label, View } from "@tarojs/components";
import Taro, { FC } from "@tarojs/taro";
import { AtButton, AtForm, AtInput, AtTextarea } from "taro-ui";
import BgImg from "../../images/feedback@2x-min.png";
import { handleValidate } from "../../../utils";
import { getBaseURL } from "@dage/service";
import { Rules } from "async-validator";
import { feedbackApi } from "../../../api";
import { FooterProtocol } from "../../../components/FooterProtocol";
import "./index.scss";

const DEFAULT_PARAMS = {
  name: "",
  phone: "",
  content: "",
  randCode: "",
};

const formRules: Rules = {
  name: [{ required: true, message: "请输入称呼" }],
  phone: [{ required: true, message: "请输入联系方式" }],
  content: [{ required: true, message: "请输入反馈内容" }],
  randCode: [
    { required: true, message: "请输入验证码" },
    {
      validator: (_, value) => {
        return value.length === 5;
      },
      message: "验证码输入有误",
    },
  ],
};

const FeedBackPage: FC = () => {
  const [checked, setChecked] = useState(false);
  const [params, setParams] = useState({ ...DEFAULT_PARAMS });
  const [timestamp, setTimestamp] = useState(new Date().getTime());
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (event, readProtocol = false) => {
    if (!(await handleValidate(params, formRules))) return;

    if (!checked && !readProtocol) {
      Taro.showModal({
        title: "提示",
        content: "是否已阅读并同意《用户服务协议》及《个人信息保护政策》",
        confirmText: "同意",
        success: (res) => {
          if (res.confirm) {
            setChecked(true);
            handleSubmit(undefined, true);
          }
        },
      });
      return;
    }

    try {
      setLoading(true);
      await feedbackApi(params);

      setParams({ ...DEFAULT_PARAMS });
      setTimestamp(new Date().getTime());
      Taro.showToast({
        title: "提交成功",
        icon: "success",
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <View className="feedback-page">
      <View className="feedback">
        <AtForm className="feedback-main" onSubmit={handleSubmit}>
          <View className="feedback-main__form">
            <Label className="feedback__label">您的称呼</Label>
            <AtInput
              name="name"
              className="feedback__input"
              maxLength={20}
              placeholder="请输入内容，20字以内"
              value={params.name}
              onChange={(val) =>
                setParams({
                  ...params,
                  name: val as string,
                })
              }
            />

            <Label className="feedback__label">联系方式</Label>
            <AtInput
              name="phone"
              type="phone"
              className="feedback__input"
              maxLength={20}
              placeholder="请输入内容，20字以内"
              value={params.phone}
              onChange={(val) =>
                setParams({
                  ...params,
                  phone: val as string,
                })
              }
            />

            <Label className="feedback__label">反馈内容</Label>
            <AtTextarea
              value={params.content}
              className="feedback__input textarea"
              maxLength={200}
              placeholder="请输入内容，200字以内"
              onChange={(val) =>
                setParams({
                  ...params,
                  content: val,
                })
              }
            />
          </View>

          <View className="feedback-main__form">
            <Label className="feedback__label">验证码</Label>
            <View className="code">
              <AtInput
                name="randCode"
                value={params.randCode}
                className="feedback__input"
                maxLength={5}
                placeholder="请输入内容"
                onChange={(val) =>
                  setParams({
                    ...params,
                    randCode: val as string,
                  })
                }
              />

              <Image
                className="code__img"
                src={`${getBaseURL()}/api/show/getRandCode?t=${timestamp}`}
                onClick={() => setTimestamp(new Date().getTime())}
              />
            </View>

            <View className="toolbar">
              <AtButton
                className="toolbar__btn cancel"
                onClick={() => {
                  Taro.navigateBack();
                }}
              >
                取消
              </AtButton>
              <AtButton
                className="toolbar__btn submit"
                formType="submit"
                loading={loading}
              >
                提交
              </AtButton>
            </View>
          </View>

          <FooterProtocol checked={checked} setChecked={setChecked} />
        </AtForm>

        <Image src={BgImg} className="feedback__bg" mode="widthFix" />
      </View>
    </View>
  );
};

export default FeedBackPage;
