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

import { appId } from "../../../App"
import { dispatch } from '../../../model'
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 { AssetDraftReference } from "../../../util/constant"
import StartProcess from "./start-process"
import ImportAsset from "./import"
import DistributeTask from './distribute-task'
import RedistributeTask from './redistribute-task'
import PermissionButton from '../../../util/Component/PermissionButton'
import StartFlow from './start-flow'

// const specialCol = ['数据关键用户', '业务数据owner', 'it责任人', '创建人', '更新人']
const specialCol = ['创建人', '更新人']

const operationMap = {
  view: '查看',
  edit: '编辑',
  // delete: '删除',
  distribute: '分配',
  reDistribute: '转分配',
  submit: '提交',
  // publish: '发布',
  changeToPendingSubmit: '转为待提交',
}

// const draftStates = [
//   { id: 'PENDINGSUBMIT', name: '待提交' },
//   { id: 'tobeReleased', name: '待发布' },
//   { id: 'PROCESSING', name: '处理中' },
//   { id: 'DONE', name: '已完成' },
//   { id: 'PUBLISHED', name: '已发布' },
// ]

const FC = (props) => {
  const [loadingTemplates, setLoadingTemplates] = React.useState(false)
  const [templates, setTemplates] = React.useState()
  const [currentTemplateValue, setTemplateValue] = React.useState()
  const [loadingDraftStates, setLoadingDraftStates] = React.useState(false)
  const [draftStates, setDraftStates] = React.useState()
  const [pagination, setPagination] = React.useState({ pageNum: 1, pageSize: 20 })
  const [currentElementValue, setElementValue] = React.useState()
  const [keyword, setKeyword] = React.useState()
  const [draftState, setDraftState] = React.useState() 
  const [selectedRows, setSelectedRows] = React.useState()
  const [loadingElements, setLoadingElements] = React.useState()
  const [elements, setElements] = 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 [users, setUsers] = React.useState()
  const [isAdmin, setAdmin] = React.useState()
  const [importAssetParams, setImportAssetParams] = React.useState({
    visible: false
  })
  const [updateAssetParams, setUpdateAssetParams] = React.useState({
    visible: false,
    action: undefined,
    id: undefined,
    dirId: undefined,
    readonly: false,
  })
  const [startProcessParams, setStartProcessParams] = React.useState({
    visible: false,
    items: undefined,
  })
  const [distributeTaskParams, setDistributeTaskParams] = React.useState({
    visible: false,
    items: undefined,
  })
  const [redistributeTaskParams, setRedistributeTaskParams] = React.useState({
    visible: false,
    items: undefined
  })
  const [startFlowParams, setStartFlowParams] = React.useState({
    visible: false,
    ids: undefined
  })
  const [rightRow, setRightRow] = React.useState()
  
  const [modal, contextHolder] = Modal.useModal();

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

  React.useEffect(() => {
    if (currentTemplateValue && isAdmin!==undefined) {
      getElements()
      getFilterElements()
    }
  }, [currentTemplateValue, isAdmin])

  useDebounceEffect(() => {
    if (currentTemplateValue && isAdmin!==undefined) {
      getDrafts()
    }
  }, [currentTemplateValue, keyword, currentElementValue, pagination, isAdmin, draftState], { wait: 300 })

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

    let [_canExport, _canPublish, _canDelete, _canFlow] = [true, true, true, true]
    for (const item of (selectedRows??[])) {
      const exportIndex = (item.allowButtons??[]).findIndex(item => item==='export')
      const publishIndex = (item.allowButtons??[]).findIndex(item => item==='publish')
      const deleteIndex = (item.allowButtons??[]).findIndex(item => item==='delete')
      const flowIndex = (item.allowButtons??[]).findIndex(item => item==='flowSubmitForAudit')

      if (exportIndex === -1) {
        _canExport = false
      }
      if (publishIndex === -1) {
        _canPublish = false
      }
      if (deleteIndex === -1) {
        _canDelete = false
      }
      if (flowIndex === -1) {
        _canFlow = false
      }
    }

    return [_canExport, _canPublish, _canDelete, _canFlow]
  }, [selectedRows])

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

  const pathCol = {
    title: '路径',
    dataIndex: 'dirPath',
    ellipsis: true,
    width: 120,
    render: (text, record) => {
      return (
        <Tooltip title={text}>
          <Typography.Text ellipsis={true}>
          {highlightSearchContentByTerms(text, [keyword??''], true)}
          </Typography.Text>
        </Tooltip>
      );
    }
  }

  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 fixedCols = [
    {
      title: '当前处理人',
      dataIndex: 'nextProcessUsers',
      width: 120,
      fixed: 'right',
    },
    {
      title: '修改类型',
      dataIndex: 'operationType',
      ellipsis: true,
      width: 120,
      fixed: 'right',
      render: (text, record) => {
        if (text === 'release') return '发布'
        if (text === 'change') return '变更'
        if (text === 'offline') return '下线'

        return ''
      }
    },
    {
      title: '状态',
      dataIndex: 'draftState',
      ellipsis: true,
      width: 120,
      fixed: 'right',
      render: (text, record) => {
        const index = (draftStates??[]).findIndex(item => item.state === text)

        if (index !== -1) {
          return draftStates[index].desc
        }

        return ''
      }
    },
  ]

  const [columns, tableData, total] = React.useMemo(() => {
    let [newColumns, newTableData] = [[], []]

    for (const element of filterElements??[]) {
      for (const name of element.names??[]) {
        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) {
      for (const item of (data?.data??[])) {
        let index = 0
        let newItem = {}
        for (const elementValue of (item.elementValues??[])) {
          for (const value of elementValue.values) {
            if ((newColumns??[]).length > index) {
              const name = newColumns[index].dataIndex
              newItem[name] = value

              if (specialCol.indexOf((name??'').toLowerCase()) !== -1) {
                const user = users?.filter((user)=>(user.pernr===value))
                if ((user??[]).length > 0) {
                  newItem[name] = user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr;
                }
              }
            }
  
            index++
          }
        }
  
        newTableData.push({...item, ...newItem})
      }
    }

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

  const getAdmin = () => {
    dispatch({
      type: 'assetmanage.checkAdmin',
      callback: (data) => {
        setAdmin((data==='true')?true:false)
      }
    })
  }

  const getUsers = () => {
    dispatch({
      type: 'pds.getOwners',
      callback: (data) => {
        setUsers(data)
      }
    })
  }

  const getTemplates = () => {
    setLoadingTemplates(true)
    dispatch({
      type: 'assetmanage.getTemplates',
      callback: data => {
        setLoadingTemplates(false)
        setTemplates(data)
        if ((data??[]).length > 0) {
          LocalStorage.set(`templateType-${appId}`, data[0].type)
          setTemplateValue(data[0].type)
        }
      },
      error: () => {
        setLoadingTemplates(false)
      }
    })
  }

  const getElements = () => {
    setLoadingElements(true)
    dispatch({
      type: 'assetmanage.listElements',
      callback: data => {
        setLoadingElements(false)
        setElements(data)
      },
      error: () => {
        setLoadingElements(false)
      }
    })
  }

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

  const getStates = () => {
    setLoadingDraftStates(true)
    dispatch({
      type: 'assetmanage.listDraftStates',
      callback: data => {
        setLoadingDraftStates(false)
        setDraftStates(data)
      },
      error: () => {
        setLoadingDraftStates(false)
      }
    })
  }

  const getDrafts = () => {
    setLoading(true)
    let code = null
    if (draftState!==undefined&&draftState!==null&&draftState!=='') {
      const index = (draftStates??[]).findIndex(item => item.id === draftState)
      if (index !== -1) {
        code = draftStates[index].state
      }
    }

    dispatch({
      type: 'assetmanage.getDrafts',
      payload: {
        isAdmin,
        queryElementId: currentElementValue,
        templateType: currentTemplateValue,
        keyword: encodeURIComponent(keyword??''),
        state: code,
        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 onBatchUpdateClick = () => {
    setImportAssetParams({
      visible: true,
    })
  }

  const onExportClick = () => {
    window.open(`/api/dataassetmanager/draftApi/exportByDraftIds?draftIds=${(selectedRows??[]).map(item => item.id).toString()}&templateType=${currentTemplateValue}`);
  }

  const onFlowClick = () => {
    setStartFlowParams({
      visible: true,
      ids: (selectedRows??[]).map(item => item.id)
    })
  }

  const onPublishClick = () => {
    if (isAdmin) {
      modal.confirm({
        title: '是否确认发布选中的资产',
        onOk: () => {
          dispatch({
            type: 'assetmanage.publishDrafts',
            payload: {
              data: (selectedRows??[]).map(item => item.id)
            },
            callback: () => {
              showMessage("success","发布成功")
              setSelectedRows()
              getDrafts()
            }
          })
        }
      })
    } else {
      setStartProcessParams({
        visible: true,
        items: selectedRows
      })
    }
  }

  const onDeletesClick = () => {
    modal.confirm({
      title: '是否确认删除选中的资产目录',
      onOk: () => {
        dispatch({
          type: 'assetmanage.deleteDrafts',
          payload: {
            data: (selectedRows??[]).map(item => item.id)
          },
          callback: () => {
            showMessage("success","删除成功")
            setSelectedRows()
            getDrafts()
          }
        })
      }
    })
  }

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

  const onRightEditClick = () => {
    setUpdateAssetParams({
      visible: true,
      action: 'edit',
      id: rightRow?.id,
      dirId: rightRow?.dirId,
      readonly: false,
    })
  }

  const onRightDistributeClick = () => {
    if (rightRow) {
      setDistributeTaskParams({
        visible: true,
        items: [rightRow]
      })
    }
  }

  const onRightRedistributeClick = () => {
    if (rightRow) {
      setRedistributeTaskParams({
        visible: true,
        items: [rightRow]
      })
    }
  }

  const onRightSubmitClick = () => {
    modal.confirm({
      title: '提示',
      content: '是否确认提交选中的资产?',
      onOk: () => {
        dispatch({
          type: 'assetmanage.submitDraft',
          payload: {
            data: [rightRow?.id]
          },
          callback: (data) => {
            showMessage('success', '提交成功')
            getDrafts()
          }
        })
      }
    })
  }

  const onRightChangeToPendingSubmitClick = () => {
    modal.confirm({
      title: '提示',
      content: '是否确认转为待提交选中的资产?',
      onOk: () => {
        dispatch({
          type: 'assetmanage.changeToPendingSubmitDraft',
          payload: {
            data: [rightRow?.id]
          },
          callback: (data) => {
            showMessage('success', '转为待提交成功')
            getDrafts()
          }
        })
      }
    })
  }

  const onRightMenuItemClick = (key, record) => {
    if (key === '查看') {
      onRightDetailClick()
    } else if (key === '编辑') {
      onRightEditClick()
    } else if (key === '分配') {
      onRightDistributeClick()
    } else if (key === '转分配') {
      onRightRedistributeClick()
    } else if (key === '提交') {
      onRightSubmitClick()
    } else if (key === '转为待提交') {
      onRightChangeToPendingSubmitClick()
    }
  }

  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>
          <Button onClick={onBatchUpdateClick}>批量修改</Button>
    
          <PermissionButton 
            defaultPermission={canExport} 
            tip={(selectedRows||[]).length===0?'请先选择资产':''}
            onClick={onExportClick} 
            disabled={(selectedRows||[]).length===0}
          >
            导出
          </PermissionButton>

          <PermissionButton 
            defaultPermission={canFlow} 
            tip={(selectedRows||[]).length===0?'请先选择资产':''}
            onClick={onFlowClick} 
            disabled={(selectedRows||[]).length===0}
          >
            送审
          </PermissionButton>

          <PermissionButton 
            defaultPermission={canPublish} 
            tip={(selectedRows||[]).length===0?'请先选择资产':''}
            onClick={onPublishClick} 
            disabled={(selectedRows||[]).length===0}
          >
            发布
          </PermissionButton>

          <PermissionButton 
            defaultPermission={canDelete} 
            tip={(selectedRows||[]).length===0?'请先选择资产':''}
            onClick={onDeletesClick} 
            disabled={(selectedRows||[]).length===0}
          >
            删除
          </PermissionButton>
        </Space>
        <Space>
          <Select allowClear
            placeholder='请选择状态'
            value={draftState}
            onChange={(val) => {
              setDraftState(val)
            }}
            loading={loadingDraftStates}
            style={{ width: 160 }}
          >
          {
            draftStates?.map((item, index) => (
              <Select.Option key={item.id} value={item.id}>{item.desc}</Select.Option>
            ))
          }
          </Select>
          <Select allowClear
            loading={loadingElements}
            value={currentElementValue}
            placeholder='请选择搜索属性'
            onChange={(val) => {
              setElementValue(val)
            }}
            style={{ width: 160 }}
          >
          {
            (elements??[]).map((item, index) => (
              <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
            ))
          }
          </Select>
          <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>
      <ImportAsset
        {...importAssetParams}
        onCancel={() => {
          setImportAssetParams({
            visible: false,
          })
        }}
        onSuccess={() => {
          getDrafts()
        }}
      />
      <UpdateAsset
        {...updateAssetParams}
        reference={AssetDraftReference}
        onCancel={(refresh) => {
          setUpdateAssetParams({
            visible: false,
            action: undefined,
            id: undefined,
            dirId: undefined,
            readonly: false,
          })

          refresh && getDrafts()
        }}
      />
      <StartProcess 
        {...startProcessParams}
        onCancel={(refresh) => {
          setStartProcessParams({
            visible: false,
            items: undefined
          })

          refresh && getDrafts()
        }}
      />
      <DistributeTask 
        {...distributeTaskParams}
        onCancel={(refresh) => {
          setDistributeTaskParams({
            visible: false,
            items: undefined,
          })

          refresh && getDrafts()
        }}
      />
      <RedistributeTask 
        {...redistributeTaskParams}
        onCancel={(refresh) => {
          setRedistributeTaskParams({
            visible: false,
            items: undefined,
          })

          refresh && getDrafts()
        }}
      />
      <StartFlow
        {...startFlowParams}
        onCancel={(refresh) => {
          setStartFlowParams({
            visible: false,
            ids: undefined
          })

          refresh && getDrafts()
        }}
      />
      {contextHolder}
    </div>
  )
}

export default FC