import React from "react";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import { Cell, Button, Dialog } from "@antmjs/vantui";
import { ROLES } from "@/utils/user";
import Page from "@/layouts/index";
import PowerList from "@/components/PowerList";
import { getSysUser, deleteSysUser } from "@/services/sysuser";
import styles from "./index.module.less";

const sid1 = Math.random().toString(36).substring(2, 8);
// const sid2 = Math.random().toString(36).substring(2, 8);

const params = {pageSize: 20};

export default (props) => {
  const [loading, setLoading] = React.useState(false);
  const listRef = React.useRef();
  const dialogId = React.useMemo(() => `dialog-${Math.random().toString(36).substring(2, 7)}`, []);

  const onAdd = () => {
    Taro.navigateTo({
      url: "/pages/user/add/index",
    });
  };

  const onDelete = (user) => {
    Dialog.confirm({
      width: '70vw',
      title: "确认删除用户?",
      selector: dialogId,
    }).then((action) => {
      if (action === "confirm") {
        setLoading(true);
        deleteSysUser(user.userId)
          .then(() => {
            setLoading(false);

            // 刷新列表
            listRef.current.refresh();
          })
          .catch(() => {
            Dialog.close();
            setLoading(false);
          });
      }
    });
  };



  const onShow = () => {
    listRef.current.refresh();
  }

  // console.log('loading', loading);
  return (
    <Page loading={loading} onShow={onShow}>
      <Dialog id={dialogId} />
      <view className={styles["user-warpper"]}>
        <view className={styles["user-warpper-list"]}>
          <PowerList
            sid={sid1}
            ref={listRef}
            params={params}
            request={getSysUser}
            onLoadingChange={setLoading}
            renderItem={(item) => (
              <Cell
                key={item.userId}
                title={`${item.name} ${item.phone}`}
                label={item.createDate.substring(0, 10)}
              >
                <View>
                  <View>
                    {
                      item.dutyList?.map(x => ROLES[x]).join(' ')
                    }
                  </View>
                  <View>
                    <Button
                      plain
                      type="danger"
                      size="small"
                      onClick={() => onDelete(item)}
                    >
                      删除
                    </Button>
                  </View>
                </View>
              </Cell>
            )}
          />
        </view>

        <Button
          type="primary"
          size="large"
          onClick={() => onAdd()}
          style={{
            margin: "var(--main-space)",
            width: "calc(100% - var(--main-space) * 2)",
          }}
        >
          添加
        </Button>
      </view>
    </Page>
  );
};
