import React, { useEffect, useState } from 'react';
import { Table, Button, Tooltip, Modal, Divider } from 'antd';

import { Action, TemplateId } from '../../../../util/constant';
import { dispatch } from '../../../../model';
import { showMessage } from '../../../../util';
import IframeDrawer from './IframeDrawer';

const TemplateCURD = (props) => {

  const [ templates, setTemplates ] = useState([]);
  const [ loading, setLoading ] = useState(false);
  const [iframeDrawerParams, setIframeDrawerParams] = useState({
    visible: false,
    title: undefined,
    url: undefined
  })

  const [modal, contextHolder] = Modal.useModal();

  useEffect(() => {

    getTemplates();

    window?.addEventListener("storage", (e) => {
      if (e.key === 'templateChange') {
        getTemplates();
      }
    });

  }, [])

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      editable: false,
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width: 60,
    },
    {
      title: '模版名称',
      dataIndex: 'name',
      width: 180,
      ellipsis: true,
      render: (text, record, _) => {
        return (
          <Tooltip title={text||''}>
            <a onClick={()=>{detailItem(record);}}>
            {text||''}
            </a>
          </Tooltip>
        );
      }
    },
    {
      title: '中文名称',
      dataIndex: 'cnName',
      width: 180,
      ellipsis: true,
    },
    {
      title: '模版描述',
      dataIndex: 'remark',
      ellipsis: true,
    },
    {
      title: '更新时间',
      dataIndex: 'modifiedTs',
      width: 160,
      ellipsis: true,
      render: (_, record) => record.modifiedTs ? new Date(record.modifiedTs).toLocaleString() : ''
    },
    {
      title: '操作',
      key: 'action',
      width: 120,

      render: (text,record) => {
        return (  
          <div style={{ display: 'flex', alignItems: 'center'  }}>
            <Button 
              type='link'
              size='small'
              onClick={() => { editItem(record); }}
              style={{ padding: 0 }}
            >
            编辑
            </Button>
            <div style={{ margin: '0 5px' }}>
              <Divider type='vertical' />
            </div>
            <Button
              type='link'
              size='small'
              onClick={() => { deleteItem(record); }}
              style={{ padding: 0 }}
            >
            删除
            </Button>
          </div>
        )
      }
    }
  ];

  const getTemplates = () => {
    setLoading(true);
    dispatch({
      type: 'datamodel.getAllTemplates',
      callback: data => {
        setTemplates(data||[]);
        setLoading(false);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const editItem = (record) => {
    setIframeDrawerParams({
      visible: true,
      title: '模版编辑',
      url: `/data-govern/model-template-action?${Action}=edit&${TemplateId}=${record.id}`
    })
  }

  const detailItem = (record) => {
    setIframeDrawerParams({
      visible: true,
      title: '模版详情',
      url: `/data-govern/model-template-action?${Action}=detail&${TemplateId}=${record.id}`
    })
  }

  const deleteItem = (record) => {
    modal.confirm({
      title: '提示!',
      content: '您确定要删除该模版吗?',
      onOk: () => {
        dispatch({
          type: 'datamodel.deleteTemplate',
          payload: {
            params: {
              id: record.id
            }
          },
          callback: () => {
            showMessage('success', '模版删除成功');
            getTemplates();
          }
        })
      }
    });
  }

  const onAddClick = () => {
    setIframeDrawerParams({
      visible: true,
      title: '新增模版',
      url: `/data-govern/model-template-action?${Action}=add`
    })
  }

  return (
    <div>
      <div className='d-flex mb-3' style={{ alignItems: 'center' }}>
        <Button 
          onClick={onAddClick} 
        >
        新建
        </Button>
      </div>
      <Table
        loading={loading}
        columns={columns} 
        rowKey={'id'}
        dataSource={templates||[]}
        pagination={false} 
        sticky
      />
      <IframeDrawer
        {...iframeDrawerParams}
        onCancel={() => {
          setIframeDrawerParams({
            visible: false,
            title: undefined,
            url: undefined,
          })
        }}
      />
    { contextHolder }
    </div>
  );
}

export default TemplateCURD;