<template>
  <div class="customer-css">
    <!-- 查询条件 -->
    <el-form :inline="true" label-position="top" class="search-form-inline">
      <div class="search-row">
        <el-form-item label="供应商编码" class="search-item">
          <el-input v-model="searchData.supplierNo" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="供应商名称" class="search-item">
          <el-input v-model="searchData.supplierName" style="width: 200px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="反馈单号" class="search-item">
          <el-input v-model="searchData.issueNo" style="width: 120px" @keyup.enter.native="getMainData"/>
        </el-form-item>
        <el-form-item label="问题日期" class="search-item">
          <el-date-picker
            v-model="searchData.issueDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            style="width: 150px"
            clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" class="search-item">
          <el-select v-model="searchData.statusDb" clearable placeholder="全部" style="width: 100%">
            <el-option label="全部" value="" />
            <el-option label="已确认" value="Confirmed" />
            <el-option label="已分析" value="Analyzed" />
            <el-option label="已关闭" value="Closed" />
            <el-option label="已取消" value="Cancelled" />
          </el-select>
        </el-form-item>

      </div>

      <div class="search-row">
        <el-form-item label=" " class="search-item search-btn-item">
          <el-button type="primary" @click="getMainData" class="customer-bun-min">查询</el-button>
          <el-button type="primary" @click="addQualityIssue" class="customer-bun-min">新增</el-button>
          <el-button type="primary" @click="exportExcel" class="customer-bun-min">导出</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-table
      :height="height"
      :data="mainDataList"
      border
      ref="mainTable"
      highlight-current-row
      @row-click="changeData"
      v-loading="dataListLoading"
      style="margin-top: 0px; width: 100%;">
      <el-table-column
        v-for="(item,index) in columnArray1" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="!item.columnHidden">{{ scope.row[item.columnProp] }}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]"
                                             style="width: 100px; height: 100px"/></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="180" label="操作">
        <template slot-scope="scope">
          <template v-if="scope.row.status !== '已回复'">
            <a class="customer-a" @click="editQualityIssue(scope.row)">编辑 |</a>
            <a class="customer-a" @click="deleteQualityIssue(scope.row)">删除 </a>
            <a class="customer-a" @click="replyQualityIssue(scope.row)">| 回复</a>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件 -->
    <el-pagination style="margin-top: 0px"
                   @size-change="sizeChangeHandle"
                   @current-change="currentChangeHandle"
                   :current-page="pageIndex"
                   :page-sizes="[20, 50, 100, 200, 500]"
                   :page-size="pageSize"
                   :total="totalPage"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 详情页签 -->
    <el-tabs v-model="activeTab" style="margin-top: 0px; width: 99%;" @tab-click="handleTabClick" class="customer-tab" type="border-card">
      <!-- 详情 -->
      <el-tab-pane label="详情" name="detail">
        <quality-issue-detail :detail-data="currentRow" />
      </el-tab-pane>
      <!-- 附件 -->
      <el-tab-pane label="附件" name="attachment">
        <quality-issue-attachment :detail-data="currentRow" :table-height="detailHeight" />
      </el-tab-pane>
    </el-tabs>

    <!-- 新增弹窗 -->
    <el-dialog
      title="质量问题 - 新增"
      :visible.sync="addDialogVisible"
      width="45%"
      top="10vh"
      :close-on-click-modal="false"
      @close="handleCloseAddDialog">

      <el-form :model="addFormData" :rules="addRules" ref="addFormData" label-width="110px" size="mini" class="add-dialog-form">
        <!-- 第一行 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="反馈单号">
              <el-input v-model="addFormData.issueNo" placeholder="自动生成" disabled size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="问题日期" prop="issueDate">
              <el-date-picker
                v-model="addFormData.issueDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                size="mini"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="要求回复日期" prop="requireReplyDate">
              <el-date-picker
                v-model="addFormData.requireReplyDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                size="mini"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="供应商编码" prop="supplierNo">
              <el-input v-model="addFormData.supplierNo" placeholder="请选择" readonly @click.native="selectSupplier" size="mini">
                <i slot="suffix" class="el-icon-search" style="cursor: pointer;"></i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称">
              <el-input v-model="addFormData.supplierName" disabled size="mini"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="问题分类" prop="issueCategory">
              <el-select v-model="addFormData.issueCategory" placeholder="请选择" size="mini" style="width: 100%">
                <el-option label="产品外观" value="产品外观"></el-option>
                <el-option label="产品性能" value="产品性能"></el-option>
                <el-option label="尺寸不符" value="尺寸不符"></el-option>
                <el-option label="材质问题" value="材质问题"></el-option>
                <el-option label="包装破损" value="包装破损"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="问题简述" prop="issueSummary">
              <el-input v-model="addFormData.issueSummary" placeholder="请输入问题简述" size="mini"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="问题详细描述">
              <el-input
                v-model="addFormData.issueDescription"
                type="textarea"
                :rows="4"
                placeholder="请输入问题详细描述"
                size="mini">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveAdd" class="customer-bun-min">保存</el-button>
        <el-button @click="handleCloseAddDialog" class="customer-bun-min">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="质量问题 - 编辑"
      :visible.sync="editDialogVisible"
      width="45%"
      top="10vh"
      :close-on-click-modal="false"
      @close="handleCloseEditDialog">

      <el-form :model="editFormData" :rules="editRules" ref="editFormData" label-width="110px" size="mini" class="add-dialog-form">
        <!-- 第一行 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="反馈单号">
              <el-input v-model="editFormData.issueNo" placeholder="自动生成" disabled size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="问题日期" prop="issueDate">
              <el-date-picker
                v-model="editFormData.issueDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                size="mini"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="要求回复日期" prop="requireReplyDate">
              <el-date-picker
                v-model="editFormData.requireReplyDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                size="mini"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="供应商编码">
              <el-input v-model="editFormData.supplierNo" disabled size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称">
              <el-input v-model="editFormData.supplierName" disabled size="mini"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="问题分类" prop="issueCategory">
              <el-select v-model="editFormData.issueCategory" placeholder="请选择" size="mini" style="width: 100%">
                <el-option label="产品外观" value="产品外观"></el-option>
                <el-option label="产品性能" value="产品性能"></el-option>
                <el-option label="尺寸不符" value="尺寸不符"></el-option>
                <el-option label="材质问题" value="材质问题"></el-option>
                <el-option label="包装破损" value="包装破损"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="问题简述" prop="issueSummary">
              <el-input v-model="editFormData.issueSummary" placeholder="请输入问题简述" size="mini"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="问题详细描述">
              <el-input
                v-model="editFormData.issueDescription"
                type="textarea"
                :rows="4"
                placeholder="请输入问题详细描述"
                size="mini">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveEdit" class="customer-bun-min">保存</el-button>
        <el-button @click="handleCloseEditDialog" class="customer-bun-min">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 回复弹窗 -->
    <el-dialog
      title="质量问题 - 回复"
      :visible.sync="replyDialogVisible"
      width="50%"
      top="10vh"
      :close-on-click-modal="false"
      @close="handleCloseReplyDialog">

      <div class="reply-dialog-info">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="info-label">反馈单号：</span>
              <span class="info-value">{{ replyFormData.issueNo }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="info-label">回复日期：</span>
              <span class="info-value">{{ replyFormData.replyTime }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="info-label">回复人：</span>
              <span class="info-value">{{ replyFormData.replyBy }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-form :model="replyFormData" :rules="replyRules" ref="replyFormData" label-position="top" size="mini" class="reply-dialog-form">
        <!-- 原因分析 -->
        <el-form-item label="原因分析" prop="analysis">
          <el-input
            v-model="replyFormData.analysis"
            type="textarea"
            :rows="4"
            placeholder="请输入原因分析"
            size="mini">
          </el-input>
        </el-form-item>

        <!-- 后续措施 -->
        <el-form-item label="后续措施" prop="correctiveAction">
          <el-input
            v-model="replyFormData.correctiveAction"
            type="textarea"
            :rows="4"
            placeholder="请输入后续措施"
            size="mini">
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveReply" class="customer-bun-min">保存</el-button>
        <el-button @click="handleCloseReplyDialog" class="customer-bun-min">关闭</el-button>
      </div>
    </el-dialog>

    <Chooselist ref="baseList" @getBaseData="getBaseData"></Chooselist>
  </div>
</template>

<script>
import { queryQualityIssuePage, saveQualityIssue,deleteQualityIssue,updateQualityIssue, saveReply } from '@/api/quality/qualityIssue.js'
import Chooselist from '@/views/modules/common/Chooselist_eam'
import ComQualityIssueDetail from './com_qualityIssueDetail.vue'
import ComQualityIssueAttachment from './com_qualityIssueAttachment.vue'
import excel from '@/utils/excel-util.js'

export default {
  components: {
    Chooselist,
    QualityIssueDetail: ComQualityIssueDetail,
    QualityIssueAttachment: ComQualityIssueAttachment
  },
  data () {
    return {
      functionId: this.$route.meta.menuId,
      height: 400,
      detailHeight: 400,
      currentRow: {},
      activeTab: 'detail',
      // 新增弹窗相关数据
      addDialogVisible: false,
      addFormData: {
        issueNo: '',
        issueDate: '',
        requireReplyDate: '',
        supplierNo: '',
        supplierName: '',
        issueCategory: '',
        issueSummary: '',
        issueDescription: ''
      },
      addRules: {
        issueDate: [
          { required: true, message: '请选择问题日期', trigger: 'change' }
        ],
        requireReplyDate: [
          { required: true, message: '请选择要求回复日期', trigger: 'change' }
        ],
        supplierNo: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        issueCategory: [
          { required: true, message: '请选择问题分类', trigger: 'change' }
        ],
        issueSummary: [
          { required: true, message: '请输入问题简述', trigger: 'blur' }
        ]
      },
      // 编辑弹窗相关数据
      editDialogVisible: false,
      editFormData: {
        issueNo: '',
        issueDate: '',
        requireReplyDate: '',
        supplierNo: '',
        supplierName: '',
        issueCategory: '',
        issueSummary: '',
        issueDescription: '',
        site: ''
      },
      editRules: {
        issueDate: [
          { required: true, message: '请选择问题日期', trigger: 'change' }
        ],
        requireReplyDate: [
          { required: true, message: '请选择要求回复日期', trigger: 'change' }
        ],
        issueCategory: [
          { required: true, message: '请选择问题分类', trigger: 'change' }
        ],
        issueSummary: [
          { required: true, message: '请输入问题简述', trigger: 'blur' }
        ]
      },
      // 回复弹窗相关数据
      replyDialogVisible: false,
      replyFormData: {
        site: '',
        issueNo: '',
        analysis: '',
        correctiveAction: '',
        replyBy: '',
        replyTime: ''
      },
      replyRules: {
        analysis: [
          { required: true, message: '请输入原因分析', trigger: 'blur' }
        ],
        correctiveAction: [
          { required: true, message: '请输入后续措施', trigger: 'blur' }
        ]
      },
      tagNo: '',
      searchData: {
        issueNo: '',
        supplierNo: '',
        supplierName: '',
        issueCategory: '',
        statusDb: '',
        issueDate: '',
        page: 1,
        limit: 50
      },
      searchType: '',
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      mainDataList: [],
      dataListLoading: false,
      columnArray1: [
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'QualityIssueTable1IssueNo',
          tableId: 'QualityIssueTable1',
          tableName: '质量问题',
          columnProp: 'issueNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '反馈单号',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'QualityIssueTable1IssueDate',
          tableId: 'QualityIssueTable1',
          tableName: '质量问题',
          columnProp: 'issueDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '问题日期',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'QualityIssueTable1SupplierNo',
          tableId: 'QualityIssueTable1',
          tableName: '质量问题',
          columnProp: 'supplierNo',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '供应商编码',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'QualityIssueTable1SupplierName',
          tableId: 'QualityIssueTable1',
          tableName: '质量问题',
          columnProp: 'supplierName',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '供应商名称',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'QualityIssueTable1IssueCategory',
          tableId: 'QualityIssueTable1',
          tableName: '质量问题',
          columnProp: 'issueCategory',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '问题分类',
          columnWidth: '120',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'QualityIssueTable1IssueSummary',
          tableId: 'QualityIssueTable1',
          tableName: '质量问题',
          columnProp: 'issueSummary',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '问题简述',
          columnWidth: '200',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'QualityIssueTable1Status',
          tableId: 'QualityIssueTable1',
          tableName: '质量问题',
          columnProp: 'status',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '状态',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'QualityIssueTable1CreateBy',
          tableId: 'QualityIssueTable1',
          tableName: '质量问题',
          columnProp: 'createBy',
          headerAlign: 'center',
          align: 'left',
          columnLabel: '录入人',
          columnWidth: '100',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        },
        {
          userId: this.$store.state.user.name,
          functionId: this.functionId,
          serialNumber: 'QualityIssueTable1CreateDate',
          tableId: 'QualityIssueTable1',
          tableName: '质量问题',
          columnProp: 'createDate',
          headerAlign: 'center',
          align: 'center',
          columnLabel: '录入时间',
          columnWidth: '150',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: false
        }
      ]
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.height = (window.innerHeight - 220) / 2
      this.detailHeight = (window.innerHeight - 220) / 2
      this.getMainData()
    })
  },
  methods: {
    // 获取基础数据列表
    getBaseList (val, type) {
      this.tagNo = val
      this.searchType = type || ''
      this.$nextTick(() => {
        let strVal = ''
        let conSql = ''
        if (val === 1100) {
          strVal = this.addFormData.supplierNo || ''
          conSql = " and site = '" + this.$store.state.user.site + "'"
        }
        this.$refs.baseList.init(val, strVal, conSql)
      })
    },

    /* 列表方法的回调 */
    getBaseData (val) {
      if (this.tagNo === 1100) {
        // 新增弹窗：使用下划线命名的字段，使用$set确保响应式
        this.$set(this.addFormData, 'supplierNo', val.supplier_no || '')
        this.$set(this.addFormData, 'supplierName', val.supplier_name || '')
      }
    },
    // 查询数据
    getMainData () {
      this.searchData.limit = this.pageSize
      this.searchData.page = this.pageIndex
      this.searchData.site = this.$store.state.user.site
      this.dataListLoading = true

      queryQualityIssuePage(this.searchData).then(({ data }) => {
        if (data.code === 0) {
          this.mainDataList = data.page.list
          this.pageIndex = data.page.currPage
          this.pageSize = data.page.pageSize
          this.totalPage = data.page.totalCount

          this.$nextTick(() => {
            if (this.$refs.mainTable) {
              this.$refs.mainTable.clearSelection()
            }
          })

          // 判断是否有数据
          if (this.mainDataList.length > 0) {
            this.$refs.mainTable.setCurrentRow(this.mainDataList[0])
            this.changeData(this.mainDataList[0])
          } else {
            this.changeData(null)
          }
        }
        this.dataListLoading = false
      }).catch(() => {
        this.dataListLoading = false
      })
    },

    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getMainData()
    },

    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getMainData()
    },

    // 页签点击事件
    handleTabClick (tab) {
      // 每次点击页签都触发对应页签的查询
      if (tab.name === 'detail') {
        // 详情页签
      } else if (tab.name === 'attachment') {
        // 附件页签
        this.$nextTick(() => {
          if (this.$refs.attachmentTab) {
            this.$refs.attachmentTab.loadAttachmentList()
          }
        })
      }
    },

    // 行点击事件
    changeData (row) {
      this.currentRow = row ? JSON.parse(JSON.stringify(row)) : {}
    },

    // 新增质量问题
    addQualityIssue () {
      this.addDialogVisible = true
      this.resetAddForm()
    },

    // 关闭新增弹窗
    handleCloseAddDialog () {
      this.addDialogVisible = false
      this.resetAddForm()
    },

    // 关闭编辑弹窗
    handleCloseEditDialog () {
      this.editDialogVisible = false
      this.resetEditForm()
    },

    // 重置表单
    resetAddForm () {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      const todayStr = `${year}-${month}-${day}`

      this.addFormData = {
        issueNo: '',
        issueDate: todayStr,
        requireReplyDate: '',
        supplierNo: '',
        supplierName: '',
        issueCategory: '',
        issueSummary: '',
        issueDescription: ''
      }
      if (this.$refs.addFormData) {
        this.$refs.addFormData.clearValidate()
      }
    },

    // 重置编辑表单
    resetEditForm () {
      this.editFormData = {
        issueNo: '',
        issueDate: '',
        requireReplyDate: '',
        supplierNo: '',
        supplierName: '',
        issueCategory: '',
        issueSummary: '',
        issueDescription: '',
        site: ''
      }
      if (this.$refs.currentFormData) {
        this.$refs.currentFormData.clearValidate()
      }
    },

    // 选择供应商（仅新增模式）
    selectSupplier () {
      this.tagNo = 1100
      this.$nextTick(() => {
        const conSql = " and site = '" + this.$store.state.user.site + "'"
        this.$refs.baseList.init(1100, this.addFormData.supplierNo || '', conSql)
      })
    },

    // 保存新增
    handleSaveAdd () {
      this.$refs.addFormData.validate((valid) => {
        if (valid) {
          // 构建提交数据
          const submitData = {
            issueDate: this.addFormData.issueDate,
            requireReplyDate: this.addFormData.requireReplyDate,
            supplierNo: this.addFormData.supplierNo,
            supplierName: this.addFormData.supplierName,
            issueCategory: this.addFormData.issueCategory,
            issueSummary: this.addFormData.issueSummary,
            issueDescription: this.addFormData.issueDescription,
            site: this.$store.state.user.site
          }

          console.log('提交数据：', submitData)

          saveQualityIssue(submitData).then(({ data }) => {
            console.log('保存接口返回：', data)
            if (data.code === 0) {
              this.$message.success('保存成功')
              this.handleCloseAddDialog()
              this.getMainData()
            } else {
              this.$message.error(data.msg || '保存失败')
            }
          }).catch((error) => {
            console.error('保存接口错误：', error)
            this.$message.error('保存失败，请稍后重试')
          })
        } else {
          console.log('表单验证失败')
          this.$message.warning('请填写完整的表单信息')
        }
      })
    },

    // 保存编辑
    handleSaveEdit () {
      this.$refs.editFormData.validate((valid) => {
        if (valid) {
          // 构建提交数据
          const submitData = {
            site: this.editFormData.site,
            issueNo: this.editFormData.issueNo,
            issueDate: this.editFormData.issueDate,
            requireReplyDate: this.editFormData.requireReplyDate,
            issueCategory: this.editFormData.issueCategory,
            issueSummary: this.editFormData.issueSummary,
            issueDescription: this.editFormData.issueDescription
          }

          console.log('更新数据：', submitData)

          updateQualityIssue(submitData).then(({ data }) => {
            console.log('更新接口返回：', data)
            if (data.code === 0) {
              this.$message.success('更新成功')
              this.handleCloseEditDialog()
              this.getMainData()
            } else {
              this.$message.error(data.msg || '更新失败')
            }
          }).catch((error) => {
            console.error('更新接口错误：', error)
            this.$message.error('更新失败，请稍后重试')
          })
        } else {
          console.log('表单验证失败')
          this.$message.warning('请填写完整的表单信息')
        }
      })
    },

    // 编辑质量问题
    editQualityIssue (row) {
      this.editDialogVisible = true
      // 自动填充表格中的数据
      this.editFormData = {
        issueNo: row.issueNo || '',
        issueDate: row.issueDate || '',
        requireReplyDate: row.requireReplyDate || '',
        supplierNo: row.supplierNo || '',
        supplierName: row.supplierName || '',
        issueCategory: row.issueCategory || '',
        issueSummary: row.issueSummary || '',
        issueDescription: row.issueDescription || '',
        site: row.site || this.$store.state.user.site
      }
      // 清除验证状态
      this.$nextTick(() => {
        if (this.$refs.editFormData) {
          this.$refs.editFormData.clearValidate()
        }
      })
    },

    // 删除质量问题
    deleteQualityIssue(row) {
      this.$confirm('确定要删除该质量问题吗？删除后无法恢复！', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        // 显示加载中
        const loading = this.$loading({
          lock: true,
          text: '删除中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        // 构建删除参数
        const deleteParams = {
          site: row.site || this.$store.state.user.site,
          issueNo: row.issueNo
        };
        console.log('删除参数：', deleteParams);
        // 调用删除接口
        deleteQualityIssue(deleteParams).then(({ data }) => {
          loading.close();

          if (data.code === 0) {
            this.$message.success('删除成功');

            // 判断当前页是否还有数据
            const isLastItem = this.mainDataList.length === 1;

            // 刷新列表
            if (isLastItem && this.pageIndex > 1) {
              // 如果是最后一页的最后一条数据，跳转到上一页
              this.pageIndex--;
            }
            this.getMainData();
          } else {
            this.$message.error(data.msg || '删除失败');
          }
        }).catch((error) => {
          loading.close();
          console.error('删除接口错误：', error);
          this.$message.error('删除失败，请稍后重试');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 回复质量问题
    replyQualityIssue (row) {
      this.replyDialogVisible = true
      // 自动填充表格中的数据
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const currentDate = `${year}-${month}-${day}`

      this.replyFormData = {
        site: row.site || this.$store.state.user.site,
        issueNo: row.issueNo || '',
        analysis: '',
        correctiveAction: '',
        replyBy: this.$store.state.user.name || '',
        replyTime: currentDate
      }
      // 清除验证状态
      this.$nextTick(() => {
        if (this.$refs.replyFormData) {
          this.$refs.replyFormData.clearValidate()
        }
      })
    },

    // 关闭回复弹窗
    handleCloseReplyDialog () {
      this.replyDialogVisible = false
      this.resetReplyForm()
    },

    // 重置回复表单
    resetReplyForm () {
      this.replyFormData = {
        site: '',
        issueNo: '',
        analysis: '',
        correctiveAction: '',
        replyBy: '',
        replyTime: ''
      }
      if (this.$refs.replyFormData) {
        this.$refs.replyFormData.clearValidate()
      }
    },

    // 保存回复
    handleSaveReply () {
      this.$refs.replyFormData.validate((valid) => {
        if (valid) {
          // 构建提交数据
          const submitData = {
            site: this.replyFormData.site,
            issueNo: this.replyFormData.issueNo,
            analysis: this.replyFormData.analysis,
            correctiveAction: this.replyFormData.correctiveAction
          }

          console.log('回复数据：', submitData)

          saveReply(submitData).then(({ data }) => {
            console.log('回复接口返回：', data)
            if (data.code === 0) {
              this.$message.success('回复成功')
              this.handleCloseReplyDialog()
              this.getMainData()
            } else {
              this.$message.error(data.msg || '回复失败')
            }
          }).catch((error) => {
            console.error('回复接口错误：', error)
            this.$message.error('回复失败，请稍后重试')
          })
        } else {
          console.log('表单验证失败')
          this.$message.warning('请填写完整的回复信息')
        }
      })
    },

    // 导出
    exportExcel () {
      console.log('开始导出...')

      // 生成文件名（使用原生 Date）
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      const second = String(now.getSeconds()).padStart(2, '0')
      const exportName = `质量问题${year}${month}${day}${hour}${minute}${second}`

      console.log('导出参数:', this.searchData)

      // 获取当前查询条件
      const exportParams = {
        ...this.searchData,
        limit: -1,  // 导出全部数据
        page: 1
      }

      try {
        excel.exportTable({
          url: '/srm/qualityIssue/queryPage',
          columnMapping: this.columnArray1,
          mergeSetting: [],
          params: exportParams,
          fileName: exportName + '.xlsx',
          rowFetcher: res => {
            console.log('导出数据响应:', res)
            return res.data.page.list
          },
          columnFormatter: [],
          dropColumns: []
        })
        console.log('导出请求已发送')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败: ' + error.message)
      }
    }
  },
  created () {
    this.getMainData()
  }
}
</script>

<style scoped lang="scss">

.search-form-inline {
  background: #fff;
}

.search-row {
  display: flex;
  align-items: flex-end;
  flex-wrap: nowrap;
  gap: 15px;
}

.search-row:last-child {
  margin-top: -10px;
}

.search-item {
  flex: none;
  margin-bottom: 10px;
}

.search-btn-item {
  flex: none;
  margin-bottom: 10px;
}

.search-btn-item /deep/ .el-form-item__content {
  line-height: normal;
}

.search-item /deep/ .el-form-item__label {
  font-size: 13px;
  color: #606266;
  padding-bottom: 5px;
  line-height: 1;
  height: auto;
}

.search-item /deep/ .el-form-item__content {
  line-height: normal;
}

.date-range {
  display: flex;
  align-items: center;
}

.split {
  padding: 0 6px;
  color: #606266;
  font-size: 13px;
}

/deep/ .customer-tab .el-tabs__content {
  padding: 5px !important;
}

.add-dialog-form /deep/ .el-form-item {
  margin-bottom: 10px;
}

.add-dialog-form /deep/ .el-form-item__label {
  text-align: left;
  float: none;
  display: block;
  padding: 0 0 5px 0;
  line-height: 1;
  font-size: 13px;
}

.add-dialog-form /deep/ .el-form-item__content {
  margin-left: 0 !important;
}

.dialog-footer {
  text-align: center;
}

/* 回复弹窗样式 */
.reply-dialog-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.reply-dialog-info .info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.reply-dialog-info .info-item:last-child {
  margin-bottom: 0;
}

.reply-dialog-info .info-label {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
  min-width: 80px;
}

.reply-dialog-info .info-value {
  font-size: 13px;
  color: #303133;
  flex: 1;
}

.reply-dialog-form /deep/ .el-form-item {
  margin-bottom: 15px;
}

.reply-dialog-form /deep/ .el-form-item__label {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
  padding-bottom: 5px;
  line-height: 1;
  height: auto;
}

.reply-dialog-form /deep/ .el-form-item__content {
  line-height: normal;
}

</style>
