import React, { useEffect, useState, useRef } from 'react';
import {
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Drawer,
  Popover,
  Form,
  Switch,
  InputNumber,
  Modal,
  Image,
} from 'antd';
const { TextArea } = Input;
const { RangePicker } = DatePicker;
import PaginationCom from '@/common/Pagination';
import { getAppList, addApp, editApp, delApp, changeStatus, getAppInfo } from './request';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import Add from '@/assets/images/icon/add.png';
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 dayjs from 'dayjs';
import { useSelector } from 'react-redux';
// import './index.less'
const Applied = () => {
  const [data, setData] = useState([]);
  const [page_size, setpage_size] = useState(10);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  // 显示弹框
  const [isEdit, setIsEdit] = useState(false);
  const [isadd, setisadd] = useState(true);
  const [form] = Form.useForm();
  const inpFirstRef = useRef();
  const inpSecondRef = useRef();
  const [delModal, setDelModal] = useState(false);
  const [initialValues, setinitialValues] = useState({
    url_validity: 60,
    login_validity: 3600,
    is_sign: 1,
    is_nonce: 1,
    remarks: '',
    app_name: '',
    validity: '',
  });
  const [dateVal, setDateVal] = useState('');
  const [id, setid] = useState(0);
  const [delid, setdelid] = useState(0);
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);
  const [filterObj, setfilterObj] = useState({
    app_name: '',
    start_time: '',
    end_time: '',
  });
  // 过滤
  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];
      }
    }

    console.log('start_time', filterObj['start_time']);
    console.log('end_time', filterObj['end_time']);
    setfilterObj({ ...filterObj });
    if (!val) init(filterObj);
  };
  const handleEdit = async (id) => {
    setisadd(false);
    setIsEdit(true);
    const data = await getAppInfo({ id });
    setid(id);
    form.setFieldsValue({
      ...data,
      create_time: dayjs(data.create_time),
      validity: dayjs(data.validity),
    });
  };
  const onClose = () => {
    setIsEdit(false);
  };
  const submitForm = async (obj) => {
    let { validity, is_sign, is_nonce } = obj;
    let bool;
    if (isadd) {
      bool = await addApp({
        ...obj,
        validity: dayjs(validity).unix(),
        is_sign: is_sign ? 1 : 0,
        is_nonce: is_nonce ? 1 : 0,
      });
    } else {
      bool = await editApp({
        ...obj,
        validity: dayjs(validity).unix(),
        is_sign: is_sign ? 1 : 0,
        is_nonce: is_nonce ? 1 : 0,
        id,
      });
    }
    if (!bool) return;
    init();
    setIsEdit(false);
  };
  // 删除
  const handleDel = async (id) => {
    const bool = await delApp({ id: delid });
    bool && init();
    setDelModal(false);
  };
  const switchChange = async (obj) => {
    let { id } = obj;
    let status = obj.status === 1 ? 0 : 1;
    const bool = await changeStatus({ id, status });
    bool && init();
  };
  // 获取数据
  const init = async (obj = {}) => {
    setLoading(true);
    const { total, list } = await getAppList({ page, page_size, ...obj });
    setTotal(total);
    setData(list);
    setLoading(false);
  };
  useEffect(() => {
    if (!isEdit) {
      form.setFieldsValue(initialValues);
      form.resetFields();
    }
  }, [isEdit]);
  const columns = [
    {
      title: 'ID',
      key: 'id',
      align: 'center',
      dataIndex: 'id',
    },
    {
      title: '应用名称',
      key: 'app_name',
      dataIndex: 'app_name',
      align: 'center',
      width: 350,
      render: (text) => (
        <Popover content={text} overlayStyle={{ maxWidth: '400px' }}>
          <div
            style={{
              display: '-webkit-box',
              WebkitLineClamp: '2',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              textAlign: 'center',
            }}
          >
            {text}
          </div>
        </Popover>
      ),
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      align: 'center',
      render: (_, record) => {
        return (
          <>
            <Switch
              defaultChecked={record.status}
              onChange={() => switchChange(record)}
              disabled={!operationPermissionsList.includes('/setting/applied/changeStatus')}
            ></Switch>
          </>
        );
      },
    },
    {
      title: '有效期',
      key: 'validity',
      dataIndex: 'validity',
      align: 'center',
    },
    {
      title: '创建时间',
      key: 'create_time',
      dataIndex: 'create_time',
      align: 'center',
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      align: 'center',
      render: (_, record) => {
        return (
          <Space>
            {operationPermissionsList.includes('/setting/applied/getInfoById') && (
              <Button onClick={() => handleEdit(record.id)}>编辑</Button>
            )}
            {operationPermissionsList.includes('/setting/applied/del') && (
              <Button
                onClick={() => {
                  setdelid(record.id);
                  setDelModal(true);
                }}
              >
                删除
              </Button>
            )}
          </Space>
        );
      },
    },
  ];
  const handleReset = () => {
    setfilterObj({ app_name: '' });
    setDateVal('');
    init();
  };
  return (
    <div>
      <Row justify={'space-between'}>
        <Col className='form-devices-inline'>
          <Form layout='inline'>
            <Form.Item label='应用名称'>
              <Input
                autoComplete='off'
                value={filterObj.app_name}
                allowClear
                placeholder='请输入应用名称'
                id='name'
                onChange={(ev) => handleFilter('app_name', ev.target.value)}
              ></Input>
            </Form.Item>
            <Form.Item label='有效期'>
              <RangePicker
                value={dateVal}
                id='createTime'
                onChange={(ev) => handleFilter('startandend', ev)}
              ></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'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={filter} />
                  </span>
                }
                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>
            </Space>
          </Form>
        </Col>
        <Col>
          <Space>
            {operationPermissionsList.includes('/setting/applied/add') && (
              <Button
                type='primary'
                ghost
                onClick={() => {
                  setisadd(true);
                  setIsEdit(true);
                }}
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={Add} />
                  </span>
                }
              >
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      <Modal
        mask={false}
        centered
        open={delModal}
        onOk={handleDel}
        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>
      <Table
        scroll={{
          y: 600,
          x: true,
        }}
        bordered={false}
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
        pagination={false}
      ></Table>
      <br />
      <PaginationCom
        total={total}
        init={init}
        page={page}
        page_size={page_size}
        setPage={setPage}
        setpage_size={setpage_size}
        filterObj={filterObj}
      />
      <Drawer placement='right' onClose={onClose} open={isEdit} mask={false}>
        <Form
          form={form}
          initialValues={initialValues}
          onFinish={submitForm}
          labelCol={{ span: 9 }}
          wrapperCol={{ span: 12 }}
        >
          <Form.Item
            label='应用名称'
            name='app_name'
            rules={[
              { required: true, message: '请输入应用名称' },
              { max: 50, message: '长度最大50字符' },
            ]}
          >
            <Input autoComplete='off' placeholder='请输入应用名称'></Input>
          </Form.Item>
          <Form.Item
            label='有效期'
            name='validity'
            rules={[{ required: true, message: '请选择有效期' }]}
          >
            <DatePicker placeholder='请输入有效期'></DatePicker>
          </Form.Item>
          {!isadd && (
            <>
              <Form.Item label='开发者ID(AppID)' name='app_id'>
                <Input disabled></Input>
              </Form.Item>
              <Form.Item label='开发者密钥(AppSecret)' name='app_secret'>
                <Input disabled></Input>
              </Form.Item>
            </>
          )}
          <Form.Item label='是否签名' name='is_sign'>
            <Switch defaultChecked={initialValues.is_sign}></Switch>
          </Form.Item>
          {!isadd && (
            <Form.Item label='签名密钥' name='sign_secret'>
              <Input placeholder='请输入签名密钥' disabled></Input>
            </Form.Item>
          )}
          <Form.Item
            label='URL有效期(秒)'
            name='url_validity'
            // rules={[{ max: 9, message: '最大9位数' }]}
          >
            <InputNumber
              autoComplete='off'
              style={{ width: 160 }}
              ref={inpFirstRef}
              addonBefore={
                <MinusOutlined
                  onClick={() => {
                    inpFirstRef.current.value--;
                  }}
                  style={{ cursor: 'pointer' }}
                />
              }
              addonAfter={
                <PlusOutlined
                  onClick={() => {
                    inpFirstRef.current.value++;
                  }}
                  style={{ cursor: 'pointer', width: '100%' }}
                />
              }
            ></InputNumber>
          </Form.Item>
          <Form.Item label='是否防重放' name='is_nonce'>
            <Switch defaultChecked={initialValues.is_nonce}></Switch>
          </Form.Item>
          <Form.Item label='登录有效期(秒)' rules={[{ max: 9, message: '最大9位数' }]}>
            <InputNumber
              autoComplete='off'
              style={{ width: 160 }}
              defaultValue={3600}
              ref={inpSecondRef}
              addonBefore={
                <MinusOutlined
                  onClick={() => {
                    inpSecondRef.current.value--;
                  }}
                  style={{ cursor: 'pointer' }}
                />
              }
              addonAfter={
                <PlusOutlined
                  onClick={() => {
                    inpSecondRef.current.value++;
                  }}
                  style={{ cursor: 'pointer', width: '100%' }}
                />
              }
            ></InputNumber>
          </Form.Item>
          <Form.Item label='备注' name='remarks' rules={[{ max: 255, message: '最大255字符' }]}>
            <TextArea placeholder='请输入备注' autoSize={{ minRows: 3, maxRows: 5 }} />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 11, span: 16 }}>
            <Space size={20}>
              <Button className='cancel' onClick={() => setIsEdit(false)}>
                取消
              </Button>
              <Button className='submit' htmlType='submit'>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default Applied;
