import React, { useEffect, useState, useRef } from 'react';
import {
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Pagination,
  Drawer,
  Form,
  Modal,
  Switch,
  Select,
  Image,
} from 'antd';
import { useNavigate } from 'react-router-dom';
const { RangePicker } = DatePicker;
import PaginationCom from '@/common/Pagination';
import { getList1, addRole, infoRole, editRole, changeStatus, delRole, editPass } from './request';
import { getAllList } from '../role/request';
import reload from '@/assets/images/icon/reload.png';
import reset from '@/assets/images/icon/reset.png';
import filter from '@/assets/images/icon/filter.png';
import add from '@/assets/images/icon/add.png';
import dayjs from 'dayjs';
import TableCom from '@/common/TableCom/index';
import md5 from 'js-md5';
import { useSelector } from 'react-redux';
const Administrator = () => {
  const [data, setData] = useState([]);
  const navigate = useNavigate();
  const [page_size, setpage_size] = useState(10);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [showModal, setshowModal] = useState(false);
  const [isAdd, setIsAdd] = useState(false);
  const [delMoadal, setDelModal] = useState(false);
  const [passwordModal, setPasswordModal] = useState(false);
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [id, setId] = useState(0);
  const flag = useRef(true);
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);
  // 角色列表
  const [roleList, setRoleList] = useState([]);
  const [initialValues, setinitialValues] = useState({
    real_name: '',
    tel: '',
    role_id: '',
    validity: '',
    password: '',
  });
  const [filterObj, setfilterObj] = useState({
    real_name: '',
    tel: '',
    role_id: null,
    start_time: '',
    end_time: '',
  });
  const [dateVal, setDateVal] = useState([]);
  // 过滤
  const handleFilter = (flag, val) => {
    if (flag == 'startandend') {
      let val2 = val || [];
      filterObj['start_time'] = parseInt(
        new Date(dayjs(val2[0]).format('YYYY-MM-DD') + ' 00:00:00').getTime() / 1000,
      );
      const endDate = new Date(dayjs(val2[1])).getDate();
      const endTime = parseInt(
        new Date(dayjs(val2[1]).format('YYYY-MM-') + endDate + ' 23:59:59').getTime() / 1000,
      );
      filterObj['end_time'] = endTime;
      setDateVal(val);
      if (!val2.length) {
        delete filterObj['start_time'];
        delete filterObj['end_time'];
      }
    } else {
      filterObj[flag] = val;
    }
    for (const key in filterObj) {
      if (!filterObj[key]) {
        delete filterObj[key];
      }
    }
    setfilterObj({ ...filterObj });
    if (!val) init(filterObj);
  };
  // 重置
  const handleReset = () => {
    setfilterObj({ real_name: '', tel: '', role_id: '' });
    setDateVal([]);
    init();
  };
  const init = async (obj = {}) => {
    setLoading(true);
    const { total, list } = await getList1({ page, page_size, ...obj });
    setTotal(total);
    setData(list);
    setLoading(false);
  };
  const handleEdit = async (id) => {
    console.log('handleEdit id', id);

    const data = await infoRole({ id });
    let { validity } = data;
    setIsAdd(false);
    setshowModal(true);
    setId(id);
    form.setFieldsValue({ ...data, validity: dayjs(validity) });
  };
  const onClose = () => {
    setshowModal(false);
  };
  const submitForm = async (obj) => {
    let bool;
    let { password, validity } = obj;
    if (isAdd) {
      bool = await addRole({
        ...obj,
        password: md5(md5(password)),
        validity: dayjs(validity).unix(),
      });
    } else {
      bool = await editRole({ ...obj, id, validity: dayjs(validity).unix() });
    }
    if (!bool) return;
    init();
    setshowModal(false);
  };
  const delSuccess = async (id) => {
    console.log('id', id);

    const bool = await delRole({ id });
    console.log('bool', bool);
    bool && init();
    setDelModal(false);
  };

  const handleStatus = async (status, id) => {
    const bool = await changeStatus({ status: status ? '1' : '0', id });
    bool && init();
  };
  const passwordSuccess = async (obj) => {
    let { password: pass, re_password: repass } = obj;
    const bool = await editPass({ id, password: md5(md5(pass)), re_password: md5(md5(repass)) });
    if (!bool) return;
    init();
    setPasswordModal(false);
  };
  // 获取角色
  const RoleList = async () => {
    const res = await getAllList({ type: 1 });
    setRoleList(res);
  };
  useEffect(() => {
    // if(!flag.current){
    RoleList();
    // }else{
    // flag.current=false
    // }
  }, []);
  useEffect(() => {
    if (!passwordModal) {
      form2.setFieldsValue({
        password: '',
        re_password: '',
      });
    }
  }, [passwordModal]);
  const columns = [
    {
      title: 'ID',
      key: 'id',
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '管理员名称',
      key: 'real_name',
      dataIndex: 'real_name',
      align: 'center',
    },
    {
      title: '手机号',
      key: 'tel',
      dataIndex: 'tel',
      align: 'center',
    },
    {
      title: '角色名称',
      key: 'role_name',
      dataIndex: 'role_name',
      align: 'center',
    },
    {
      title: '状态',
      key: 'sort',
      dataIndex: 'sort',
      render (_, { status, id }) {
        return (
          <Switch
            defaultChecked={status}
            onChange={(ev) => handleStatus(ev, id)}
            disabled={!operationPermissionsList.includes('/jurisdiction/admin/changeStatus')}
          />
        );
      },
      align: 'center',
    },
    {
      title: '有效期',
      key: 'validity',
      align: 'center',
      dataIndex: 'validity',
    },
    {
      title: '创建时间',
      key: 'create_time',
      align: 'center',
      dataIndex: 'create_time',
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      render: (_, record) => {
        return (
          <Space>
            {operationPermissionsList.includes('/jurisdiction/admin/getInfoById') && (
              <Button onClick={() => handleEdit(record.id)}>编辑</Button>
            )}
            {operationPermissionsList.includes('/jurisdiction/admin/editPass') && (
              <Button
                onClick={() => {
                  setId(record.id);
                  setPasswordModal(true);
                }}
              >
                修改密码
              </Button>
            )}
            {operationPermissionsList.includes('/jurisdiction/admin/del') && (
              <Button
                onClick={() => {
                  setId(record.id);
                  setDelModal(true);
                }}
              >
                删除
              </Button>
            )}
          </Space>
        );
      },
    },
  ];
  useEffect(() => {
    if (!showModal) {
      form.setFieldsValue({
        real_name: '',
        tel: '',
        role_id: null,
        validity: '',
        password: '',
      });
      form.resetFields();
    }
  }, [showModal]);
  return (
    <div>
      <Row justify={'space-between'}>
        <Col className='form-devices-inline'>
          <Form layout='inline'>
            <Form.Item label='管理员名称'>
              <Input
                autoComplete='off'
                allowClear
                value={filterObj.real_name}
                onChange={(ev) => handleFilter('real_name', ev.target.value)}
                placeholder='请输入管理员名称'
                id='name'
              ></Input>
            </Form.Item>
            <Form.Item label='手机号'>
              <Input
                autoComplete='off'
                allowClear
                value={filterObj.tel}
                onChange={(ev) => handleFilter('tel', ev.target.value)}
                placeholder='请输入手机号'
                id='phone'
              ></Input>
            </Form.Item>
            <Form.Item label='角色' rules={[{ required: true, message: '请选择角色' }]}>
              <Select placeholder='请选择角色' allowClear style={{ width: '200px' }}>
                {roleList.length &&
                  roleList.map((item) => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
            <Form.Item label='有效期'>
              <RangePicker
                value={dateVal}
                onChange={(ev) => handleFilter('startandend', ev)}
                allowClear
                id='createTime'
              ></RangePicker>
            </Form.Item>
            <Space>
              <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '11px',
                      height: '10px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={reset} />
                  </span>
                }
                onClick={handleReset}
              >
                重置
              </Button>
              <Button
                type='primary'
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={filter} />
                  </span>
                }
                ghost
                onClick={() => {
                  setPage(1);
                  Object.values(filterObj).some((item) => item) ? init(filterObj) : init();
                }}
              >
                筛选
              </Button>
              <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '10px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={reload} />
                  </span>
                }
                onClick={() =>
                  Object.values(filterObj).some((item) => item) ? init(filterObj) : init()
                }
              >
                刷新
              </Button>
              {/* <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={add} />
                  </span>
                }
                onClick={() => {
                  setIsAdd(true);
                  setshowModal(true);
                }}
              >
                添加
              </Button> */}
            </Space>
          </Form>
        </Col>
        <Col>
          <Space>
            {operationPermissionsList.includes('/jurisdiction/role/add') && (
              <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={add} />
                  </span>
                }
                onClick={() => {
                  setIsAdd(true);
                  setshowModal(true);
                }}
              >
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      {TableCom({ columns, loading, data })}
      <Modal
        mask={false}
        centered
        open={delMoadal}
        onOk={() => delSuccess(id)}
        onCancel={() => setDelModal(false)}
        footer={(_, { OkBtn, CancelBtn }) => {
          return (
            <Row justify={'center'} className='delModal' style={{ marginBottom: '30px' }}>
              <Space size={20}>
                <CancelBtn className='cancel' />
                <OkBtn className='true' />
              </Space>
            </Row>
          );
        }}
        okText='确认'
      >
        <p style={{ textAlign: 'center', padding: '30px 0 18px', fontSize: 16 }}>
          管理员将永久删除，是否继续?
        </p>
      </Modal>
      <Drawer
        mask={false}
        centered
        open={passwordModal}
        onCancel={() => setPasswordModal(false)}
        onClose={() => setPasswordModal(false)}
        footer={null}
        okText='提交'
      >
        <Form
          labelCol={{ span: 6 }}
          form={form2}
          wrapperCol={{ span: 12 }}
          onFinish={passwordSuccess}
        >
          <Form.Item
            label='新密码'
            name='password'
            wrapperCol={{ span: 16 }}
            rules={[
              { required: true, message: '请输入新密码' },
              {
                pattern: /^((?=.*\d)(?=.*[A-Z])(?=.*[a-z]))|((?=.*\d)(?=.*[A-Z])(?=.*[\W_]))|((?=.*\d)(?=.*[a-z])(?=.*[\W_]))|((?=.*[A-Z])(?=.*[a-z])(?=.*[\W_]))[a-zA-Z\d\W_]{8,12}$/,
                message: '密码至少满足三种格式(大写字母、小写字母、数字、特殊符号), 长度为8~12位字符！',
                trigger: ['change', 'blur']
              },
              {
                validator (_, value) {
                  if (!value || form2.getFieldValue('re_password') === value) {
                    form2.setFields([{ name: 're_password', errors: [''] }])
                    return Promise.resolve(); 
                  }
                  form2.setFields([{ name: 're_password', errors: ['两次输入的密码不一致'] }])
                  return Promise.reject();
                },
              },
            ]}
            // validateStatus='error' // 设置为 'error' 显示错误样式
          >
            <Input.Password autoComplete='off' placeholder='请输入新密码'></Input.Password>
          </Form.Item>
          <Form.Item
            label='确认新密码'
            name='re_password'
            wrapperCol={{ span: 16 }}
            rules={[
              { required: true, message: '请再次输入新密码' },
              {
                pattern: /^((?=.*\d)(?=.*[A-Z])(?=.*[a-z]))|((?=.*\d)(?=.*[A-Z])(?=.*[\W_]))|((?=.*\d)(?=.*[a-z])(?=.*[\W_]))|((?=.*[A-Z])(?=.*[a-z])(?=.*[\W_]))[a-zA-Z\d\W_]{8,12}$/,
                message: '密码至少满足三种格式(大写字母、小写字母、数字、特殊符号), 长度为8~12位字符！',
                trigger: ['change', 'blur']
              },
              {
                validator (_, value) {
                  if (!value || form2.getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              },
            ]}
          >
            <Input.Password autoComplete='off' placeholder='请再次输入新密码'></Input.Password>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 10, span: 24 }}>
            <Space size={20}>
              <Button className='cancel' onClick={() => setPasswordModal(false)}>
                取消
              </Button>
              <Button className='submit' htmlType='submit'>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
      <br />
      <PaginationCom
        total={total}
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        setPage={setPage}
        init={init}
        filterObj={filterObj}
      />
      <Drawer placement='right' onClose={onClose} open={showModal} mask={false}>
        <Form form={form} onFinish={submitForm} labelCol={{ span: 6 }}>
          <Form.Item
            name='real_name'
            label='管理员名称'
            rules={[
              { required: true, message: '请输入管理员名称' },
              { max: 30, message: '最大30字符' },
            ]}
          >
            <Input autoComplete='off' placeholder='请输入管理员名称'></Input>
          </Form.Item>
          <Form.Item
            name='tel'
            label='手机号'
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
                message: '请输入正确格式的手机号',
                trigger: 'blur',
              },
            ]}
          >
            <Input autoComplete='off' placeholder='请输入手机号'></Input>
          </Form.Item>
          <Form.Item
            name='role_id'
            label='角色'
            rules={[{ required: true, message: '请选择角色' }]}
          >
            {/* <Select placeholder='请选择角色'>
              {roleList
                .reduce((acc, item) => {
                  if (item.type === 1 && !acc.some((el) => el.type === 1)) {
                    acc.push(item);
                  }
                  if (item.type === 2 && !acc.some((el) => el.type === 2)) {
                    acc.push(item);
                  }
                  return acc;
                }, [])
                .map((item) => (
                  <Select.Option key={item.id} value={item.id}>
                    {item.type === 1 ? '管理员' : '老师'}
                  </Select.Option>
                ))}
            </Select> */}

            <Select
              placeholder='请选择角色'
              showSearch
              optionFilterProp='children'
              autoComplete='off'
            >
              {roleList.length &&
                roleList.map((item) => (
                  <Select.Option key={item.id} value={item.id}>
                    {item.name}
                  </Select.Option>
                ))}
            </Select>
          </Form.Item>

          <Form.Item
            name='validity'
            label='有效期'
            rules={[{ required: true, message: '请选择有效期' }]}
          >
            <DatePicker placeholder='请选择有效期'></DatePicker>
          </Form.Item>
          {isAdd && (
            <Form.Item
              name='password'
              label='初始密码'
              rules={[
                { required: true, message: '请输入密码' },
                {
                  pattern: /^((?=.*\d)(?=.*[A-Z])(?=.*[a-z]))|((?=.*\d)(?=.*[A-Z])(?=.*[\W_]))|((?=.*\d)(?=.*[a-z])(?=.*[\W_]))|((?=.*[A-Z])(?=.*[a-z])(?=.*[\W_]))[a-zA-Z\d\W_]{8,12}$/,
                  message: '密码至少满足三种格式(大写字母、小写字母、数字、特殊符号), 长度为8~12位字符！',
                  trigger: ['change', 'blur']
                },
              ]}
            >
              <Input allowClear placeholder='请输入密码' autoComplete='off' />
              {/* <Input.Password
                allowClear
                placeholder='请输入密码'
                autoComplete='new-password'
                autoFill='off'
                data-autocomplete='off'
                style={{ MozAppearance: 'textfield' }}
                name={Math.random().toString(36).substring(2)} // 假设这个值是每次都会重新生成的随机字符串
                inputProps={{
                  autocomplete: 'new-password',
                  style: { WebkitTextSecurity: 'disc'}
              , }} /> */}
            </Form.Item>
          )}
          <Form.Item wrapperCol={{ offset: 5, span: 16 }} style={{ textAlign: 'center' }}>
            <Space size={20}>
              <Button className='cancel' onClick={() => setshowModal(false)}>
                取消
              </Button>
              <Button className='submit' htmlType='submit'>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default Administrator;
