import React from "react";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import Page from "@/layouts/index";
import {
  Button,
  Field,
  Cell,
  CellGroup,
  CheckboxGroup,
  Checkbox,
} from "@antmjs/vantui";
import { ROLE_ORG_MANAGER, ROLE_ORG_USER } from "@/utils/user";

import { warn } from "@/utils/message";
import { postSysUser } from "@/services/sysuser";

export default (props) => {
  const [loading, setLoading] = React.useState(false);
  const [identity, setIdentity] = React.useState([]);
  const [formData, setFormData] = React.useState({});

  const setField = (name, value) => {
    setFormData((data) => ({
      ...data,
      [name]: value,
    }));
  };
  const onSubmit = () => {
    try {
      warn(!formData.name, "请填写姓名");
      warn(!formData.phone, "请填写手机号");
      warn(identity.length < 1, "请选择身份");
    } catch (e) {
      return;
    }

    setLoading(true);
    postSysUser({ ...formData, dutyList: identity })
      .then(() => {
        setLoading(false);
        Taro.navigateBack({
          delta: 1,
          fail: () => {
            Taro.reLaunch({
              url: "/pages/user/list/index",
            });
          },
        });
      })
      .catch(() => {
        setLoading(false);
      });
  };

  return (
    <Page>
      <CellGroup>
        <Field
          required
          label="姓名"
          placeholder="请输入姓名"
          value={formData.name}
          onChange={(e) => setField("name", e.detail)}
        />
        <Field
          required
          label="手机号"
          placeholder="请输入手机号"
          value={formData.phone}
          onChange={(e) => setField("phone", e.detail)}
        />
        <Cell
          title="身份"
          required
          titleWidth="100px"
          titleStyle={{
            maxWidth: "6.2em",
            minWidth: "6.2em",
            marginRight: "12px",
          }}
        >
          <View style={{ display: "flex" }}>
            <CheckboxGroup
              direction="horizontal"
              value={identity}
              onChange={(e) => {
                console.info(e);
                setIdentity([...e.detail]);
              }}
            >
              <Checkbox name={ROLE_ORG_USER}>交办单位人员</Checkbox>
              <Checkbox name={ROLE_ORG_MANAGER}>交办单位管理员</Checkbox>
            </CheckboxGroup>
          </View>
        </Cell>

        {/* // 交办单位人员
export const ROLE_ORG_USER = 'org_user';

// 交办单位管理员
export const ROLE_ORG_MANAGER = 'org_manager'; */}
      </CellGroup>

      <View style={{ padding: "var(--main-space)", background: "#fff" }}>
        <Button block type="primary" loading={loading} onClick={onSubmit}>
          提交
        </Button>
      </View>
    </Page>
  );
};
