<template>
  <a-drawer
    :visible="visible"
    :width="isMobile ? screenWidth : screenWidth * 0.85"
    placement="right"
    title="工单进度查询"
    @close="onClose"
  >
    <!--  添加描述弹框  -->
    <a-modal
      :visible="addOnVisible"
      :zIndex="1001"
      title="追加问题描述"
      @cancel="handleCancelAddOn"
      @ok="handleAddOn"
    >
      <a-form-model-item label="描述">
        <a-input v-model="desc" type="textarea" />
      </a-form-model-item>
      <div class="clearfix">
        <a-upload
          :before-upload="beforeUpload"
          :file-list="fileList"
          :remove="remove"
          action="/api/af-oa/file/upload"
          list-type="picture-card"
          name="avatar"
          @change="handleChange"
          @preview="handlePreview"
        >
          <div v-if="fileList.length < 5">
            <a-icon type="plus" />
            <div class="ant-upload-text">点击上传</div>
          </div>
        </a-upload>
        <a-modal
          :footer="null"
          :visible="previewVisible"
          @cancel="handleCancel"
        >
          <img :src="previewImage" alt="图片上传" style="width: 100%"/>
        </a-modal>
      </div>
    </a-modal>
    <a-card :bordered="false" class="result-success">
      <result :description="getDescription()" :is-success="icon" :title="getTitle()">
        <template slot="action">
          <a-space v-show="btnGroup">
            <!--<a-tooltip placement="topLeft" :title="tip" arrow-point-at-center>-->
            <!--  <a-button type="primary" v-if="UrgentAvailable && details.status === 0 && details.priority === 2" :disabled="urgentAccess" @click="urgent">请求加急处理</a-button>-->
            <!--</a-tooltip>-->
            <a-button type="primary" @click="addOnVisible = true" >追加问题描述</a-button>
            <a-button type="danger" @click="closeBtn" >撤销工单</a-button>
          </a-space>
          <a-button v-show="!btnGroup" type="primary" @click="onClose">返回</a-button>
        </template>
        <a-modal
          :visible="closeVisible"
          :zIndex="1002"
          title="关闭工单"
          @cancel="handleCloseCancel"
          @ok="handleCloseOk"
        >
          <p>是否确认手动关闭工单？</p>
          <p style="color: red">（该操作不可撤销，请谨慎操作！）</p>
        </a-modal>
        <div>
          <div class="project-name">工单处理进度</div>
          <detail-list size="small" style="max-width: 800px; margin-bottom: 8px" :col="2">
            <detail-list-item term="工单编号">{{ serialNumber }}</detail-list-item>
            <detail-list-item term="提交时间">{{ format(details.createdTime, 'yyyy-MM-dd') }}</detail-list-item>
          </detail-list>
          <a-steps :current="step" progressDot>
            <a-step title="工单提交">
              <a-step-item-group slot="description">
                <a-step-item :title="details.uploader" />
                <a-step-item :title="details.createdTime"/>
              </a-step-item-group>
            </a-step>
            <a-step title="工单处理中" >
              <a-step-item-group slot="description">
                <a-step-item v-if="step >= 1" :title="details.name" />
                <a-step-item v-if="step >= 1" :title="details.confirmTime"/>
              </a-step-item-group>
            </a-step>
            <a-step title="工单完成" >
              <a-step-item-group slot="description">
                <a-step-item v-if="step >= 2" :title="details.finishedTime"/>
              </a-step-item-group>
            </a-step>
          </a-steps>
        </div>
      </result>
    </a-card>
  </a-drawer>
</template>

<script>
import Result from '@vue2-client/components/result/Result'
import DetailList from '@vue2-client/components/tool/DetailList'
import AStepItem from '@vue2-client/components/tool/AStepItem'
import { TicketDetailsViewApi, post } from '@vue2-client/services/api'
import { mapState } from 'vuex'
import { formatDate } from '@vue2-client/utils/util'
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

const AStepItemGroup = AStepItem.Group
const DetailListItem = DetailList.Item
export default {
  name: 'SubmitTicketSuccess',
  components: { AStepItemGroup, AStepItem, DetailListItem, DetailList, Result },
  data () {
    return {
      // 页面宽度
      screenWidth: document.documentElement.clientWidth,
      title: '',
      description: '',
      // 工单详情
      details: {
        uploader: '',
        status: '',
        name: '',
        priority: undefined,
        createdTime: '',
        confirmTime: '',
        finishedTime: '',
        createdTimestamp: undefined
      },
      // 控制加急按钮
      urgentAccess: true,
      // 倒计时
      countDown: 0,
      // 控制加急按钮显示
      UrgentAvailable: true,
      // 刷新页面的定时器
      timer: undefined,
      // 取消工单确认框可见性
      closeVisible: false,
      // 控制页面大图标
      icon: true,
      // 控制加急后定时器
      showTelephoneCountDown: 0,
      // 控制预览显示
      previewVisible: false,
      // 图片真实地址
      previewImage: '',
      // 图片列表
      fileList: [],
      // 控制添加描述框显示
      addOnVisible: false,
      // 描述
      desc: '',
      // 等待时间计时器
      waitTimer: undefined,
      // 控制三个按钮显示
      btnGroup: true,
      // 控制工单关闭后标题显示
      titleEnd: 0,
      // 控制显示文字
      descriptionUrgentLevel: 0
    }
  },
  props: {
    serialNumber: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    },
    categoryStr: {
      type: String,
      required: true
    }
  },
  mounted () {
    this.initView()
  },
  methods: {
    initView () {
      this.getTicketDetail()
      this.refresh()
      this.countDown = 0
    },
    // 提交添加描述
    handleAddOn () {
      return post(TicketDetailsViewApi.AddonDescriptionToTicket, {
        description: this.desc,
        fileList: this.fileList,
        serialNumber: this.serialNumber
      })
        .then(res => {
          this.$message.success('提交成功！')
          this.desc = ''
          this.fileList = []
          this.addOnVisible = false
        }, err => {
          console.log(err)
        })
    },
    // 放弃添加
    handleCancelAddOn () {
      return post(TicketDetailsViewApi.removeAllImages, {
        fileList: this.fileList
      })
        .then(res => {
          this.desc = ''
          this.fileList = []
          this.addOnVisible = false
        }, err => {
          console.log(err)
        })
    },
    // 图像修改检测
    handleChange ({ fileList }) {
      this.fileList = fileList.filter((item) => {
        return item.status === 'done' || item.status === 'uploading'
      })
    },
    // 在上传页面，点击图片上的垃圾桶，撤销上传
    remove (file) {
      return post(TicketDetailsViewApi.revocationImage, {
        file: file
      })
        .then(res => {
          if (res.data === 'success') {
            this.$message.success('删除成功')
          }
          this.fileList = this.fileList.filter((item) => {
            return item.response.name !== file.response.name
          })
        }, err => {
          console.log(err)
        })
    },
    // 上传头像前校验
    beforeUpload (file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      const Lt2M = file.size / 1024 / 1024 < 2
      if (!Lt2M) {
        this.$message.error('图片不得大于2MB!')
      }
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg/png格式的图片')
      }
      return isJpgOrPng && Lt2M
    },
    handleCancel () {
      this.previewVisible = false
    },
    // 处理预览图像
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    // 关闭抽屉时回调
    onClose () {
      this.titleEnd = 0
      this.urgentAccess = true
      clearInterval(this.timer)
      clearInterval(this.waitTimer)
      this.timer = undefined
      this.waitTimer = undefined
      this.btnGroup = true
      this.$emit('update:visible', false)
      this.descriptionUrgentLevel = 0
      this.title = '提交成功'
      this.UrgentAvailable = true
    },
    format (date, format) {
      return formatDate(date, format)
    },
    // 关闭工单确认后操作
    handleCloseOk () {
      return post(TicketDetailsViewApi.manualCloseTicketByCustomer, {
        serialNumber: this.serialNumber,
        time: new Date(),
        categoryStr: this.categoryStr
      })
        .then(res => {
          this.closeVisible = false
          this.details.status = 2
          clearInterval(this.timer)
          clearInterval(this.waitTimer)
          this.timer = undefined
          this.waitTimer = undefined
          this.btnGroup = false
          this.titleEnd = 1
          this.getTicketDetail()
        }, err => {
          console.error(err)
        })
    },
    // 关闭工单取消后业务逻辑
    handleCloseCancel () {
      this.closeVisible = false
    },
    // 关闭工单按钮
    closeBtn () {
      this.closeVisible = true
    },
    // 过10s刷新一下页面数据
    refresh () {
      if (this.timer === undefined) {
        this.timer = setInterval(() => {
          this.getTicketDetail()
        }, 5000)
      }
    },
    // 对工单进行加急处理
    urgent () {
      return post(TicketDetailsViewApi.rushTicket, {
        serialNumber: this.serialNumber,
        categoryStr: this.categoryStr
      })
        .then(res => {
          if (res.data === 1) {
            this.$message.success(
              '已为您自动加急',
              5
            )
            this.details.priority = 1
            this.UrgentAvailable = false
          } else {
            this.$message.error(
              '自动加急失败',
              5
            )
          }
        }, err => {
          console.log(err)
        })
    },
    // 格式化倒计时
    countDownFormat () {
      let mins = Math.floor(this.countDown / 60)
      let secs = this.countDown % 60
      if (mins < 10) {
        mins = '0' + mins
      }
      if (secs < 10) {
        secs = '0' + secs
      }
      return mins + ':' + secs
    },
    // 设置用于控制加急按钮倒计时定时器，加急按钮5分钟后才可点击
    setTimer () {
      this.countDown = this.timePass()
      if (this.waitTimer === undefined) {
        this.waitTimer = setInterval(() => {
          this.countDown++
          if (this.countDown >= 300 && this.details.priority === 2) {
            this.urgent()
            this.details.priority = 1
          }
        }, 1000)
      }
    },
    // 获取显示文字内容
    getDescription () {
      if (this.details.status === 1) {
        // 处理中
        return '工单已被接受，请保持电话畅通。我们的工作人员正在尽快为您解决问题'
      }
      if (this.details.status >= 2) {
        // 已关闭
        return ''
      }
      // 已提交，判断优先级
      if (this.details.priority >= 2) {
        // 低优先级
        // 判断用时
        if (this.timePass() < 300) {
          // 5分钟以内
          return '您创建的工单已成功提交，请保持电话畅通，我们的工作人员将在5分钟内与您联系'
        } else if (this.timePass() >= 300 && this.timePass() <= 600) {
          // 5-10分钟
          return '由于您的工单等待时间过长，系统已为您自动加急工单，请保持电话畅通，感谢您的理解'
        } else {
          // 超过十分钟
          return '很抱歉让您久等，请电询：14709288966'
        }
      } else {
        // 高优先级
        // 判断用时
        if (this.timePass() < 300) {
          // 5分钟以内
          return '您的工单已经被加急处理，我们的工作人员会马上与您取得联系'
        } else if (this.timePass() >= 300 && this.timePass() <= 600) {
          // 5-10分钟
          return '您的工单已经被加急处理，我们的工作人员会马上与您取得联系'
        } else {
          // 超过十分钟
          return '很抱歉让您久等，请电询：14709288966'
        }
      }
    },
    // 获取标题内容
    getTitle () {
      const titleTime = this.countDownFormat()
      if (this.details.status === 1) {
        // 处理中
        return '工单正在处理中'
      }
      if (this.details.status >= 2) {
        // 已关闭
        return '工单已关闭'
      }
      // 已提交，判断优先级
      if (this.details.priority >= 2) {
        // 低优先级
        return '已提交工单' + '\xa0\xa0\xa0\xa0\xa0(\xa0已等待\xa0\xa0' + titleTime + '\xa0)'
      } else {
        // 高优先级
        return '加急成功' + '\xa0\xa0\xa0\xa0\xa0(\xa0已等待\xa0\xa0' + titleTime + '\xa0)'
      }
    },
    // 获取工单创建以来过了多久，单位：秒
    timePass () {
      const now = new Date().getTime()
      let result = Math.floor((now - this.details.createdTimestamp) / 1000)
      if (result < 0) {
        result = 0
      }
      return result
    },
    // 获取工单详情
    getTicketDetail () {
      return post(TicketDetailsViewApi.getTicketDetailsForUploader, {
        serialNumber: this.serialNumber
      })
        .then(res => {
          this.details.uploader = res.uploader
          // 判断负责人有没有值
          if (res.name === undefined) {
            this.details.name = ''
          } else {
            this.details.name = res.name
          }
          // 判断工单被确认时间
          if (res.confirmtime === undefined) {
            this.details.confirmTime = ''
          } else {
            this.details.confirmTime = this.format(res.confirmtime, 'yyyy-MM-dd hh:mm:ss')
          }
          // 判断工单完成时间
          if (res.finishedtime === undefined) {
            this.details.finishedTime = ''
          } else {
            this.details.finishedTime = this.format(res.finishedtime, 'yyyy-MM-dd hh:mm:ss')
          }
          this.details.createdTime = this.format(res.createdtime, 'yyyy-MM-dd hh:mm:ss')
          this.details.status = res.status
          this.details.priority = res.priority
          const dateStr = formatDate(this.details.createdTime)
          this.details.createdTimestamp = new Date(dateStr).getTime()
          const timepass = this.timePass()
          // 如果当前状态为一般，设置定时器，五分钟后允许加急
          if (this.countDown === 0 && this.details.status === 0) {
            this.setTimer()
          }
          if (timepass > 300) {
            this.urgentAccess = false
          }
          if (this.details.status >= 2) {
            this.btnGroup = false
          }
          if (this.details.priority <= 1 && this.details.status === 0) {
            this.descriptionUrgentLevel = 2
          }
        }, err => {
          console.log(err)
        })
    }
  },
  computed: {
    ...mapState('account', { currUser: 'user' }),
    ...mapState('setting', ['isMobile']),
    // 用于进度条，进度显示控制
    step () {
      if (this.details.status !== 0 && this.details.status !== 1) {
        return 2
      } else {
        return this.details.status
      }
    }
  },
  watch: {
    'visible' (val) {
      if (val) {
        this.initView()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.result-success{
  .action:not(:first-child){
    margin-left: 8px;
  }
  .project-name{
    font-size: 16px;
    color: @title-color;
    font-weight: 500;
    margin-bottom: 20px;
  }
}
</style>
