<template>
  <div class="flex-row">
    <div class="basic-main">
      <criteria-paged :model="model" v-ref:paged>
        <criteria partial="criteria" class="search_area" @condition-changed='$parent.selfSearch' v-ref:criteria>
          <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
            <div class="row">
              <div class="form-group col-sm-2">
                <label class="font_normal_body">工单编号</label>
                <input type="text" class="input_search" v-model="model.f_work_order_no"
                       style="width: 60%" placeholder="工单编号" condition="f_work_order_no like '%{}%'">
              </div>
              <div class="form-group col-sm-2">
                <label class="font_normal_body">检查单位</label>
                <input type="text" class="input_search" v-model="model.f_check_unit"
                       style="width: 60%" placeholder="检查单位" condition="f_check_unit like '%{}%'">
              </div>
              <div class="form-group col-sm-2">
                <label class="font_normal_body">所属公司</label>
                <input type="text" class="input_search" v-model="model.f_company"
                       style="width: 60%" placeholder="所属公司" condition="f_company like '%{}%'">
              </div>
              <div class="form-group col-sm-2">
                <label class="font_normal_body">隐患等级</label>
<!--                <v-select :value.sync="model.f_defect_level"-->
<!--                          v-model="model.f_defect_level"-->
<!--                          style="width: 60%"-->
<!--                          class=" select"-->
<!--                          :options="$parent.$parent.defectLevelOptions"-->
<!--                          placeholder="隐患等级"-->
<!--                          :value-single="true"-->
<!--                          condition="f_defect_level = '{}'"></v-select>-->
                <input type="text" class="input_search" v-model="model.f_defect_level"
                       style="width: 60%" placeholder="隐患等级" condition="f_defect_level like '%{}%'">
              </div>
              <div class="form-group col-sm-2">
                <label class="font_normal_body">完成情况</label>
<!--                <v-select :value.sync="model.f_completion_status"-->
<!--                          v-model="model.f_completion_status"-->
<!--                          style="width: 60%"-->
<!--                          class=" select"-->
<!--                          :options="$parent.$parent.completionOptions"-->
<!--                          placeholder="完成情况"-->
<!--                          :value-single="true"-->
<!--                          condition="f_completion_status = '{}'"></v-select>-->
                <input type="text" class="input_search" v-model="model.f_completion_status"
                       style="width: 60%" placeholder="完成情况" condition="f_completion_status like '%{}%'">
              </div>
            </div>
            <div class="row">
              <div class="form-group col-sm-4" style="display: flex; flex-wrap: wrap; gap: 8px; align-items: center;float:right;">
                <button class="button_spacing button_new" @click="$parent.$parent.downloadTemplate">下载模板</button>
                <button class="button_spacing button_search" @click="$parent.$parent.showImportDialog = true">导入数据</button>
                <export-excel-safe :data="$parent.$parent.searchData"
                                   :field="$parent.$parent.excelHeaders"
                                   :choose-col="true"
                                   sqlurl="rs/logic/SafeExportExcel" sql-name="safe_singleTable_OrderBy" template-name='生成隐患导出'></export-excel-safe>
                <button class="button_spacing button_search" @click="search()">查询</button>
              </div>
            </div>
          </div>
        </criteria>
        <data-grid class="list_area table_sy" style="overflow: hidden" :model="model" partial="list" v-ref:grid>
          <template partial="head">
            <tr>
              <th><nobr>工单编号</nobr></th>
              <th><nobr>检查单位/部门</nobr></th>
              <th><nobr>所属公司</nobr></th>
              <th><nobr>检查类型</nobr></th>
              <th><data-order field="f_check_time" name="检查具体时间"></data-order></th>
              <th><nobr>隐患问题分类</nobr></th>
              <th><nobr>隐患等级</nobr></th>
              <th><nobr>隐患描述</nobr></th>
              <th><data-order field="f_plan_complete_time" name="计划整改完成时间"></data-order></th>
              <th><data-order field="f_actual_complete_time" name="实际完成时间"></data-order></th>
              <th><nobr>责任人</nobr></th>
              <th><nobr>完成情况</nobr></th>
              <th><nobr>是否制定延期报告应急预案</nobr></th>
              <th><nobr>未完成原因</nobr></th>
              <th><nobr>附件</nobr></th>
              <th><nobr>操作</nobr></th>
            </tr>
          </template>
          <template partial="body">
            <td style="text-align: center">{{row.f_work_order_no}}</td>
            <td style="text-align: center">{{row.f_check_unit}}</td>
            <td style="text-align: center">{{row.f_company}}</td>
            <td style="text-align: center">{{row.f_check_type}}</td>
            <td style="text-align: center">{{row.f_check_time}}</td>
            <td style="text-align: center">{{row.f_defect_category}}</td>
            <td style="text-align: center">{{row.f_defect_level}}</td>
            <td style="text-align: center">{{row.f_defect_description}}</td>
            <td style="text-align: center">{{row.f_plan_complete_time}}</td>
            <td style="text-align: center">{{row.f_actual_complete_time}}</td>
            <td style="text-align: center">{{row.f_responsible_person}}</td>
            <td style="text-align: center">{{row.f_completion_status}}</td>
            <td style="text-align: center">{{row.f_has_emergency_plan}}</td>
            <td style="text-align: center">{{row.f_incomplete_reason}}</td>
            <td style="text-align: center">
              <button class="button_new button_spacing" @click="$parent.$parent.$parent.viewAttachments(row)">查看附件</button>
            </td>
            <td style="text-align: center">
              <button class="button_new button_spacing" @click="$parent.$parent.$parent.uploadAttachment(row)">上传附件</button>
            </td>
          </template>
        </data-grid>
      </criteria-paged>

      <!-- 导入数据对话框 -->
      <modal :show.sync="showImportDialog" backdrop="false">
        <div slot="modal-header" class="modal-header">
          <h4 class="modal-title">导入生产隐患数据</h4>
        </div>
        <div slot="modal-body" class="modal-body">
          <div class="form-group">
            <label class="col-sm-3 control-label">选择文件：</label>
            <div class="col-sm-9">
              <input type="file" class="form-control" @change="selectImportFile" accept=".xls,.xlsx" ref="importFileInput">
            </div>
          </div>
          <div class="form-group" style="margin-top: 15px;">
            <p style="color: #999; padding: 10px;">注意：系统会根据工单编号自动判断是新增还是更新数据。如果工单编号已存在，则更新该记录；否则新增记录。支持多次导入，相同工单编号的数据会自动更新。</p>
          </div>
        </div>
        <div slot="modal-footer" class="modal-footer">
          <button class="button_spacing button_search" @click="importData">导入</button>
          <button class="button_spacing button_new" @click="cancelImport">取消</button>
        </div>
      </modal>

      <!-- 附件上传对话框 -->
      <modal :show.sync="showAttachmentDialog" backdrop="false" width="800px">
        <div slot="modal-header" class="modal-header">
          <h4 class="modal-title">上传附件 - {{currentRow.f_work_order_no}}</h4>
        </div>
        <div slot="modal-body" class="modal-body" style="min-height: 300px;">
          <file-upload style="margin-top: -8px;margin-left: 45px" :name="'myFile' + currentRow.id"
                       action="rs/file/uploadFile" tagname="文件上传" :headers="headers" multiple v-ref:file>
          </file-upload>
        </div>
        <div slot="modal-footer" class="modal-footer">
          <button class="button_spacing button_new" @click="showAttachmentDialog = false">关闭</button>
        </div>
      </modal>

      <!-- 附件查看对话框 -->
      <modal :show.sync="showViewAttachmentDialog" backdrop="false" width="800px">
        <div slot="modal-header" class="modal-header">
          <h4 class="modal-title">查看附件 - {{currentRow.f_work_order_no}}</h4>
        </div>
        <div slot="modal-body" class="modal-body" style="min-height: 300px;">
          <div v-if="attachmentList.length === 0" style="text-align: center; color: #999; padding: 40px;">
            暂无附件
          </div>
          <table v-else class="table table-bordered table-hover" style="width:100%;">
            <thead>
              <tr>
                <th style="text-align: center; width: 50px;">序号</th>
                <th style="text-align: center;">文件名</th>
                <th style="text-align: center; width: 180px;">上传时间</th>
                <th style="text-align: center; width: 100px;">查看</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="file in attachmentList" track-by="$index">
                <td style="text-align: center;">{{$index + 1}}</td>
                <td style="text-align: center;">{{file.f_filename}}</td>
                <td style="text-align: center;">{{file.f_uploaddate}}</td>
                <td style="text-align: center;">
<!--                  <a :href="'rs/image/file/'+ file.f_filename" target="_blank" class="button_search button_spacing" style="text-decoration: none;">下载</a>-->
                  <img-self-plus :src="'files/' + (file.f_downloadpath.startsWith('D:') ? file.f_downloadpath.slice(9) : file.f_downloadpath)" width="150" height="150"></img-self-plus>

                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div slot="modal-footer" class="modal-footer">
          <button class="button_spacing button_new" @click="showViewAttachmentDialog = false">关闭</button>
        </div>
      </modal>
    </div>
  </div>
</template>

<script>
  import {PagedList} from 'vue-client'
  import HttpResetClass from "vue-client/src/plugins/HttpResetClass";

  export default {
    title: '生产隐患汇总',
    data() {
      let model = new PagedList('rs/sql/safe_singleTable_OrderBy', 20,{
        items: "'*'",
        tablename: "'t_production_defect'",
        orderitem: "'id desc'"
      })
      return {
        headers: {'username': this.$login.f.name, 'blodid': '','businessid':'', 'fremarks': '','defname':'','fusetype':''},
        model: model,
        criteriaShow: false,
        defectLevelOptions: [
          {label: '全部', value: ''},
          {label: '重大隐患', value: '重大隐患'},
          {label: '较大隐患', value: '较大隐患'},
          {label: '一般隐患', value: '一般隐患'}
        ],
        completionOptions: [
          {label: '全部', value: ''},
          {label: '已整改', value: '已整改'},
          {label: '未整改', value: '未整改'}
        ],
        searchData: {items: '*', tablename: 't_production_defect', orderitem: 'id desc',condition: ""},
        excelHeaders: {
          'f_work_order_no': '工单编号',
          'f_check_unit': '检查单位/部门',
          'f_company': '所属公司',
          'f_check_type': '检查类型',
          'f_check_time': '检查具体时间',
          'f_defect_category': '隐患问题分类',
          'f_defect_level': '隐患等级',
          'f_defect_description': '隐患描述',
          'f_plan_complete_time': '计划整改完成时间',
          'f_actual_complete_time': '实际完成时间',
          'f_responsible_person': '责任人',
          'f_completion_status': '完成情况',
          'f_has_emergency_plan': '是否制定延期报告应急预案',
          'f_incomplete_reason': '未完成原因'
        },
        showImportDialog: false,
        importFile: null,
        showAttachmentDialog: false,
        showViewAttachmentDialog: false,
        currentRow: {},
        attachmentList: []
      }
    },
    methods: {
      doSearch() {
        this.$refs.paged.$refs.criteria.search()
      },
      selfSearch(args){
        this.searchData.condition = args.condition
        this.model.search(args.condition, args.model, args.condValue)
      },

      // SQL 值转义（防注入，处理单引号）
      esc(str) {
        return str == null ? '' : String(str).replace(/'/g, "''")
      },

      // 下载模板
      downloadTemplate() {
        let headers = [
          ['生产工单编号', '检查单位/部门', '所属公司', '检查类型', '检查具体时间',
           '隐患问题分类', '隐患等级', '隐患描述', '计划整改完成时间',
           '实际完成时间', '责任人', '完成情况', '是否制定延期报告应急预案', '未完成原因']
        ]
        let XLSX = require('xlsx')
        let ws = XLSX.utils.aoa_to_sheet(headers)
        let wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '生产隐患导入模板')
        XLSX.writeFile(wb, '生产隐患导入模板.xlsx')
      },

      // 选择导入文件
      selectImportFile(event) {
        this.importFile = event.target.files[0]
      },

      // 取消导入
      cancelImport() {
        this.showImportDialog = false
        this.importFile = null
        if (this.$refs.importFileInput) {
          this.$refs.importFileInput.value = ''
        }
      },

      // 构建 SET 子句（for UPDATE）
      buildSetClauses(row) {
        let fields = {
          f_check_unit: row['检查单位/部门'] || row['检查单位'] || '',
          f_company: row['所属公司'] || '',
          f_check_type: row['检查类型'] || '',
          f_check_time: this.formatExcelDate(row['检查具体时间']) || '',
          f_defect_category: row['隐患问题分类'] || row['隐患分类'] || '',
          f_defect_level: row['隐患等级'] || '',
          f_defect_description: row['隐患描述'] || '',
          f_plan_complete_time: this.formatExcelDate(row['计划整改完成时间']) || '',
          f_actual_complete_time: this.formatExcelDate(row['实际完成时间']) || '',
          f_responsible_person: row['责任人'] || '',
          f_completion_status: row['完成情况'] || '',
          f_has_emergency_plan: row['是否制定延期报告应急预案'] || '',
          f_incomplete_reason: row['未完成原因'] || ''
        }
        let sets = []
        for (let key in fields) {
          sets.push(`${key} = '${this.esc(fields[key])}'`)
        }
        return sets.join(', ')
      },

      // 构建 INSERT 语句
      buildInsertSql(row) {
        let fields = {
          f_work_order_no: row['生产工单编号'] || row['工单编号'] || '',
          f_check_unit: row['检查单位/部门'] || row['检查单位'] || '',
          f_company: row['所属公司'] || '',
          f_check_type: row['检查类型'] || '',
          f_check_time: this.formatExcelDate(row['检查具体时间']) || '',
          f_defect_category: row['隐患问题分类'] || row['隐患分类'] || '',
          f_defect_level: row['隐患等级'] || '',
          f_defect_description: row['隐患描述'] || '',
          f_plan_complete_time: this.formatExcelDate(row['计划整改完成时间']) || '',
          f_actual_complete_time: this.formatExcelDate(row['实际完成时间']) || '',
          f_responsible_person: row['责任人'] || '',
          f_completion_status: row['完成情况'] || '',
          f_has_emergency_plan: row['是否制定延期报告应急预案'] || '',
          f_incomplete_reason: row['未完成原因'] || '',
          f_filialeid: this.$login.f.orgid || '',
          f_creator: this.$login.f.name || '',
          f_create_time: new Date().toISOString().split('T')[0] + ' ' + new Date().toTimeString().split(' ')[0],
          f_is_valid: '1'
        }
        let cols = Object.keys(fields)
        let vals = cols.map(k => `'${this.esc(fields[k])}'`)
        // SQL Server 用 NEWID() 生成32位GUID作为主键
        let guidSql = `REPLACE(NEWID(), '-', '')`
        return `INSERT INTO t_production_defect (id, ${cols.join(', ')}) VALUES (${guidSql}, ${vals.join(', ')})`
      },
      importData() {
        if (!this.importFile) {
          this.$showMessage('请先选择要导入的文件！')
          return
        }

        let XLSX = require('xlsx')
        let reader = new FileReader()

        reader.onload = (e) => {
          try {
            let data = new Uint8Array(e.target.result)
            let workbook = XLSX.read(data, {type: 'array'})
            let firstSheet = workbook.Sheets[workbook.SheetNames[0]]
            let jsonData = XLSX.utils.sheet_to_json(firstSheet)

            if (jsonData.length === 0) {
              this.$showMessage('导入的文件没有数据！')
              return
            }

            this.doImport(jsonData)
          } catch (error) {
            console.error('解析Excel失败：', error)
            this.$showMessage('文件解析失败，请检查文件格式！')
          }
        }

        reader.readAsArrayBuffer(this.importFile)
      },

      // 执行导入
      async doImport(jsonData) {
        let http = new HttpResetClass()
        let successCount = 0
        let updateCount = 0
        let errorCount = 0

        for (let i = 0; i < jsonData.length; i++) {
          let row = jsonData[i]
          let workOrderNo = row['生产工单编号'] || row['工单编号'] || ''

          if (!workOrderNo) {
            console.warn(`第${i+2}行缺少工单编号，跳过`)
            errorCount++
            continue
          }

          try {
            let checkResult = await http.load('POST', 'rs/sql/safe_singleTable_OrderBy', {data: {
              items: 'id, f_attachment_ids',
              tablename: 't_production_defect',
              condition: `f_work_order_no = '${this.esc(workOrderNo)}'`,
              orderitem: 'id'
            }}, {resolveMsg: null, rejectMsg: '查询工单失败'})

            if (checkResult.data && checkResult.data.length > 0) {
              // 已存在 → UPDATE
              let setClauses = this.buildSetClauses(row)
              let sql = `UPDATE t_production_defect SET ${setClauses} WHERE f_work_order_no = '${this.esc(workOrderNo)}'`
              await http.load('POST', 'rs/logic/runSQL', {data: {sql: sql}},
                {resolveMsg: null, rejectMsg: '更新生产隐患失败'})
              updateCount++
            } else {
              // 不存在 → INSERT
              let sql = this.buildInsertSql(row)
              await http.load('POST', 'rs/logic/runSQL', {data: {sql: sql}},
                {resolveMsg: null, rejectMsg: '新增生产隐患失败'})
              successCount++
            }
          } catch (err) {
            console.error(`导入第${i+2}行失败：`, err)
            errorCount++
          }
        }

        this.$showMessage(`导入完成！新增${successCount}条，更新${updateCount}条，失败${errorCount}条`)
        this.cancelImport()
        this.doSearch()
      },

      // 格式化Excel日期
      formatExcelDate(value) {
        if (!value) return ''
        if (typeof value === 'string') {
          let date = new Date(value)
          if (!isNaN(date.getTime())) {
            return date.toISOString().split('T')[0]
          }
          return value
        }
        if (typeof value === 'number') {
          let date = new Date((value - 25569) * 86400000)
          return date.toISOString().split('T')[0]
        }
        return value
      },

      // 查看附件
      async viewAttachments(row) {
        this.currentRow = row
        this.attachmentList = []

        let ids = (row.f_attachment_ids || '').trim()
        if (!ids) {
          this.$showMessage('该记录暂无附件')
          return
        }

        let idArray = ids.split(',').map(id => id.trim()).filter(id => id)
        let inClause = idArray.map(id => `'${this.esc(id)}'`).join(',')
        let condition = `id IN (${inClause})`

        try {
          let http = new HttpResetClass()
          let result = await http.load('POST', 'rs/sql/safe_singleTable_OrderBy', {data: {
            items: 'id, f_filename, f_filetype, f_downloadpath, f_realpath, f_uploaddate',
            tablename: 't_files',
            condition: condition,
            orderitem: 'f_uploaddate desc'
          }}, {resolveMsg: null, rejectMsg: '查询附件失败'})
          if (result.data && result.data.length > 0) {
            this.attachmentList = result.data
          }
          this.showViewAttachmentDialog = true
        } catch (err) {
          console.error('查询附件失败：', err)
          this.attachmentList = []
          this.showViewAttachmentDialog = true
        }
      },

      // 上传附件
      uploadAttachment(row) {
        this.currentRow = row
        this.showAttachmentDialog = true
      }
    },
    ready() {
      // this.doSearch()
    },
    events: {
      onFileUpload: function (file, res) {
        if (res.result !== 'success' || !res.id) {
          console.error('附件上传失败', res)
          return
        }
        // file-upload 的 $parent 是 modal，modal 的 $parent 是 ProductionDefectSummary.vue 实例
        let self = this
        let row = self.currentRow
        if (!row || !row.id) return

        // 追加附件 id，用逗号分割
        let oldIds = (row.f_attachment_ids || '').trim()
        let newIds = oldIds ? oldIds + ',' + res.id : '' + res.id

        let sql = `UPDATE t_production_defect SET f_attachment_ids = '${self.esc(newIds)}' WHERE id = '${self.esc(row.id)}'`
        let http = new HttpResetClass()
        http.load('POST', 'rs/logic/runSQL', {data: {sql: sql}}, {resolveMsg: null, rejectMsg: '更新附件信息失败'})
          .then(() => {
            row.f_attachment_ids = newIds
            self.$showMessage('附件上传成功！')
          })
          .catch((err) => {
            console.error('更新附件id失败：', err)
          })
      }
    }
  }
</script>

<style scoped>
  .button_spacing {
    margin-left: 5px;
  }

  .input_search {
    width: 60%;
    padding: 5px;
    border:1px solid #ccc;
    border-radius: 3px;
  }

  .select_list {
    width: 60%;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 3px;
  }

  .font_normal_body {
    font-weight: normal;
    font-size: 12px;
  }
</style>
