import React, { useState, useEffect, useRef } from 'react';
import { Button, Popconfirm, Modal, Form, Input, message, Radio, Select } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getCooperativeList } from '@/services/cooperative';
import {
  getUserList,
  addUser,
  deleteUser,
  updateUser,
  getDefaultPassword,
  getUserDetail,
} from '@/services/user';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import PageTable from '@/components/PageTable';
import Search from '@/components/CooperativeSearch';

const FormItem = Form.Item;
const { Option } = Select;

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 actionRef = useRef();

  // 编辑弹窗的表单提交
  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 (userId) {
      updateUser(userId, newData).then(() => {
        setLoading(false);
        message.success(`修改成功`);
        onCancel();
        actionRef.current.reload();
      });
    } 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 handelEdit = (val) => {
    setuserId(val.userId);
    setEditModal(true);
  };
  //列表点击删除按钮
  const handleDelete = (id) => {
    deleteUser(id)
      .then(() => {
        message.success('删除成功');
        actionRef.current.reload();
      })
      .catch((err) => {
        message.error(err);
      });
  };
  //列表切换人员状态方法
  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) => {
            message.error(err);
          });
      },
    });
  };
  useEffect(() => {
    //获取账号默认密码
    getDefaultPassword().then((res) => {
      setPassWord(res);
    });
    //获取机构列表数据
    getCooperativeList().then((res) => {
      setCooperativeList(res.records);
    });
    if (userId) {
      getUserDetail(userId).then((res) => {
        if (res.orgId === '-1') {
          form.setFieldsValue({ ...res, orgId: cooperativeList[0].orgId });
        } else {
          form.setFieldsValue(res);
        }
      });
    } 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: '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: 'email',
      key: 'email',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      renderFormItem: () => {
        return (
          <Select placeholder="请选择">
            <Option value={1}>启用</Option>
            <Option value={0}>禁用</Option>
          </Select>
        );
      },
      render: (_, record) => {
        return record.status === 1 ? '启用' : '未启用';
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <Button type="link" key={1} onClick={() => handleOK(record)}>
          {record.status === 0 ? '启用' : '禁用'}
        </Button>,
        <a key={2} onClick={() => handelEdit(record)}>
          编辑
        </a>,
        <Popconfirm
          key={3}
          title="您是否确认删除 ?"
          onConfirm={() => handleDelete(record.userId)}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageHeaderWrapper>
      <PageTable
        request={getUserList}
        // expfunc={exportPersonList}
        columns={columns}
        actionRef={actionRef}
        rowKey="userId"
        options={false}
        toolBarRender={actions}
        scroll={{ x: 1000 }}
      />
      <Modal
        title={userId ? '人员编辑' : '人员新增'}
        visible={editModal}
        onCancel={onCancel}
        keyboard={false}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <Form {...formItemLayout} onFinish={Submit} form={form}>
          <FormItem label="登录账号">
            <Input.Group compact>
              <Form.Item
                name="loginName"
                noStyle
                rules={[{ required: true, message: '请输入登录账号' }]}
              >
                <Input placeholder="请输入" />
              </Form.Item>
              <span style={{ opacity: '0.7' }}>默认密码{password}</span>
            </Input.Group>
          </FormItem>
          <FormItem label="用户名" name="userName" rules={[{ required: true, message: '请输入' }]}>
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem label="性别" name="sex">
            <Radio.Group name="sex" defaultValue={1}>
              <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="email" rules={[{ required: true, message: '请输入' }]}>
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem label="所属机构" name="orgId" rules={[{ required: true, message: '请输入' }]}>
            <Search placeholder="请选择机构" onChange={handelChange} />
            {/* <Select
              placeholder="请选择机构"
              showSearch
              onSearch={handelFormSearch}
              onChange={handelFormSearch}
            >
              {cooperativeList.map((item) => (
                <Option value={item.orgId} key={item.orgId}>
                  {item.name}
                </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>
    </PageHeaderWrapper>
  );
};
