import Authorization from '@/components/Authorization'
import Header from '@/components/Header'
import Slot from '@/components/Header/slot'
import RuleModal from '@/components/RuleModal'
import SvgIcon from '@/components/SvgIcon'
import { apiSaveRule } from '@/pages/Safe/Content/List/api'
import { contractStore, tenderStore } from '@/store/mobx'
import { ContractTree, iModalProps } from '@/types/contract'
import { contractTreeBaseId } from '@/utils/common/constStatus'
import consts from '@/utils/consts'
import { Button, message, Tooltip } from 'antd'
import React, { useState, useEffect } from 'react'
import { apiResfulContract } from './api'
import ContractModal from '@/pages/Contract/Content/Income/components/Modal'
import TableContent from '../Income/components/TableContent'
import { RouteComponentProps } from 'react-router'
import { ContractType } from '@/store/mobx/contract'
import { apiResfulContractTree } from '../Income/api'

interface iModal {
  visible: boolean
  loading: boolean
}

const Expenditure: React.FC<RouteComponentProps> = ({ history }) => {
  useEffect(() => {
    contractStore.resetContractStore()
  }, [])
  const [ modalObj, setModalObj ] = useState<iModalProps>({
    type: '',
    visible: false,
    confirmLoading: false,
    contractType: 'expenditure'
  })
  const [ row, setRow ] = useState<ContractTree>({
    elderBrother: false,
    isEnd: false,
    attribsortution: 0,
    attribution: '',
    bidsectionId: '',
    children: [],
    code: '',
    contractCode: '',
    contractId: '',
    contractName: '',
    contractPrice: '',
    contractReturned: '',
    contractStatus: 0,
    contractsPaid: '',
    createTime: '',
    depth: 0,
    id: '',
    name: '',
    operation: '',
    parentId: '',
    projectId: '',
    serial: 0,
    templateNumber: 0
  })
  const [ ruleModal, setRuleModal ] = useState<iModal>({
    visible: false,
    loading: false
  })
  const onCreate = async (values: any, type: any) => {
    setModalObj({
      ...modalObj,
      confirmLoading: true
    })
    const { code = -1, contract = {} } = await apiResfulContract(type, values)
    if (code === consts.RET_CODE.SUCCESS) {
      contractStore.updateContract(contract)
      contractStore.resetTree(ContractType.EXPENDITURE, tenderStore.bid)
      if (type === 'paid') {
        contractStore.changeUpdate('2')
      }
    }
    setModalObj({
      ...modalObj,
      type: '',
      visible: false,
      confirmLoading: false
    })
  }
  const changeModalType = (type: string) => {
    setModalObj({
      ...modalObj,
      visible: true,
      type
    })
  }
  const treeResfulApiHandler = async (type: string, payload: any) => {
    const { code = -1, section = {} } = await apiResfulContractTree(type, payload, consts.CONTRACT_TREE.PAID)
    if (code === consts.RET_CODE.SUCCESS) {
      contractStore.resetTree(ContractType.EXPENDITURE, tenderStore.bid)
      if (type !== 'add' && type !== 'del') {
        setRow({ ...row, ...section })
      }
    }
  }

  const onRuleCreate = async (ruleValue: any) => {
    setRuleModal({ ...ruleModal, loading: true })
    const { code = -1 } = await apiSaveRule({ bidsectionId: tenderStore.bid, type: 'contract_paid_rule', rule: ruleValue })
    if (code === consts.RET_CODE.SUCCESS) {
      message.success("规则更改成功")
    }
    setRuleModal({ ...ruleModal, loading: false, visible: false })
  }

  // 切换到删除合同弹窗
  const toggleReloadModal = (type: string) => {
    setModalObj({ ...modalObj, visible: false })
    setTimeout(() => {
      setModalObj({ ...modalObj, visible: true, type })
    }, 300)
  }
  const showCBtn = () => {
    return !row.children && !row.contractCode && row.id
  }

  return (
    <div className="wrap-contaniner">
      <Header title="维护项目节：">
        <Slot position="left">
          <div className="pi-flex-row">
            {
              row.id ?
                <>
                  <Tooltip title="添加子项">
                    <Button type="text" icon={<SvgIcon type="xxh-plus" style={{ color: '#007bff', fontSize: 12 }} />} onClick={() => treeResfulApiHandler('add', { id: row.id, bidsectionId: row.bidsectionId })} />
                  </Tooltip>
                  {
                    !row.children?.length && row.depth !== 1 ?
                      <Tooltip title="删除">
                        <Button type="text" icon={<SvgIcon type="xxh-times" style={{ color: '#007bff', fontSize: 12 }} />} onClick={() => treeResfulApiHandler('del', { id: row.id, bidsectionId: row.bidsectionId })} />
                      </Tooltip>
                      : <span className="pi-width-32 pi-height-32 pi-pd-tb-4 pi-flex-row-center"><SvgIcon type="xxh-times" style={{ color: '#9a9a9a', fontSize: 12 }} /></span>
                  }
                  {
                    row.parentId && row.parentId !== contractTreeBaseId ?
                      <Tooltip title="升级">
                        <Button type="text" icon={<SvgIcon type="xxh-arrow-left" style={{ color: '#007bff', fontSize: 12 }} onClick={() => treeResfulApiHandler('depth', { id: row.id, bidsectionId: row.bidsectionId, operation: 'upDepth' })} />} />
                      </Tooltip>
                      :
                      <span className="pi-width-32 pi-height-32 pi-pd-tb-4 pi-flex-row-center"><SvgIcon type="xxh-arrow-left" style={{ color: '#9a9a9a', fontSize: 12 }} /></span>
                  }
                  {
                    row.elderBrother ?
                      <Tooltip title="降级">
                        <Button type="text" icon={<SvgIcon type="xxh-arrow-right" style={{ color: '#007bff', fontSize: 12 }} />} onClick={() => treeResfulApiHandler('depth', { id: row.id, bidsectionId: row.bidsectionId, operation: 'downDepth' })} />
                      </Tooltip>
                      :
                      <span className="pi-width-32 pi-height-32 pi-pd-tb-4 pi-flex-row-center"><SvgIcon type="xxh-arrow-right" style={{ color: '#9a9a9a', fontSize: 12 }} /></span>
                  }
                  {
                    row.elderBrother ?
                      <Tooltip title="上移">
                        <Button type="text" icon={<SvgIcon type="xxh-arrow-up" style={{ color: '#007bff', fontSize: 12 }} />} onClick={() => treeResfulApiHandler('serial', { id: row.id, bidsectionId: row.bidsectionId, operation: 'upSerial' })} disabled={!row.elderBrother} />
                      </Tooltip>
                      :
                      <span className="pi-width-32 pi-height-32 pi-pd-tb-4 pi-flex-row-center"><SvgIcon type="xxh-arrow-up" style={{ color: '#9a9a9a', fontSize: 12 }} /></span>
                  }
                  {
                    !row.isEnd ?
                      <Tooltip title="下移">
                        <Button type="text" icon={<SvgIcon type="xxh-arrow-down" style={{ color: '#007bff', fontSize: 12 }} />} onClick={() => treeResfulApiHandler('serial', { id: row.id, bidsectionId: row.bidsectionId, operation: 'downSerial' })} disabled={row.isEnd} />
                      </Tooltip>
                      :
                      <span className="pi-width-32 pi-height-32 pi-pd-tb-4 pi-flex-row-center"><SvgIcon type="xxh-arrow-down" style={{ color: '#9a9a9a', fontSize: 12 }} /></span>
                  }
                </>
                : ''
            }
          </div>
        </Slot>
        <Slot position="right">
          <Button type="ghost" size="small" icon={<SvgIcon type="xxh-cog" />} className="pi-mg-right-3" style={{ color: '#007bff' }} onClick={() => setRuleModal({ ...ruleModal, visible: true })}>设置</Button>
          {
            showCBtn ?
              <Authorization type="contract" auth="add">
                <Button type="primary" size="small" onClick={() => setModalObj({ ...modalObj, type: 'create', visible: true })}>新建支出合同</Button>
              </Authorization>
              : ""
          }
        </Slot>
      </Header>
      <TableContent
        changeModalType={changeModalType}
        row={row}
        setRow={(record: ContractTree) => setRow({ ...row, ...record })}
        history={history}
        type={ContractType.EXPENDITURE}
      />
      <RuleModal
        type={consts.RULE.CONTRACT_PAID}
        title="合同管理编号设置"
        visible={ruleModal.visible}
        onCreate={onRuleCreate}
        loading={ruleModal.loading}
        onCancel={() => setRuleModal({ ...ruleModal, visible: false })}
      />
      <ContractModal row={row} modalObj={modalObj} onConfirm={onCreate} onCancel={() => setModalObj({ ...modalObj, visible: false })} reload={(type) => toggleReloadModal(type)} />
    </div>
  )
}

export default Expenditure
