import React, { useState, useEffect, useRef } from 'react';
import {
  Button,
  Popconfirm,
  Modal,
  Form,
  Input,
  message,
  Radio,
  Select,
  List,
  Row,
  Col,
  Card,
  Tree,
  Checkbox,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getCooperativeList } from '@/services/cooperative';
import {
  getUserList,
  addUser,
  deleteUser,
  updateUser,
  getDefaultPassword,
  getUserDetail,
} from '@/services/user';
import { getRoleList } from '@/services/role';
import { getUserRoleList, addUserUserRole, deleteUserRole } from '@/services/userRole';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import PageTable from '@/components/PageTable';
import moment from 'moment';
import Search from '@/components/CooperativeSearch';
import './index.less';

const FormItem = Form.Item;
const { Option } = Select;
const formatterTime = (val) => {
  return val && val !== '-' ? moment(val).format('YYYY-MM-DD') : '-';
};
export default (props) => {
  //编辑弹窗
  const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };
  const [form] = Form.useForm();
  const [editModal, setEditModal] = useState(false);
  const [loading, setLoading] = useState(false);
  const [userId, setuserId] = useState();
  const [password, setPassWord] = useState('');
  const [cooperativeList, setCooperativeList] = useState([]);

  const [editRoleModal, setEditRoleModal] = useState(false);
  const [rLoading, setRLoading] = useState(false);
  const [rUserId, setRUserId] = useState();
  const [roleList, setRoleList] = useState([]);
  const [currentCheckbox, setCurrentCheckbox] = useState();
  //列表数据
  const actionRef = useRef();
  const [data, setData] = useState([]);
  const [orgId, setOrgId] = useState();

  // 动态生成树
  const handelNode = (item) => {
    let node = (
      <div
        key={item.orgId}
        style={{
          justifyContent: 'space-between',
          display: 'flex',
          padding: '8px 0',
        }}
      >
        <span>{item.title}</span>
      </div>
    );
    return node;
  };
  const onSelect = (checkedKeys, info) => {
    if (info.selected) {
      setOrgId(info.node.key);
    } else {
      setOrgId();
    }
  };
  // 编辑弹窗的表单提交
  const Submit = (values) => {
    const newData = { ...values };
    if (!newData.sex && newData.sex !== 0) {
      newData.sex = 1;
    }
    setLoading(true);
    if (!/^1[0-9]{10}$/.test(newData.phone)) {
      message.warning('请输入正确的十一位手机号');
      setLoading(false);
      return false;
    }
    if (
      !/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
        newData.idCard,
      )
    ) {
      message.warning('请输入正确的身份证号');
      setLoading(false);
      return false;
    }

    if (userId) {
      updateUser(userId, newData)
        .then(() => {
          setLoading(false);
          message.success(`修改成功`);
          onCancel();
          actionRef.current.reload();
        })
        .catch((err) => {
          setLoading(false);
          console.log(err.message);
        });
    } else {
      addUser(newData)
        .then(() => {
          setLoading(false);
          message.success(`保存成功`);
          onCancel();
          actionRef.current.reload();
        })
        .catch((err) => {
          setLoading(false);
          message.error(err.message || err);
        });
    }
  };
  //表单点击取消按钮
  const onCancel = () => {
    setuserId();
    form.resetFields();
    setEditModal(false);
  };
  // 弹窗表单中合作社搜索框改变事件目前没用
  const handelChange = () => {};

  // 列表点击编辑按钮
  const handleEdit = (val) => {
    setuserId(val.userId);
    setEditModal(true);
  };
  //列表点击删除按钮
  const handleDelete = (id) => {
    deleteUser(id)
      .then(() => {
        message.success('删除成功');
        actionRef.current.reload();
      })
      .catch((err) => {
        console.log(err.message);
      });
  };
  //列表切换人员状态方法
  const handleOK = (record, data) => {
    const title = record.status
      ? '您确定要将该人员状态变更为禁用吗? 禁用后该人员将不能登录'
      : '您确定要将该人员状态变更为启用吗? 启用后该人员可以登录!';
    Modal.confirm({
      title: title,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        updateUser(record.userId, { ...record, status: record.status === 1 ? 0 : 1 })
          .then((res) => {
            message.success('操作成功');
            actionRef.current.reload();
          })
          .catch((err) => {
            console.log(err.message);
          });
      },
    });
  };
  //点击授权角色方法
  const handleRole = (val) => {
    setRUserId(val.userId);
    getUserRoleList({ user_id: val.userId })
      .then((res) => {
        if (res.length !== 0) {
          setCurrentCheckbox(res.map((item) => item.roleId));
        }
      })
      .catch((err) => {
        console.log(err.message);
      });
    setEditRoleModal(true);
  };
  //授权弹窗点击取消按钮
  const onRoleCancel = () => {
    setRUserId();
    setCurrentCheckbox();
    form.resetFields();
    setEditRoleModal(false);
  };
  const handelOk = () => {
    if (!currentCheckbox) {
      message.info('请选择角色');
      return;
    }
    setRLoading(true);
    if (currentCheckbox.length === 0) {
      deleteUserRole(rUserId)
        .then(() => {
          message.success('取消授权角色成功');
          setRLoading(false);
          onRoleCancel();
        })
        .catch((err) => {
          console.log(err.message);
          setRLoading(false);
        });
    } else {
      addUserUserRole(
        rUserId,
        currentCheckbox.map((item) => {
          return { userId: rUserId, roleId: item };
        }),
      )
        .then(() => {
          message.success('授权角色成功');
          setRLoading(false);
          onRoleCancel();
        })
        .catch((err) => {
          console.log(err.message);
          setRLoading(false);
        });
    }
  };
  const handleCheckboxChange = (list) => {
    setCurrentCheckbox(list);
  };
  useEffect(() => {
    //获取账号默认密码
    getDefaultPassword()
      .then((res) => {
        setPassWord(res);
      })
      .catch((err) => {
        console.log(err.message);
      });
    //获取合作社列表数据
    getCooperativeList({ pageSize: 999 })
      .then((res) => {
        setCooperativeList(res.records);
        const list = res.records?.map((item) => {
          return { title: item.name, key: item.orgId };
        });
        setData(list);
      })
      .catch((err) => {
        console.log(err.message);
      });
    //获取角色列表数据
    getRoleList({ pageSize: 999 })
      .then((res) => {
        setRoleList(res.records);
      })
      .catch((err) => {
        console.log(err.message);
      });
  }, []);
  useEffect(() => {
    if (userId) {
      getUserDetail(userId)
        .then((res) => {
          if (res.orgId === '-1') {
            form.setFieldsValue({ ...res, orgId: cooperativeList[0].orgId });
          } else {
            form.setFieldsValue(res);
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    } else {
      form.resetFields();
    }
  }, [userId]);

  const actions = () => [
    <Button key="add" type="primary" icon={<PlusOutlined />} onClick={() => setEditModal(true)}>
      新增
    </Button>,
  ];
  const columns = [
    {
      title: '姓名',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      key: 'nickName',
      search: false,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      width: 80,
      render: (_, record) => {
        return record.sex === 1 ? '男' : record.sex === 0 ? '女' : '未知';
      },
      search: false,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '注册时间',
      dataIndex: 'createDate',
      key: 'createDate',
      render: formatterTime,
      search: false,
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      search: false,
      render: (_, record) => {
        return record.status === 1 ? '启用' : '未启用';
      },
    },
    {
      title: '管理员',
      dataIndex: 'isOrgManager',
      key: 'isOrgManager',
      width: 80,
      search: false,
      render: (_, record) => {
        return record.isOrgManager && record.isOrgManager == 1 ? '管理员' : '非管理员';
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 160,
      render: (_, record) => [
        <Button style={{ padding: 0 }} type="link" key={1} onClick={() => handleOK(record)}>
          {record.status === 0 ? '启用' : '禁用'}
        </Button>,
        <Button style={{ padding: 0 }} type="link" key={2} onClick={() => handleEdit(record)}>
          编辑
        </Button>,
        <Button style={{ padding: 0 }} type="link" key={3} onClick={() => handleRole(record)}>
          授权角色
        </Button>,
        <Popconfirm
          key={4}
          title="您是否确认删除 ?"
          onConfirm={() => handleDelete(record.userId)}
          okText="确定"
          cancelText="取消"
        >
          <Button style={{ padding: 0 }} type="link">
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageHeaderWrapper>
      <Row gutter={16}>
        <Col span={6}>
          <Card title="合作社列表">
            <Tree
              onSelect={onSelect}
              className="treeClass"
              titleRender={(data) => handelNode(data)}
              treeData={data}
            />
          </Card>
        </Col>
        <Col span={18}>
          <PageTable
            request={getUserList}
            params={{ org_id: orgId }}
            // expfunc={exportPersonList}
            columns={columns}
            actionRef={actionRef}
            rowKey="userId"
            options={false}
            toolBarRender={actions}
            scroll={{ x: 1000 }}
          />
        </Col>
      </Row>
      <Modal
        forceRender
        title={userId ? '人员编辑' : '人员新增'}
        visible={editModal}
        onCancel={onCancel}
        keyboard={false}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <Form {...formItemLayout} onFinish={Submit} form={form}>
          <FormItem label="用户名" name="userName" rules={[{ required: true, message: '请输入' }]}>
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem label="性别" name="sex">
            <Radio.Group>
              <Radio value={1}>男</Radio>
              <Radio value={0}>女</Radio>
            </Radio.Group>
          </FormItem>
          <FormItem label="手机号" name="phone" rules={[{ required: true, message: '请输入' }]}>
            <Input maxLength="11" placeholder="请输入" />
          </FormItem>
          <FormItem label="身份证" name="idCard" rules={[{ required: true, message: '请输入' }]}>
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem
            label="登录账号"
            name="loginName"
            rules={[{ required: true, message: '请输入登录账号' }]}
          >
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem label=" " colon={false} style={{ height: '4px', marginTop: '-28px' }}>
            <span style={{ opacity: '0.7' }}>默认密码{password}</span>
          </FormItem>
          <FormItem label="所属合作社" name="orgId" rules={[{ required: true, message: '请输入' }]}>
            <Search placeholder="请输入合作社" onChange={handelChange} />
          </FormItem>
          {userId && (
            <FormItem
              label="合作社管理员"
              name="isOrgManager"
              rules={[{ required: true, message: '请选择' }]}
            >
              <Select placeholder="请选择是否启用">
                <Option value={false}>否</Option>
                <Option value={true}>是</Option>
              </Select>
            </FormItem>
          )}
          <FormItem label="状态" name="status" rules={[{ required: true, message: '请选择' }]}>
            <Select placeholder="请选择是否启用">
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </FormItem>
          <FormItem label=" " colon={false}>
            <Button type="default" onClick={onCancel}>
              取消
            </Button>
            <Button
              type="primary"
              loading={loading}
              htmlType="Submit"
              style={{ marginLeft: '4em' }}
            >
              确认
            </Button>
          </FormItem>
        </Form>
      </Modal>
      <Modal
        forceRender
        title="授权角色"
        visible={editRoleModal}
        onCancel={onRoleCancel}
        keyboard={false}
        maskClosable={false}
        destroyOnClose={true}
        onOk={handelOk}
        confirmLoading={rLoading}
      >
        <Checkbox.Group
          style={{ width: '100%' }}
          value={currentCheckbox}
          onChange={handleCheckboxChange}
        >
          <List
            dataSource={roleList}
            renderItem={(item) => (
              <List.Item>
                <Checkbox value={item.roleId}>{item.name}</Checkbox>
              </List.Item>
            )}
          />
        </Checkbox.Group>
      </Modal>
    </PageHeaderWrapper>
  );
};
