import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Select,Popconfirm } from 'antd';
import React, { useState, useRef,useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm'
import PwdForm from './components/PwdForm'
import RoleForm from './components/RoleAuth'
import OrgForm from './components/OrgForm';
import api from './service';
import Enumerable from 'linq';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  try {
    await api.Add(fields).then((r) => {
      if (r.data) {
        message.success('添加成功');
      } else {
        message.error('添加失败,'+r.errors);
      }
    });
    return true;
  } catch (error) {
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 正在分配数据权限
 * @param fields
 */
const handleGrantData = async (fields) => {
  const hide = message.loading('正在分配数据权限');
  try {
    await api.SetDataRole({ ...fields });
    hide();
    message.success('分配数据权限成功');
    return true;
  } catch (error) {
    hide();
    message.error('分配数据权限失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  try {
    await api.Update(fields).then((r) => {
      if (r.data) {
        message.success('修改成功');
      } else {
        message.error('修改失败请重试！');
      }
    });
    return true;
  } catch (error) {
    message.error('修改失败请重试!');
    return false;
  }
};

const Prefix = "User";
const userManager = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState();
  const [stepFormValues, setStepFormValues] = useState({});
  const [updateOrgModalVisible, handleUpdateOrgModalVisible] = useState();
  /*绑定数据 */
  const actionRef = useRef();
  /*选中*/
  const [selectedRowsState, setSelectedRows] = useState();
  const [pwdVisible, setpwdVisible] = useState(false);
  const [roleVisible, setroleVisible] = useState(false);
  const [selectDatas, SetselectData] = useState();
  const [sysUserId, SetSysUserId] = useState();
  const [account, setaccount] = useState();
  const [treeData, setTreeData] = useState();
  const InitRole = (id) => {
    SetSysUserId(id);
    api.GetRoleDic().then(r => {
      var arr = [];
      for (var key in r.data) {
        arr.push(<Option value={key}>{r.data[key]}</Option>)
      }
      SetselectData(arr);
      api.GetUserRole(id).then(r => {
        setStepFormValues(r.data);
        setroleVisible(true);
      });

    })
  }
  const handleRemove = async (selectedRows) => {
    console.log(selectedRows)
    if (!selectedRows){
      message.error('请选择数据');
    } else{
      await api.RemoveUser(selectedRows.map((row) => row.id)).then((r) => {
        if (r.data) {
          message.success('删除成功，即将刷新');
          actionRef.current.reloadAndRest();
        } else {
          message.error('删除失败，请重试');
        }
      });
    } 
  };
  const cancel = (e) => {
  };
  const handleResetPwd=(record)=>{
    api.ResetPwd(record.id).then(r => {
      r.data ? message.success("重置成功") : message.error("重置失败");
    })
  }
  const Btn = (record) => {
    var arr = [];
    arr.push(<a
      disabled={record.adminType == 2}
      style={{ pointerEvents: record.adminType == 2 ? 'none' : 'auto' }}
      onClick={() => {
        handleModalVisible(true);
        setStepFormValues(record);
      }}
    >
      修改
    </a>);
    arr.push( <Popconfirm
      title="确认删除吗？"
      onConfirm={() => {handleRemove([record])}}
      onCancel={cancel}
      okText="确定"
      cancelText="取消"
    ><a
      disabled={record.adminType == 2}
      style={{ pointerEvents: record.adminType == 2 ? 'none' : 'auto' }}
     
    >
      删除
    </a></Popconfirm>);
    arr.push(<Popconfirm
      title="确认重置密码吗？"
      onConfirm={() => {handleResetPwd(record)}}
      onCancel={cancel}
      okText="确定"
      cancelText="取消"
    ><a>重置密码</a></Popconfirm>);
    arr.push(<a
      onClick={() => {
        setpwdVisible(true);
        
        setStepFormValues(record);
      }}
    >
      修改密码
    </a>);
    arr.push(<a
      disabled={record.adminType == 2}
      style={{ pointerEvents: record.adminType == 2 ? 'none' : 'auto' }}
      onClick={() => {
        InitRole(record.id);
      }}
    >
      角色授权
    </a>);
    // arr.push(<a
    //   disabled={record.adminType == 2}
    //   style={{ pointerEvents: record.adminType == 2 ? 'none' : 'auto' }}
    //   onClick={() => {
    //     handleUpdateOrgModalVisible(true);
    //     setStepFormValues(record);
    //   }}
    // >
    //   数据授权
    // </a>);

    return arr;
  }

  /** 国际化配置 */
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: 'key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '用户姓名',
      dataIndex: 'name',
    },
    {
      title: '登录账户',
      dataIndex: 'account'
    },
    {
      title: '所属加盟商',
      dataIndex: 'companyName'
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      hideInSearch: true,
      sorter: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 350,
      render: (_, record) => Btn(record)
    },
  ];

  useEffect(() => {
   
    initfranchiseeType();
  }, []);
  function initfranchiseeType() {
    api.gettree2().then((r) => {
      debugger
      setTreeData(r.data);
    });api
  }

  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => {
          return <Button
            type="primary"
            key="create"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>
        }}
        request={async (params) => {
          let UserData = [];
          var total = 0;
          await api.Page(params).then((r) => {
            UserData = r.data.data;
            total = r.data.total;
          });
          return {
            data: UserData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />
      {/* {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          {(Enumerable.from(localStorage.getItem("permissions").split(',')).contains(Prefix + "Delete") || localStorage.getItem("adminType") == 1) ? (<Button
                        type="primary"
                        onClick={async () => {
                            await handleRemove(selectedRowsState);
                            setSelectedRows([]);
                            actionRef.current?.reloadAndRest?.();
                        }}
                    >
                        批量删除
                    </Button>) : ''}
        </FooterToolbar>
      )} */}
      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            value.phone= value.account;
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setStepFormValues({});

            if (actionRef.current) {
              actionRef.current.reloadAndRest();
            }
          }
          actionRef.current.reloadAndRest();
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        treeDatas={treeData}
        modalVisible={createModalVisible}
        values={stepFormValues || {}}
      />

      <PwdForm
        onFinish={(value) => {
          api.UpdatePwd(value).then(r => {
            r.data ? message.success("修改成功") : message.error("修改失败");
            setpwdVisible(false);
          })
        }}
        onCancel={() => {
          setpwdVisible(false);
        }}
        values={stepFormValues || {}}
        pwdVisible={pwdVisible}
      />
      <RoleForm
        onFinish={(value) => {
          if (value.id) {
            api.UpdateUserRole(value).then(r => {
              r.data ? message.success("修改成功") : message.error("修改失败");
              setroleVisible(false);
            })
          } else {
            value.sysUserId = sysUserId;
            api.AddUserRole(value).then(r => {
              r.data ? message.success("添加成功") : message.error("添加失败");
              setroleVisible(false);
            })
          }

        }}
        selectData={selectDatas}
        values={stepFormValues}
        onCancel={() => {
          setStepFormValues({});
          setroleVisible(false);
        }}
        roleVisible={roleVisible}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <OrgForm
          onFinish={async (value) => {
            const values = {
              sysUserId: stepFormValues.id,
              sysOrgId: value.orgId,
            };
            const success = await handleGrantData(values);
            if (success) {
              handleUpdateOrgModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reloadAndRest();
              }
            }
          }}
          onCancel={() => {
            handleUpdateOrgModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateOrgModalVisible}
          values={stepFormValues}
        />
      ) : null}
    </PageContainer>
  );
};

export default userManager;
