import React, { useEffect, useState } from 'react'
import { PageHeader, Descriptions, List, Steps, Row, Col, Rate, Button, Statistic, Modal, Typography, notification } from 'antd'
import { fetch, fetchList, apis } from '@/utils/request'
import router from 'umi/router'
import Prompt from '@/components/Prompt'
import Title from './components/Title'
import Dispatch from './components/Dispatch'
import Price from './components/Price'

const TicketTypeDict = {
  '0': '投诉',
  '1': '报修',
  '2': '联系物业',
}

const RepairTypeDict = {
  '0': '公共区域',
  '1': '房屋质量',
  '2': '户内设施',
}

const imgGrid = {
  gutter: 16,
  xs: 1,
  sm: 2,
  md: 6,
  lg: 6,
  xl: 6,
  xxl: 10,
}

const getTicketDetail = fetch(apis.ticket.ticketEdit)
const addDispatch = fetch(apis.ticket.addRecord)
const rejectTicket = fetch(apis.ticket.updateTicketStatus)
const updateTicketPrice = fetch(apis.ticket.updateTicketPrice)

export default props => {
  const [loading, setLoading] = useState(false)
  const [showPrompt, setShowPrompt] = useState(false)
  const [showDispatch, setShowDispatch] = useState(false)
  const [showReject, setShowReject] = useState(false)
  const [ticketData, setTicketData] = useState({})
  const [approvalProcessList, setApprovalProcessList] = useState([])

  const ticketType = [
    TicketTypeDict[ticketData.type] || '',
    ticketData.type === '2' ? (RepairTypeDict[ticketData.repairType] || '') : ''
  ].join('-')

  const { id } = props.location.query

  const handleDispatchTicket = ({ userId }) => {
    addDispatch({data: {ticketId: id, id: userId}}).then(res => {
      Modal.success({
        content: '分配人员成功',
        onOk: () => window.location.reload()
      })
    })

    setShowDispatch(false)
  }

  const handleReject = textContent => {
    rejectTicket({data:{ticketId: id, textContent}}).then(res => {
      Modal.success({
        content: '拒绝受理成功',
        onOk: () => router.go(-1)
      })
    })
  }

  const handleChangePrice = vals => {
    if (!vals.priceExplain || vals.price === undefined) {
      notification.warn({ message: '请正确填写说明及金额' })
      return
    }

    const price = Math.floor(vals.price * 100)
    updateTicketPrice({data: {id, price, priceExplain: vals.priceExplain}}).then(res => {
      Modal.success({
        content: '设置费用成功',
        onOk: () => window.location.reload()
      })
    })
  }

  useEffect(() => {
    getTicketDetail({data: {id}}).then(res => {
      const { recordList } = res || {}
      setTicketData(res)
      setApprovalProcessList(recordList)
    })
  }, [])

  return (
    <div>
      <PageHeader
        title={ticketData.ticketTitle}
        subTitle="工单详情"
        backIcon={false}
        style={{ borderBottom: '1px solid rgb(235, 237, 240)' }}
      >
        <div style={{display: 'flex'}}>
          <div>
            <Descriptions column={3}>
              <Descriptions.Item label="工单号">{ticketData.id}</Descriptions.Item>
              <Descriptions.Item label="工单类型">{ticketType}</Descriptions.Item>
              <Descriptions.Item label="发起时间">{ticketData.createDate}</Descriptions.Item>
              <Descriptions.Item label="发起人">{ticketData.createUserNmae}</Descriptions.Item>
              <Descriptions.Item label="联系方式">{ticketData.loginName}</Descriptions.Item>
              <Descriptions.Item label="负责人">{ticketData.tpUserNmae || '暂无'}</Descriptions.Item>
              <Descriptions.Item label="工单内容">{ticketData.ticketContent}</Descriptions.Item>
            </Descriptions>
          </div>
          <div style={{minWidth: '150px'}}>
            {
              !ticketData.billInvoiceId ?
                <Button onClick={() => setShowPrompt(true)}>设置费用</Button> :
                <Statistic
                  title={<Typography.Text ellipsis>{ticketData.priceExplain || '费用'}</Typography.Text>}
                  prefix="￥"
                  value={ticketData.price ? (ticketData.price / 100) : 0}
                  precision={2}
                />
            }
          </div>
        </div>
        {
          ticketData.contentImageUrl && ticketData.contentImageUrl.length && (
            <List dataSource={ticketData.contentImageUrl} grid={imgGrid} renderItem={it => (
              <List.Item><img src={it} alt="" style={{width: '100%'}} /></List.Item>
            )} />
          )
        }
      </PageHeader>

      <div>
        <h4 style={{marginTop: '24px'}}>沟通记录</h4>
        <Steps progressDot direction="vertical" current={1}>
        {
          (approvalProcessList || []).map(item => {
            return (
              <Steps.Step
                key={item.id}
                style={{width: '100%'}}
                title={(
                  <Title title={item.statusName}>
                    {
                      ticketData.status === '0' && (
                        <>
                          <Button type="primary" onClick={() => setShowDispatch(true)}>分配工单</Button>
                          <Button type="danger" style={{marginLeft: '24px'}} onClick={() => setShowReject(true)}>拒绝受理</Button>
                        </>
                      )
                    }
                  </Title>
                )}
                subTitle={item.createDate}
                description={(
                  <div>
                    {
                      item.status - 0 === 5 && (
                        <Descriptions column={2}>
                          {/* <Descriptions.Item label="评分"><Rate value={item.score}/></Descriptions.Item> */}
                          <Descriptions.Item label="时间"><Rate value={item.createDate}/></Descriptions.Item>
                          <Descriptions.Item label="评语">{item.comment}</Descriptions.Item>
                        </Descriptions>
                      )
                    }
                    {
                      item.statusContent && item.statusContent.length > 0 && (
                        item.statusContent.map(ctt => {
                          return (
                            <div>
                              <div>{ `${ctt.userName} : ${ctt.content}` }</div>
                              {
                                ctt.imgURL && ctt.imgURL.length > 0 && (
                                  <List dataSource={ctt.imgURL} grid={imgGrid} renderItem={it => (
                                    <List.Item><img src={it.imageUrl} alt="" style={{width: '100%'}} /></List.Item>
                                  )} />
                                )
                              }
                            </div>
                          )
                        })
                      )
                    }
                  </div>
              )}/>
            )
          })
        }
        </Steps>
      </div>

      {/* 设置缴费金额 */}
      <Price visible={showPrompt} onSubmit={handleChangePrice} onCancel={() => setShowPrompt(false)} />

      {/* 工单分配 */}
      <Dispatch visible={showDispatch} userList={ticketData.tpUsersList} onSubmit={handleDispatchTicket} onCancel={() => setShowDispatch(false)} />
      {/* 拒绝原因 */}
      <Prompt visible={showReject} onCancel={() => setShowReject(false)} onOk={handleReject} placeholder="请填写拒绝原因"></Prompt>
    </div>
  )
}
