<template>
  <!-- 设计理念：采用更现代化的布局，增加视觉层次感，优化信息密度 -->
  <div class="ticket-system-wrapper">
    <!-- 工单详情弹窗 - 使用更大的宽度以展示完整信息 -->
    <a-modal
      v-model="successVisible"
      :footer="null"
      destroy-on-close
      title="工单详情"
      width="90%"
      :body-style="{ padding: '24px' }"
      @cancel="onSuccessCancel">
      <submit-ticket-success v-if="serialNumber" :serialNumber="serialNumber" @afterSubmit="afterSubmit"/>
    </a-modal>

    <!-- 向日葵使用手册弹窗 - 优化内容排版 -->
    <a-modal
      :visible="sunClientManualVisible"
      title="向日葵远程协助使用指南"
      width="1000px"
      :body-style="{ padding: '32px' }"
      @cancel="sunClientManualVisible = false"
      @ok="sunClientManualVisible = false">
      <div class="manual-content">
        <a-steps direction="vertical" :current="-1">
          <a-step title="安装软件">
            <div slot="description" class="manual-step">
              <img alt="安装向日葵" src="@vue2-client/assets/img/SunClientManual/1.png" class="manual-image">
              <p class="manual-text">运行下载好的安装包，按需要手动选择安装路径后，一路点下一步完成安装</p>
            </div>
          </a-step>
          <a-step title="运行软件">
            <div slot="description" class="manual-step">
              <p class="manual-text">在桌面或开始菜单中打开向日葵软件</p>
              <img alt="运行向日葵" src="@vue2-client/assets/img/SunClientManual/2.png" class="manual-image">
              <p class="manual-text">显示此页面时，您已成功运行向日葵</p>
            </div>
          </a-step>
          <a-step title="截图并提交">
            <div slot="description" class="manual-step">
              <p class="manual-text">点击软件界面中眼睛样子的按钮，使验证码正常显示</p>
              <img alt="显示验证码" src="@vue2-client/assets/img/SunClientManual/3.png" class="manual-image">
              <p class="manual-text">使用 QQ、微信或任何截图软件，截取屏幕中"本机识别码"和"本机验证码"，确保该值清晰可辨别</p>
              <img alt="截图示例" src="@vue2-client/assets/img/SunClientManual/4.png" class="manual-image">
              <p class="manual-text">将您截好的图片，通过表单提交页面下方"+"（加号）按钮提交给我们，这样我们的工作人员就可以远程协助您排查、解决问题</p>
            </div>
          </a-step>
        </a-steps>
      </div>
    </a-modal>

    <!-- ToDesk使用手册弹窗 - 优化内容排版 -->
    <a-modal
      :visible="toDeskManualVisible"
      title="ToDesk远程协助使用指南"
      width="1000px"
      :body-style="{ padding: '32px' }"
      @cancel="toDeskManualVisible = false"
      @ok="toDeskManualVisible = false">
      <div class="manual-content">
        <a-steps direction="vertical" :current="-1">
          <a-step title="安装软件">
            <div slot="description" class="manual-step">
              <img alt="安装ToDesk" src="@vue2-client/assets/img/ToDeskManual/1.png" class="manual-image">
              <p class="manual-text">运行下载好的安装包，按需要手动选择安装路径后，一路点下一步完成安装</p>
            </div>
          </a-step>
          <a-step title="运行软件">
            <div slot="description" class="manual-step">
              <p class="manual-text">在桌面或开始菜单中打开 ToDesk 软件</p>
              <img alt="运行ToDesk" src="@vue2-client/assets/img/ToDeskManual/2.png" class="manual-image">
              <p class="manual-text">显示此页面时，您已成功运行 ToDesk</p>
            </div>
          </a-step>
          <a-step title="截图并提交">
            <div slot="description" class="manual-step">
              <p class="manual-text">点击软件界面中眼睛样子的按钮，使临时密码正常显示</p>
              <img alt="显示密码" src="@vue2-client/assets/img/ToDeskManual/3.png" class="manual-image">
              <p class="manual-text">使用 QQ、微信或任何截图软件，截取屏幕中"设备代码"和"临时密码"，确保该值清晰可辨别</p>
              <img alt="截图示例" src="@vue2-client/assets/img/ToDeskManual/4.png" class="manual-image">
              <p class="manual-text">将您截好的图片，通过表单提交页面下方"+"（加号）按钮提交给我们，这样我们的工作人员就可以远程协助您排查、解决问题</p>
            </div>
          </a-step>
        </a-steps>
      </div>
    </a-modal>

    <!-- 联系方式填写弹窗 -->
    <a-modal
      :visible="infoFormVisible"
      title="查询历史工单"
      :body-style="{ padding: '24px' }"
      @cancel="infoFormVisible = false"
      @ok="onInfoFormSubmit">
      <a-alert
        message="提示：请输入提交工单时填写的联系方式"
        type="info"
        show-icon
        style="margin-bottom: 16px" />
      <a-form-model
        ref="infoFormRef"
        :label-col="{ span: 6 }"
        :model="infoForm"
        :wrapper-col="{ span: 16 }">
        <a-form-model-item
          :rules="{ required: true, message: '请输入联系方式' }"
          label="联系方式"
          prop="phone">
          <a-input
            v-model="infoForm.phone"
            placeholder="请输入手机号或固定电话"
            size="large" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <div class="page-content">
      <a-card :bordered="false" class="main-card" :body-style="{ padding: '0 24px' }">
        <a-tabs :activeKey="tabActiveKey" size="large" @change="changeTab">
          <!-- 工单提交标签页 -->
          <a-tab-pane key="workSubmit">
            <span slot="tab">
              <a-icon type="form" />
              工单提交
            </span>
            <a-row v-if="tabActiveKey === 'workSubmit'" :gutter="24" class="submit-content">
              <!-- 左侧表单区域 - 使用更宽的布局 -->
              <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
                <a-card title="问题信息" :bordered="false" class="form-card">
                  <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                    <!-- 公司名称 -->
                    <a-form-item v-if="!currUser.orgName" label="公司名称" :validate-status="showCustomerNameAlert ? 'error' : ''">
                      <a-input
                        v-model="form.name"
                        placeholder="请输入公司名称"
                        size="large" />
                      <div v-show="showCustomerNameAlert" class="error-tip">
                        <a-icon type="exclamation-circle" /> 公司名称不能为空
                      </div>
                    </a-form-item>

                    <!-- 联系人 -->
                    <a-form-item label="联系人" :validate-status="showContactAlert ? 'error' : ''">
                      <a-input
                        v-model="form.contact"
                        placeholder="请输入联系人姓名"
                        size="large" />
                      <div v-show="showContactAlert" class="error-tip">
                        <a-icon type="exclamation-circle" /> 请填写联系人
                      </div>
                    </a-form-item>

                    <!-- 联系方式 -->
                    <a-form-item label="联系方式" :validate-status="showPhoneAlert ? 'error' : ''">
                      <a-input
                        v-model="form.phone"
                        placeholder="请输入手机号或固定电话"
                        size="large" />
                      <div v-show="showPhoneAlert" class="error-tip">
                        <a-icon type="exclamation-circle" /> 请填写联系方式
                      </div>
                    </a-form-item>

                    <!-- 问题描述 -->
                    <a-form-item label="问题描述" :validate-status="showDescAlert ? 'error' : ''">
                      <a-textarea
                        v-model="form.desc"
                        allow-clear
                        placeholder="请详细描述您遇到的问题，必要时请注明客户编号、表号、系统功能项等信息"
                        :rows="5"
                        :maxLength="300"
                        show-count />
                      <div v-show="showDescAlert" class="error-tip">
                        <a-icon type="exclamation-circle" /> 问题描述不能为空
                      </div>
                    </a-form-item>

                    <!-- 问题截图 -->
                    <a-form-item label="问题截图" :validate-status="!imageList.length ? 'error' : ''">
                      <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>
                      <div v-show="!imageList.length" class="error-tip">
                        <a-icon type="exclamation-circle" /> 请上传问题截图
                      </div>
                      <div class="upload-tip">
                        <a-icon type="info-circle" /> 支持 JPG、PNG 等格式，最多上传 5 张
                      </div>
                    </a-form-item>

                    <!-- 附件上传 -->
                    <a-form-item label="附件">
                      <div class="upload-wrapper">
                        <upload v-if="uploadVisible" :model="fileUploadModel" @setFiles="setFiles" />
                      </div>
                      <div class="upload-tip">
                        <a-icon type="info-circle" /> 可选，最多上传 3 个文件
                      </div>
                    </a-form-item>

                    <!-- 提交按钮 -->
                    <a-form-item :wrapper-col="{ span: 16, offset: 6 }">
                      <a-button
                        type="primary"
                        size="large"
                        :loading="submitLoading"
                        :disabled="showPhoneAlert || showCustomerNameAlert || showContactAlert || showDescAlert || !imageList.length"
                        @click="onSubmit">
                        <a-icon type="check-circle" />
                        提交工单
                      </a-button>
                    </a-form-item>
                  </a-form>
                </a-card>
              </a-col>

              <!-- 右侧远程工具下载区域 -->
              <a-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
                <a-card title="远程协助工具" :bordered="false" class="tools-card">
                  <a-alert
                    message="如需远程协助，请下载以下任一工具"
                    type="warning"
                    show-icon
                    style="margin-bottom: 20px" />

                  <div class="tool-item">
                    <div class="tool-icon" @click="toSunClientClick">
                      <img alt="向日葵" src="@vue2-client/assets/img/SunClientDownload.png">
                    </div>
                    <div class="tool-info">
                      <h4>向日葵远程控制</h4>
                      <p>稳定可靠的远程协助工具</p>
                      <a-button type="link" size="small" @click="sunClientManualVisible = true">
                        <a-icon type="question-circle" /> 使用说明
                      </a-button>
                    </div>
                  </div>

                  <a-divider />

                  <div class="tool-item">
                    <div class="tool-icon" @click="toDeskClick">
                      <img alt="ToDesk" src="@vue2-client/assets/img/ToDeskDownload.png">
                    </div>
                    <div class="tool-info">
                      <h4>ToDesk 远程控制</h4>
                      <p>快速便捷的远程协助工具</p>
                      <a-button type="link" size="small" @click="toDeskManualVisible = true">
                        <a-icon type="question-circle" /> 使用说明
                      </a-button>
                    </div>
                  </div>
                </a-card>
              </a-col>
            </a-row>
          </a-tab-pane>

          <!-- 历史工单标签页 -->
          <a-tab-pane key="workHistory">
            <span slot="tab">
              <a-icon type="history" />
              历史工单
            </span>
            <x-form-table
              ref="searchTable"
              v-if="tabActiveKey === 'workHistory'"
              :fixed-query-form="fixedQueryForm"
              serviceName="af-oa-ticket"
              :queryParamsName="queryParamsName"
              title="已提交工单"
              @action="toDetail">
              <a-button slot="button" v-if="!currUser.orgName" type="primary" @click="infoFormVisible = true">
                <a-icon type="search" />
                填写联系方式
              </a-button>
            </x-form-table>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>
  </div>
</template>

<script>
import { TicketDetailsViewApi, post } from '@vue2-client/services/api'
import XFormTable from '@vue2-client/base-client/components/common/XFormTable/XFormTable'
import submitTicketSuccess from './submitTicketSuccess'
import Upload from '@vue2-client/base-client/components/common/Upload'

export default {
  name: 'SubmitTicket',
  components: {
    XFormTable,
    submitTicketSuccess,
    Upload
  },
  data () {
    return {
      queryParamsName: 'TicketQueryForCustomer',
      successVisible: false,
      previewVisible: false,
      previewImage: '',
      imageList: [],
      fileList: [],
      form: {
        name: '',
        desc: undefined,
        contact: '',
        phone: ''
      },
      serialNumber: '',
      showContactAlert: true,
      showPhoneAlert: true,
      showDescAlert: true,
      showCustomerNameAlert: true,
      sunClientManualVisible: false,
      toDeskManualVisible: false,
      fixedQueryForm: {},
      currUser: {
        orgName: '',
        contact: '',
        phone: ''
      },
      tabActiveKey: 'workSubmit',
      imageUploadModel,
      fileUploadModel,
      infoFormVisible: false,
      infoForm: {
        phone: ''
      },
      uploadVisible: true,
      submitLoading: false
    }
  },
  created () {
    document.title = '系统问题反馈'
    this.currUser.orgName = this.$route.query.orgName
    this.currUser.contact = this.$route.query.contact
    this.currUser.phone = this.$route.query.phone
    this.form.name = this.$route.query.orgName
    this.form.contact = this.$route.query.contact
    this.form.phone = this.$route.query.phone
    this.fixedQueryForm.t_uploader = this.currUser.orgName
  },
  methods: {
    toDetail (record, id) {
      this.serialNumber = id + ''
      this.successVisible = true
    },
    getBase64 (file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
      })
    },
    setImages (imageIds) {
      this.imageList = imageIds
    },
    setFiles (fileIds) {
      this.fileList = fileIds
    },
    handleCancel () {
      this.previewVisible = false
    },
    onSubmit () {
      this.submitLoading = true
      const form = {
        customerName: this.form.name,
        contact: this.form.contact,
        phone: this.form.phone,
        problemDetail: this.form.desc,
        Images: this.imageList,
        FilesId: this.fileList
      }
      if (form.problemDetail.length > 300) {
        this.$message.error('问题详情长度超出限制')
        return
      }
      if (form.problemDetail.indexOf('\'') !== -1) {
        this.$message.error('问题详情不能包含特殊符号')
        return
      }
      post(TicketDetailsViewApi.createTicket, { form }).then((res) => {
        this.serialNumber = res.value
        this.successVisible = true
        this.$message.success('创建成功')
        this.form.desc = ''
        this.imageList = []
        this.fileList = []
        this.uploadVisible = false
        if (!this.currUser.orgName) {
          this.fixedQueryForm.t_uploader_phone = form.phone
          this.infoForm.phone = form.phone
        }
      }).finally(res => {
        this.submitLoading = false
      })
    },
    onSuccessCancel () {
      this.uploadVisible = true
    },
    toSunClientClick () {
      window.open('https://sunlogin.oray.com/download')
    },
    toDeskClick () {
      window.open('https://www.todesk.com/download.html')
    },
    changeTab (id) {
      if (id === 'workHistory' && !this.fixedQueryForm.t_uploader && !this.fixedQueryForm.t_uploader_phone) {
        this.infoFormVisible = true
        return
      }
      this.tabActiveKey = id
    },
    onInfoFormSubmit () {
      this.$refs.infoFormRef.validate(valid => {
        if (valid) {
          this.fixedQueryForm = {
            t_uploader_phone: this.infoForm.phone
          }
          this.tabActiveKey = 'workHistory'
          this.infoFormVisible = false
        }
      })
    },
    afterSubmit () {
      this.$refs.searchTable.refreshTable()
      this.successVisible = false
    }
  },
  watch: {
    'form.contact' (newVal) {
      this.showContactAlert = !newVal || newVal.trim().length === 0
    },
    'form.phone' (newVal) {
      this.showPhoneAlert = !newVal || newVal.trim().length === 0
    },
    'form.desc' (newVal) {
      this.showDescAlert = newVal.trim().length === 0
    },
    'form.name' (newVal) {
      this.showCustomerNameAlert = !newVal || newVal.trim().length === 0
    }
  }
}
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"}')
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"}')
</script>

<style scoped lang="less">
/* 设计理念：使用现代化的配色方案和间距系统，提升视觉层次 */

:deep(.ant-form-item-control) {
  line-height: 20px;
}

:deep(.ant-form-item) {
  margin-bottom: 12px;
}

.ticket-system-wrapper {
  min-height: 100vh;
  background: #f0f2f5;
}

/* 主内容区域 */
.page-content {
  padding: 24px;
}

.main-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 表单卡片样式 */
.form-card {
  background: #fff;
  border-radius: 8px;

  /deep/ .ant-card-head {
    border-bottom: 2px solid #f0f0f0;
    font-weight: 600;
    font-size: 16px;
  }
}

/* 错误提示样式 - 使用更柔和的红色 */
.error-tip {
  color: #ff4d4f;
  font-size: 13px;
  margin-top: 4px;
  display: flex;
  align-items: center;

  .anticon {
    margin-right: 4px;
  }
}

/* 上传提示样式 */
.upload-tip {
  color: #8c8c8c;
  font-size: 13px;
  margin-top: 8px;
  display: flex;
  align-items: center;

  .anticon {
    margin-right: 4px;
  }
}

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

/* 远程工具卡片 */
.tools-card {
  background: #fff;
  border-radius: 8px;
  position: sticky;
  top: 24px;

  /deep/ .ant-card-head {
    border-bottom: 2px solid #f0f0f0;
    font-weight: 600;
    font-size: 16px;
  }
}

.tool-item {
  display: flex;
  align-items: center;
  padding: 16px 0;

  .tool-icon {
    flex-shrink: 0;
    width: 80px;
    height: 80px;
    cursor: pointer;
    transition: transform 0.3s;

    &:hover {
      transform: scale(1.05);
    }

    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }

  .tool-info {
    flex: 1;
    margin-left: 16px;

    h4 {
      margin: 0 0 4px;
      font-size: 15px;
      font-weight: 600;
      color: #262626;
    }

    p {
      margin: 0 0 8px;
      font-size: 13px;
      color: #8c8c8c;
    }
  }
}

/* 使用手册内容样式 */
.manual-content {
  /deep/ .ant-steps-item-title {
    font-size: 16px;
    font-weight: 600;
  }
}

.manual-step {
  padding: 16px 0;

  .manual-image {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin: 16px 0;
  }

  .manual-text {
    font-size: 14px;
    line-height: 1.8;
    color: #595959;
    margin: 12px 0;
  }
}

/* 响应式调整 */
@media (max-width: 992px) {
  .page-header {
    padding: 24px 16px;

    .header-title {
      font-size: 22px;

      .header-icon {
        font-size: 26px;
      }
    }
  }

  .page-content {
    padding: 0 16px 24px;
  }

  .tools-card {
    position: static;
    margin-top: 24px;
  }
}
</style>
