import React from "react"
import { useDebounceEffect } from 'ahooks'
import LocalStorage from 'local-storage'
import { Space, Select, Button, Tooltip, Input, Typography, Modal, Pagination, Divider } from 'antd'

import { appId } from "../../../App"
import Table from '../../../util/Component/Table'
import { highlightSearchContentByTerms, isSzseEnv, showMessage } from "../../../util"
import { AssetItem } from "../AssetManage/Component/AssetTable"
import UpdateAsset from "../AssetManage/Component/AssetDetailDrawer"
import { dispatch } from '../../../model'
import { AssetManageReference, AssetRecycleReference } from "../../../util/constant"
import { getTemplateType } from "../../../util/axios"
import FilterElementModal from '../AssetManage/Component/FilterElementModal'
import PermissionButton from '../../../util/Component/PermissionButton'

const operationMap = {
  view: '查看',
}

const FC = (props) => {
  const [loadingTemplates, setLoadingTemplates] = React.useState(false)
  const [templates, setTemplates] = React.useState()
  const [currentTemplateValue, setTemplateValue] = React.useState()
  const [pagination, setPagination] = React.useState({ pageNum: 1, pageSize: 20 })
  const [keyword, setKeyword] = React.useState()
  const [selectedRows, setSelectedRows] = React.useState()
  const [loadingFilterElements, setLoadingFilterElements] = React.useState(false)
  const [filterElements, setFilterElements] = React.useState()
  const [loading, setLoading] = React.useState(false)
  const [data, setData] = React.useState()
  const [updateAssetParams, setUpdateAssetParams] = React.useState({
    visible: false,
    id: undefined,
    dirId: undefined,
  })
  const [filterElementParams, setFilterElementParams] = React.useState({
    visible: false,
  })
  const [rightRow, setRightRow] = React.useState()

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

  React.useEffect(() => {
    getTemplates()
  }, [])

  React.useEffect(() => {
    if (currentTemplateValue) {
      getFilterElements()
    }
  }, [currentTemplateValue])

  useDebounceEffect(() => {
    if (currentTemplateValue) {
      getRecycles()
    }
  }, [currentTemplateValue, keyword, pagination], { wait: 300 })

  const indexCol = {
    title: '序号',
    dataIndex: 'key',
    fixed: 'left',
    render: (text, record, index) => ((pagination.pageNum-1)*pagination.pageSize+index+1),
    width: 60,
    ellipsis: true,
    filter: false,
  }

  const [columns, tableData, total] = React.useMemo(() => {
    let [newColumns, newTableData] = [[], []]
    
    for (const element of filterElements??[]) {
        const name = element.name
        const column = {
          title: name,
          dataIndex: name,
          ellipsis: true,
          width: 120,
          render: (text, record) => {
            return (
              <Tooltip title={text}>
                <Typography.Text ellipsis={true}>
                {highlightSearchContentByTerms(text, [keyword??''], true)}
                </Typography.Text>
              </Tooltip>
            );
          }
        }

        if (name === '编号') {
          column.width = 60
        } else if (name === '中文名称'|| name === '岗位中文名') {
          column.width = isSzseEnv ? 230 : 160
        } else if (name === '英文名称' || name === '岗位英文名') {
          column.width = isSzseEnv ? 224 : 160
        } else if (name === '资产项') {
          column.width = isSzseEnv ? 250 : 120
          column.render = (text) => {
            let metadata = null
            try {
              metadata = JSON.parse(text)
            } catch(error) {
              metadata = text;
            }
            return (
              <AssetItem metadata={metadata} terms={[keyword??'']} />
            );
          }
        }

        newColumns.push(column)
    }

    if (!loadingFilterElements) {
      console.log(data?.data);
      
      for (const item of (data?.data??[])) {
        let index = 0
        let newItem = {}
        for (const elementValue of (item.elementValuesWithoutTypeAttribute??[])) {
            if ((newColumns??[]).length > index) {
              const name = newColumns[index].dataIndex
              newItem[name] = elementValue
            }
            index++
        }
  
        newTableData.push({...item, ...newItem})
      }
    }

    return [[indexCol, ...newColumns]
    , newTableData, data?.total??0]
  }, [filterElements, data, loadingFilterElements, keyword, indexCol, pagination])

  const [canExport, canDelete, canRecover] = React.useMemo(() => {
    if ((selectedRows??[]).length === 0) return [false, false, false]

    let [_canExport, _canDelete, _canRecover] = [true, true, true]
    for (const item of (selectedRows??[])) {
      const exportIndex = (item.allowButtons??[]).findIndex(item => item==='export')
      const deleteIndex = (item.allowButtons??[]).findIndex(item => item==='delete')
      const recoverIndex = (item.allowButtons??[]).findIndex(item => item==='recovery')

      if (exportIndex === -1) {
        _canExport = false
      }
      if (deleteIndex === -1) {
        _canDelete = false
      }
      if (recoverIndex === -1) {
        _canRecover = false
      }
    }

    return [_canExport, _canDelete, _canRecover]
  }, [selectedRows])

  const menuData = React.useMemo(() => {
    const newMenuData = []
    for (const key of rightRow?.allowButtons??[]) {
      if (operationMap[key]) {
        newMenuData.push(operationMap[key])
      }
    }
    return newMenuData
  }, [rightRow])

  const getTemplates = () => {
    setLoadingTemplates(true)
    dispatch({
      type: 'assetmanage.getTemplates',
      callback: data => {
        setLoadingTemplates(false)
        //未挂载资产屏蔽岗位
        setTemplates((data??[]).filter(item=>item.type!=='post'))
        if ((data??[]).length > 0) {
          LocalStorage.set(`templateType-${appId}`, data[0].type)
          setTemplateValue(data[0].type)
        }
      },
      error: () => {
        setLoadingTemplates(false)
      }
    })
  }

  const getFilterElements = () => {
    setLoadingFilterElements(true)
    dispatch({
      type: 'assetmanage.listFilterElementsGroupByType',
      payload: {
        isAdmin: true,
      },
      callback: data => {
        setLoadingFilterElements(false)
        setFilterElements(data)
      },
      error: () => {
        setLoadingFilterElements(false)
      }
    })
  }

  const getRecycles = () => {
    setLoading(true)
    dispatch({
      type: 'assetmanage.listRecycleBinDataAssetsByPage',
      payload: {
        templateType: currentTemplateValue,
        keyword: encodeURIComponent(keyword??''),
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
      },
      callback: data => {
        setLoading(false)
        setData(data)
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const onTemplateChange = (value) => {
    setData()
    setSelectedRows()

    LocalStorage.set(`templateType-${appId}`, value)
    setTemplateValue(value)
    setPagination({ ...pagination, pageNum: 1 })
  }

  const onExportClick = () => {
    window.open(`/api/dataassetmanager/dataAssetApi/exportByDataAssetIds?dataAssetIds=${(selectedRows??[]).map(item=>item.id).toString()}&templateType=${getTemplateType()}`);
  }

  const onRecoverClick = () => {
    modal.confirm({
      title: '提示',
      content: '是否恢复选中的资产?',
      onOk: () => {
        dispatch({
          type: 'assetmanage.recoverDataAssetsFromRecycleBin',
          payload: {
            data: (selectedRows??[]).map(item => item.id)
          },
          callback: () => {
            showMessage("success","恢复成功");
            setSelectedRows();
            getRecycles();
          }
        })
      }
    })
  }

  const onDeleteClick = () => {
    modal.confirm({
      title: '提示',
      content: '是否删除选中的资产?',
      onOk: () => {
        dispatch({
          type: 'assetmanage.deleteDataAssets',
          payload: {
            data: (selectedRows??[]).map(item => item.id)
          },
          callback: () => {
            showMessage("success","删除成功");
            setSelectedRows();
            getRecycles();
          }
        })
      }
    })
  }

  const onRightMenuItemClick = (key, record) => {
    if (key === '查看') {
      onRightDetailClick()
    }
  }

  const onRightDetailClick = () => {
    setUpdateAssetParams({
      visible: true,
      id: rightRow?.id,
      dirId: rightRow?.dirId,
    })
  }

  return (
    <div style={{ backgroundColor: '#fff', height: '100%' }}>
      <div className='flex p-3' style={{
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBottom: '1px solid rgb(239, 239, 239)',
      }}>
        <Space>
          <Select 
            loading={loadingTemplates}
            value={currentTemplateValue}
            onChange={onTemplateChange}
            style={{ width: 100 }}
          >
          {
            (templates??[]).map((item, index) => <Select.Option key={index} value={item.type}>{item.name}</Select.Option>)
          }
          </Select>
          <PermissionButton 
            defaultPermission={canExport} 
            tip={(selectedRows||[]).length===0?'请先选择资产':''}
            onClick={onExportClick} 
            disabled={(selectedRows||[]).length===0}
          >
            导出
          </PermissionButton>
          <PermissionButton 
            defaultPermission={canRecover} 
            tip={(selectedRows||[]).length===0?'请先选择资产':''}
            onClick={onRecoverClick} 
            disabled={(selectedRows||[]).length===0}
          >
            恢复
          </PermissionButton>
          <PermissionButton 
            defaultPermission={canDelete} 
            tip={(selectedRows||[]).length===0?'请先选择资产':''}
            onClick={onDeleteClick} 
            disabled={(selectedRows||[]).length===0}
          >
            删除
          </PermissionButton>
          <Button onClick={() => {
            setFilterElementParams({ visible: true })
          }}>可见列设置</Button>
        </Space>
        <Space>
          <Input size="middle"
            placeholder="请输入关键字"
            value={keyword}
            bordered={true} allowClear
            onChange={(e) => {
              setKeyword(e.target.value)
            }} />
        </Space>
      </div>
      <div className='p-3'>
        <Table
          extraColWidth={32}
          loading={loadingFilterElements||loading}
          columns={columns}
          dataSource={tableData}
          rowKey='id'
          pagination={false}
          rowSelection={{
            selectedRowKeys: (selectedRows??[]).map(item => item.id),
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedRows(selectedRows)
            }      
          }}
          rowClassName={(record, index) => {
            return (record?.id === rightRow?.id) ? 'yy-table-select-row' : ''
          }}
          shouldRowContextMenu={(record) => {
            setRightRow(record)
            let allowContextMenu = false

            for (const key of (record.allowButtons??[])) {
              if (operationMap[key]) {
                allowContextMenu = true
                break
              }
            }
            return allowContextMenu
          }}
          menuData={menuData}
          menuPermissions={menuData}
          onMenuItemClick={onRightMenuItemClick}
          scroll={{ y: 'calc(100vh - 209px - 72px - 57px)' }}
        />
        <Pagination
          className="text-center mt-3"
          showSizeChanger
          onChange={(page, size) => {
            setSelectedRows()
            setPagination({ pageNum: page, pageSize: size })
          }}
          onShowSizeChange={(page,size) => {
            setSelectedRows()
            setPagination({ pageNum: page, pageSize: size })
          }}
          current={pagination.pageNum}
          pageSize={pagination.pageSize}
          defaultCurrent={1}
          total={total}
          showTotal={total => `共 ${total} 条`}
        />
      </div>
      <UpdateAsset
        {...updateAssetParams}
        reference={AssetRecycleReference}
        readonly
        onCancel={(refresh) => {
          setUpdateAssetParams({
            visible: false,
            id: undefined,
            dirId: undefined,
          })

          refresh && getRecycles()
        }}
      />
      <FilterElementModal
        type='admin'
        reference={AssetManageReference}
        {...filterElementParams}
        onCancel={(refresh) => {
          setFilterElementParams({ visible: false })
          if (refresh) {
            getFilterElements()
            getRecycles()
          }
        }}
      />
      {contextHolder}
    </div>
  )
}

export default FC