<template>
  <!-- 设计理念：清晰的信息层次，突出工单状态和操作流程 -->
  <div class="ticket-success-wrapper">
    <!-- 关闭工单确认弹窗 -->
    <a-modal :visible="closeVisible" :zIndex="1002" title="关闭工单" @cancel="handleCloseCancel" @ok="handleCloseOk">
      <a-alert message="确认关闭工单？" description="该操作不可撤销，请谨慎操作！" type="warning" show-icon />
    </a-modal>

    <!-- 成功状态展示 -->
    <div class="result-section">
      <result :description="description" :is-success="icon" :title="title">
        <template slot="action">
          <span v-if="countDown > 0" class="countdown-text">{{ countDown }}</span>
        </template>
      </result>
    </div>

    <!-- 工单进度卡片 -->
    <a-card :bordered="false" class="progress-card">
      <div class="card-header">
        <a-icon type="clock-circle" class="header-icon" />
        <span class="header-title">工单处理进度</span>
      </div>

      <!-- 工单基本信息 -->
      <div class="ticket-info">
        <a-row :gutter="24">
          <a-col :span="8">
            <div class="info-item">
              <span class="info-label">工单编号</span>
              <span class="info-value">{{ serialNumber }}</span>
            </div>
          </a-col>
          <a-col :span="8" v-if="details.name">
            <div class="info-item">
              <span class="info-label">负责人</span>
              <span class="info-value">{{ details.name }}</span>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="info-item">
              <span class="info-label">提交时间</span>
              <span class="info-value">{{ details.createdTime }}</span>
            </div>
          </a-col>
        </a-row>
      </div>

      <!-- 进度条 -->
      <div class="progress-steps">
        <a-steps :current="step" progress-dot>
          <a-step title="工单提交">
            <div slot="description" class="step-desc">
              <div class="step-info">
                <a-icon type="user" />
                <span>{{ details.uploader }}</span>
              </div>
              <div class="step-time">{{ details.createdTime }}</div>
            </div>
          </a-step>

          <a-step title="工单处理中">
            <div slot="description" class="step-desc" v-if="step >= 1">
              <div class="step-info">
                <a-icon type="solution" />
                <span>{{ details.phone ? `${details.name} (${details.phone})` : details.name }}</span>
              </div>
              <div class="step-time">{{ details.confirmTime }}</div>
            </div>
          </a-step>

          <a-step title="工单待确认">
            <div slot="description" class="step-desc" v-if="step >= 2">
              <div class="step-info">
                <a-tag color="blue">是否完成: {{ verifyDetails.sfwc }}</a-tag>
                <a-tag color="green">售后评价: {{ verifyDetails.shpj }}</a-tag>
              </div>
              <div class="step-feedback" v-if="verifyDetails.fkyj">反馈意见: {{ verifyDetails.fkyj }}</div>
            </div>
          </a-step>

          <a-step title="工单完成">
            <div slot="description" class="step-desc" v-if="step >= 3">
              <div class="step-time">{{ details.finishedTime }}</div>
            </div>
          </a-step>
        </a-steps>
      </div>
    </a-card>

    <!-- 工单详情卡片 -->
    <a-card :bordered="false" class="detail-card">
      <a-tabs :default-active-key="tabActiveKey" size="large">
        <!-- 工单问题标签页 -->
        <a-tab-pane key="1">
          <span slot="tab">
            <a-icon type="file-text" />
            工单问题
          </span>

          <div class="detail-content">
            <!-- 问题描述 -->
            <div class="detail-item">
              <div class="detail-label">
                <a-icon type="edit" />
                <span>问题描述</span>
              </div>
              <div class="detail-value">{{ details.description }}</div>
            </div>

            <!-- 问题截图 -->
            <div class="detail-item">
              <div class="detail-label">
                <a-icon type="picture" />
                <span>问题截图</span>
              </div>
              <div class="detail-value">
                <image-item :images="details.images" :width="120" @preview="handleFilePreview" />
              </div>
            </div>

            <!-- 附件 -->
            <div class="detail-item" v-if="details.files.length">
              <div class="detail-label">
                <a-icon type="paper-clip" />
                <span>附件</span>
              </div>
              <div class="detail-value">
                <file-item :files="details.files" :downloadable="false" @preview="handleFilePreview" />
              </div>
            </div>

            <!-- 处理结果 -->
            <div class="detail-item" v-if="details.resultrecord">
              <div class="detail-label">
                <a-icon type="check-circle" />
                <span>处理结果</span>
              </div>
              <div class="detail-value result-text">{{ details.resultrecord }}</div>
            </div>
          </div>
        </a-tab-pane>

        <!-- 工单确认标签页 -->
        <a-tab-pane key="2" :disabled="details.status !== 4">
          <span slot="tab">
            <a-icon type="audit" />
            工单确认
          </span>

          <div class="confirm-content">
            <a-alert
              message="请确认工单处理结果"
              description="如果问题已解决，请提交确认；如果问题未解决，请选择退回并说明原因。"
              type="info"
              show-icon
              style="margin-bottom: 24px"
            />

            <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
              <!-- 是否完成 -->
              <a-form-item label="是否完成">
                <a-select placeholder="请选择" v-model="customerSure.sfwc" size="large">
                  <a-select-option value="是">
                    <a-icon type="check-circle" style="color: #52c41a" />
                    是
                  </a-select-option>
                  <a-select-option value="否">
                    <a-icon type="close-circle" style="color: #ff4d4f" />
                    否
                  </a-select-option>
                </a-select>
              </a-form-item>

              <!-- 退回截图 -->
              <a-form-item label="退回截图" v-show="customerSure.sfwc === '否'">
                <div class="upload-wrapper">
                  <upload v-if="uploadVisible" :model="imageUploadModel" @setFiles="setImages" />
                  <a-modal :footer="null" :visible="previewVisible" @cancel="handleCancel">
                    <img :src="previewImage" alt="图片预览" style="width: 100%" />
                  </a-modal>
                </div>
              </a-form-item>

              <!-- 退回原因 -->
              <a-form-item label="退回原因" v-show="customerSure.sfwc === '否'">
                <a-textarea
                  placeholder="请详细说明退回原因，以便我们更好地为您服务"
                  v-model="customerSure.thyy"
                  :rows="4"
                  :maxLength="300"
                  show-count
                />
              </a-form-item>

              <!-- 售后评价 -->
              <a-form-item label="售后评价" v-show="customerSure.sfwc === '是'">
                <a-select placeholder="请选择" v-model="customerSure.shpj" size="large">
                  <a-select-option value="满意">
                    <a-icon type="smile" style="color: #52c41a" />
                    满意
                  </a-select-option>
                  <a-select-option value="不满意">
                    <a-icon type="frown" style="color: #faad14" />
                    不满意
                  </a-select-option>
                </a-select>
              </a-form-item>

              <!-- 反馈意见 -->
              <a-form-item label="反馈意见" v-show="customerSure.sfwc === '是'">
                <a-textarea
                  placeholder="请输入您的反馈意见（选填）"
                  v-model="customerSure.fkyj"
                  :rows="4"
                  :maxLength="300"
                  show-count
                />
              </a-form-item>

              <!-- 操作按钮 -->
              <a-form-item :wrapper-col="{ span: 18, offset: 4 }">
                <a-space size="middle">
                  <a-button type="danger" size="large" @click="rollBack" :disabled="customerSure.sfwc === '是'">
                    <a-icon type="rollback" />
                    退回工单
                  </a-button>
                  <a-button type="primary" size="large" @click="submit" :disabled="customerSure.sfwc === '否'">
                    <a-icon type="check" />
                    确认完成
                  </a-button>
                </a-space>
              </a-form-item>
            </a-form>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 文件预览弹窗 -->
    <a-modal v-model="filePreviewVisible" :footer="null" :dialog-style="{ top: '30px' }" width="80%" :z-index="1001">
      <file-preview :path="filePath" />
    </a-modal>
  </div>
</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 { formatDate } from '@vue2-client/utils/util'
import { FileItem, ImageItem } from '@vue2-client/components/FileImageItem'
import FilePreview from '@vue2-client/components/FilePreview'
import Upload from '@vue2-client/base-client/components/common/Upload'

const AStepItemGroup = AStepItem.Group
const DetailListItem = DetailList.Item
const fileUploadModel = JSON.parse(
  '{"addOrEdit":"all","resUploadStock":1,"pathKey":"cs","rule":{"type":"string","required":"false"},"isOnlyAddOrEdit":true,"acceptCount":3,"type":"file","accept":["*"],"stockAlias":"webmeter","fileRootPath":"D:\\\\nginx-resource\\\\resource\\\\","name":"附件","resUploadMode":"server","model":"FilesId"}'
)
const imageUploadModel = JSON.parse(
  '{"addOrEdit":"all","resUploadStock":1,"pathKey":"cs","rule":{"type":"string","required":"false"},"isOnlyAddOrEdit":true,"acceptCount":5,"type":"image","accept":[".jpg,.jpeg,.ico,.gif,svg,.webp,.png,.bmp,.pjpeg,"],"stockAlias":"webmeter","fileRootPath":"D:\\\\nginx-resource\\\\resource\\\\","name":"图片","resUploadMode":"server","model":"Images"}'
)

export default {
  name: 'SubmitTicketSuccess',
  components: {
    AStepItemGroup,
    AStepItem,
    DetailListItem,
    DetailList,
    Result,
    FileItem,
    ImageItem,
    FilePreview,
    Upload
  },
  props: {
    serialNumber: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      fileUploadModel,
      imageUploadModel,
      title: '提交成功',
      description: '您创建的工单已成功提交，请保持电话畅通，我们的工作人员将尽快与您取得联系。',
      details: {
        uploader: '',
        status: 0,
        name: '',
        phone: '',
        createdTime: '',
        confirmTime: '',
        finishedTime: '',
        description: '',
        resultrecord: '',
        files: [],
        images: []
      },
      urgentAccess: true,
      countDown: 0,
      UrgentAvailable: true,
      closeVisible: false,
      icon: true,
      filePreviewVisible: false,
      filePath: '',
      tabActiveKey: '1',
      customerSure: {
        shpj: '满意',
        fkyj: undefined,
        sfwc: '是',
        thyy: ''
      },
      applyId: 0,
      stepId: 0,
      verifyDetails: {
        shpj: '',
        sfwc: '',
        fkyj: ''
      },
      uploadVisible: true,
      previewVisible: false,
      previewImage: '',
      imageList: []
    }
  },
  mounted() {
    this.getTicketDetail()
  },
  computed: {
    step() {
      switch (this.details.status) {
        case 0:
          return 0
        case 1:
          return 1
        case 2:
          return 2
        case 3:
          return 3
        case 4:
          return 2
        default:
          return 0
      }
    }
  },
  methods: {
    format(date, format) {
      return formatDate(date, format)
    },
    handleCloseOk() {
      return post(TicketDetailsViewApi.manualCloseTicketByCustomer, {
        serialNumber: this.serialNumber,
        time: new Date()
      }).then(
        res => {
          this.closeVisible = false
          this.title = '工单已关闭'
          this.description = ''
          this.icon = false
        },
        err => {
          console.error(err)
        }
      )
    },
    handleCloseCancel() {
      this.closeVisible = false
    },
    closeBtn() {
      this.closeVisible = true
    },
    urgent() {
      return post(TicketDetailsViewApi.rushTicket, {
        serialNumber: this.serialNumber
      }).then(
        res => {
          if (res.data === 1) {
            this.$message.success('操作成功', 5)
            this.description = '您的工单已经被加急处理，我们的工作人员会优先处理您的请求。'
            this.UrgentAvailable = false
          } else {
            this.$message.error('操作失败', 5)
          }
        },
        err => {
          console.log(err)
        }
      )
    },
    getTicketDetail() {
      return post(TicketDetailsViewApi.getTicketDetailsForUploader, {
        serialNumber: this.serialNumber
      }).then(
        res => {
          this.stepId = res.stepId
          this.applyId = res.apply_id
          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.phone = res.phone
          this.details.description = res.description
          this.details.files = res.files
          this.details.images = res.images
          this.details.resultrecord = res.resultrecord
          if (res.status === 3) {
            post(TicketDetailsViewApi.getApplyCompletedStepData, {
              applyId: this.applyId,
              stepId: this.stepId
            }).then(res => {
              if (res.data) {
                this.verifyDetails.fkyj = res.data.fkyj ? res.data.fkyj : '无'
                this.verifyDetails.shpj = res.data.shpj ? res.data.shpj : '满意'
                this.verifyDetails.sfwc = res.data.sfwc ? res.data.sfwc : '是'
              }
            })
          }
        },
        err => {
          console.log(err)
        }
      )
    },
    handleFilePreview(path) {
      this.filePath = path
      this.filePreviewVisible = true
    },
    submit() {
      return post(TicketDetailsViewApi.afterApplyFinalStepSubmit, {
        applyId: this.applyId
      }).then(
        res => {
          this.onSubmit()
          this.saveWorkflowLog('确认完工', '最后一步: 客户确认', { notes: '' })
          this.$message.success('已完工！')
          post(TicketDetailsViewApi.clientSubmit, {
            status: 3,
            serial_number: this.serialNumber
          }).then(res => {
            console.log('res', res)
          })
          this.getTicketDetail()
          this.$emit('afterSubmit')
        },
        err => {
          this.$message.error('提交失败！')
          console.log(err)
        }
      )
    },
    rollBack() {
      if (this.customerSure.thyy === '') {
        this.$message.warn('请填写退回原因')
        return
      }
      const notes = this.customerSure.thyy
      return post(TicketDetailsViewApi.updateApplySubState, {
        stepId: this.stepId - 1,
        applyId: this.applyId
      }).then(
        res => {
          this.saveWorkflowLog('退回', `第${this.stepId}步: 客户确认 ---> 第${this.stepId - 1}步: 售后确认`, { notes })
          this.$message.success('退回成功')
          post(TicketDetailsViewApi.clientSubmit, {
            status: 1,
            serial_number: this.serialNumber,
            Images: this.imageList,
            applyId: this.applyId
          }).then(res => {
            console.log('res', res)
          })
          this.uploadVisible = false
          this.getTicketDetail()
          this.$emit('afterSubmit')
        },
        err => {
          this.$message.error('退回失败！')
          console.log(err)
        }
      )
    },
    saveWorkflowLog(operation, desc, extra) {
      post(TicketDetailsViewApi.saveApplyWorkflowLog, {
        applyId: this.applyId,
        operation,
        desc,
        operator: '客户确认',
        notes: '客户确认',
        setHandler: '客户确认',
        setDeadline: '',
        ...extra
      })
    },
    onSubmit() {
      const time = this.format(new Date(), 'yyyy-MM-dd hh:mm:ss')
      const form = {
        shpj: this.customerSure.shpj,
        fkyj: this.customerSure.fkyj,
        sfwc: this.customerSure.sfwc
      }
      return post(TicketDetailsViewApi.saveApplyStepFormData, {
        applyId: this.applyId,
        stepId: this.stepId,
        form: form,
        data: time,
        handler: '客户确认',
        note: ''
      }).then(
        res => {
          console.log('表单提交成功')
          this.note = ''
          this.showForm = false
          this.stepDone = true
        },
        err => {
          this.$message.error('保存失败，请检查后重试')
          console.log(err)
        }
      )
    },
    handleCancel() {
      this.previewVisible = false
    },
    setImages(imageIds) {
      this.imageList = imageIds
    }
  }
}
</script>

<style scoped lang="less">
/* 设计理念：清晰的卡片布局，突出关键信息，优化阅读体验 */

.ticket-success-wrapper {
  padding: 24px 0;
}

/* 成功状态区域 */
.result-section {
  margin-bottom: 24px;

  .countdown-text {
    font-size: 16px;
    color: #1890ff;
    font-weight: 500;
  }
}

/* 进度卡片 */
.progress-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 2px solid #f0f0f0;

    .header-icon {
      font-size: 20px;
      color: #1890ff;
      margin-right: 12px;
    }

    .header-title {
      font-size: 18px;
      font-weight: 600;
      color: #262626;
    }
  }
}

/* 工单信息 */
.ticket-info {
  background: #fafafa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 32px;

  .info-item {
    display: flex;
    flex-direction: column;

    .info-label {
      font-size: 13px;
      color: #8c8c8c;
      margin-bottom: 8px;
    }

    .info-value {
      font-size: 15px;
      color: #262626;
      font-weight: 500;
    }
  }
}

/* 进度步骤 */
.progress-steps {
  padding: 0 24px;

  :deep(.ant-steps-item-title) {
    font-size: 15px;
    font-weight: 600;
  }

  :deep(.ant-steps-item-content) {
    width: 160px;
  }

  .step-desc {
    margin-top: 8px;
    text-align: left;

    .step-info {
      display: flex;
      align-items: center;
      margin-bottom: 4px;
      color: #595959;

      .anticon {
        margin-right: 6px;
        color: #1890ff;
      }
    }

    .step-time {
      font-size: 13px;
      color: #8c8c8c;
    }

    .step-feedback {
      margin-top: 8px;
      padding: 8px 12px;
      background: #f6ffed;
      border-left: 3px solid #52c41a;
      font-size: 13px;
      color: #595959;
    }
  }
}

/* 详情卡片 */
.detail-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  /deep/ .ant-tabs-nav {
    margin-bottom: 24px;
  }
}

/* 详情内容 */
.detail-content {
  .detail-item {
    margin-bottom: 32px;

    &:last-child {
      margin-bottom: 0;
    }

    .detail-label {
      display: flex;
      align-items: center;
      font-size: 15px;
      font-weight: 600;
      color: #262626;
      margin-bottom: 12px;

      .anticon {
        margin-right: 8px;
        color: #1890ff;
        font-size: 16px;
      }
    }

    .detail-value {
      padding-left: 24px;
      font-size: 14px;
      color: #595959;
      line-height: 1.8;

      &.result-text {
        padding: 16px;
        background: #e6f7ff;
        border-left: 3px solid #1890ff;
        border-radius: 4px;
      }
    }
  }
}

/* 确认内容 */
.confirm-content {
  padding: 24px;
  background: #fafafa;
  border-radius: 6px;

  /deep/ .ant-form-item-label > label {
    font-weight: 600;
  }
}

.upload-wrapper {
  /deep/ .ant-upload-list-picture-card-container {
    margin: 0 8px 8px 0;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .ticket-info {
    .info-item {
      margin-bottom: 16px;
    }
  }

  .progress-steps {
    padding: 0 12px;
  }

  .detail-content {
    .detail-item {
      .detail-value {
        padding-left: 0;
      }
    }
  }

  .confirm-content {
    padding: 16px;
  }
}
</style>
