import DatePicker from '@/components/DatePicker'
import FileModal from '@/components/FileModal'
import { contractReturnStore } from '@/store/mobx'
import { iReceivableState, iEditableCellProps } from '@/types/contract'
import { iFileModal } from '@/types/file'
import consts from '@/utils/consts'
import { dayjsFormat } from '@/utils/util'
import { DisconnectOutlined } from '@ant-design/icons'
import { Form, Input, Popconfirm, Table } from 'antd'
import locale from 'antd/es/date-picker/locale/zh_CN'
import dayjs from 'dayjs'
import { observer } from 'mobx-react'
import React, { useEffect, useMemo, useState } from 'react'
import { apiDelReturn, apiGetReturns, apiUpdateReturn } from './api'


const EditableCell: React.FC<iEditableCellProps> = ({
  editing,
  dataIndex,
  title,
  cellType,
  children,
  record,
  index,
  ...restProps
}) => {
  // console.log(dataIndex, record)

  const cellNode = cellType === 'text' ? <Input size="small" allowClear/> : <DatePicker size="small" allowClear locale={locale} />

  const isDate = useMemo(() => {
    return dataIndex === 'createTime' || dataIndex === 'time'
  }, [ dataIndex ])
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item name={dataIndex} initialValue={isDate ? dayjs(record[dataIndex]) : record[dataIndex]} style={{ margin: 0 }} rules={[ dataIndex === 'remarks' ? {} : { required: true, message: `请输入${title}!` } ]}>
          {cellNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  )
}


const Receivable:React.FC<{}> = () => {
  const [ form ] = Form.useForm()
  const [ data, setData ] = useState<Array<iReceivableState>>([])
  const [ id, setId ] = useState<string>('')
  const [ fileModal, setFileModal ] = useState<iFileModal>({
    visible: false,
    dataType: consts.DATA_TYPE.RETURN,
    dataId: ''
  })
  const [ editingKey, setEditingKey ] = useState<string>('')

  const delConfirm = async (id: string, contractsId: string, bidsectionId: string) => {
    const { code = -1 } = await apiDelReturn(id, contractsId, bidsectionId)
    if (code === consts.RET_CODE.SUCCESS) {
      const newData = data.filter(item => item.id !== id)
      setData(newData)
    }
  }

  useEffect(() => {
    if (contractReturnStore.contract.id) {
      if (contractReturnStore.contract.id !== id) {
        setId(contractReturnStore.contract.id)
        initData()
      } else if (contractReturnStore.shouldUpdate && contractReturnStore.shouldUpdate === '2') {
        initData()
      }
      contractReturnStore.shouldUpdate && (contractReturnStore.changeUpdate(''))
    }
  }, [ contractReturnStore.contract.id, contractReturnStore.shouldUpdate ])
  const initData = async() => {
    const { code = -1, data = [] } = await apiGetReturns(contractReturnStore.contract.id, contractReturnStore.contract.bidsectionId)
      if (code === consts.RET_CODE.SUCCESS) {
        setData(data)
      }
  }
  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as iReceivableState

      const newData = [ ...data ]
      const index = newData.findIndex(item => key === item.id)
      if (index > -1) {
        const item = newData[index]
        const payload = { ...row, time: dayjsFormat(row.time, 'YYYY-MM-DD'), createTime: dayjsFormat(row.createTime, 'YYYY-MM-DD'), id: item.id, bidsectionId: item.bidsectionId, contractsId: item.contractsId }
        const { code = -1 } = await apiUpdateReturn(payload)
        if (code === consts.RET_CODE.SUCCESS) {
          newData.splice(index, 1, {
            ...item,
            ...row
          })
          setData(newData)
        }
      }
      setEditingKey('')
      // else {
      //   newData.push(row)
      //   setData(newData)
      //   setEditingKey('')
      // }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo)
    }
  }

  const isEditing = (record: iReceivableState) => record.id === editingKey
  const columns = [
    {
      dataIndex: 'sort',
      width: '5%',
      // eslint-disable-next-line react/display-name
      render: (_: any, record: any, index: number) => {
        return <span>{index + 1}</span>
      }
    },
    {
      title: '回款日期',
      dataIndex: 'time',
      editable: true,
      width: '12%',
      // eslint-disable-next-line react/display-name
      render: (text: string) => <span>{dayjsFormat(text, 'YYYY-MM-DD')}</span>
    },
    {
      title: '回款金额',
      dataIndex: 'price',
      editable: true,
      width: '12%',
      // eslint-disable-next-line react/display-name
      render: (text: string) => <span className="pi-text-right pi-width-100P">{text}</span>
    },
    {
      title: '回款方式',
      dataIndex: 'way',
      editable: true,
      width: '12%'
    },
    {
      title: '创建人',
      dataIndex: 'createUser',
      editable: true,
      width: '12%'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      editable: true,
      width: '12%',
      // eslint-disable-next-line react/display-name
      render: (text: any) => <span>{dayjsFormat(text, 'YYYY-MM-DD')}</span>
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      editable: true,
      width: '12%'
    },
    {
      title: '附件',
      dataIndex: 'fileCounts',
      // eslint-disable-next-line react/display-name
      render: (text: number, record: iReceivableState) => <span className="pi-pointer" onClick={() => setFileModal({ ...fileModal, dataId: record.id, visible: true })}><DisconnectOutlined /> {text}</span>
    },
    {
      title: '操作',
      dataIndex: 'opreate',
      width: '10%',
      // eslint-disable-next-line react/display-name
      render: (text: any, record: iReceivableState) => {
        const editable = isEditing(record)
        return (
        <div>
          {
            editable ?
            (<><span className="pi-link-blue pi-mg-right-5" onClick={() => save(record.id)}>保存</span><span className="pi-link-blue" onClick={() => setEditingKey('')}>取消</span></>)
            :
            <span className="pi-link-blue" onClick={() => setEditingKey(record.id)}>编辑</span>
          }
          <Popconfirm title="确认删除?" cancelText="取消" okText="确认" onConfirm={() => delConfirm(record.id, record.contractsId, record.bidsectionId)}>
            <span className="pi-link-red pi-mg-left-5">删除</span>
          </Popconfirm>
        </div>
        )
      }
    }
  ]

  const cancel = () => {
    setEditingKey('')
  }


  const mergedColumns = columns.map(col => {
    if (!col.editable) {
      return col
    }
    return {
      ...col,
      onCell: (record: iReceivableState) => ({
        record,
        cellType: col.dataIndex === 'createTime' || col.dataIndex === 'time' ? 'DatePicker' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record)
      })
    }
  })

  return (
    <>
      <Form form={form} component={false}>
        <Table
          components={{ body: { cell: EditableCell } }}
          dataSource={data}
          columns={mergedColumns}
          bordered
          rowClassName="editable-row"
          pagination={{ onChange: cancel, size:"small", pageSize: 7 }}
          rowKey={record => record.id}
           />
      </Form>
      <FileModal
        visible={fileModal.visible}
        dataType={fileModal.dataType}
        dataId={fileModal.dataId}
        onCancel={() => setFileModal({ ...fileModal, visible: false })}
        showUpload={true}
       />
    </>
  )
}
export default observer(Receivable)
