<template>
  <div class="sop-list-component" style="padding: 2px !important">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-button @click="fileLibraryHandle()">从文件库添加</el-button>
        <el-button type="danger" @click="batchDeleteHandle()" :disabled="dataListSelections.length === 0" :loading="deleteLoading">删除</el-button>
        <a class="sop-external-link" href="#" @click.prevent="openExternalLink">外部链接</a>
      </el-form-item>
    </el-form>

    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      :height="tableHeight"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="sopNo"
        header-align="center"
        align="center"
        label="文件编码"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="sopName"
        header-align="center"
        align="left"
        label="文件名称"
        min-width="200">
      </el-table-column>
      <el-table-column
        prop="sopType"
        header-align="center"
        align="center"
        label="文件类型"
        min-width="100">
      </el-table-column>
      <el-table-column
        prop="fileSuffix"
        header-align="center"
        align="center"
        label="文件后缀"
        mib-width="100">
      </el-table-column>
      <el-table-column
        prop="version"
        header-align="center"
        align="center"
        label="版本号"
        min-width="100">
      </el-table-column>
      <el-table-column
        prop="operationDesc"
        header-align="center"
        align="left"
        label="工序"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="phaseInDate"
        header-align="center"
        align="center"
        label="生效日期"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="phaseOutDate"
        header-align="center"
        align="center"
        label="失效日期"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="sourceSystem"
        header-align="center"
        align="center"
        label="来源系统"
        min-width="100">
      </el-table-column>
<!--      <el-table-column-->
<!--        prop="standardFields"-->
<!--        header-align="center"-->
<!--        align="center"-->
<!--        label="4个标准字段"-->
<!--        min-width="120">-->
<!--      </el-table-column>-->
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="100"
        label="操作">
        <template slot-scope="scope">
          <a type="text" size="small" @click="previewHandle(scope.row)">预览</a>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 文件上传弹窗 -->
    <sop-file-upload
      v-if="sopFileUploadVisible"
      ref="sopFileUpload"
      @refreshDataList="getDataList">
    </sop-file-upload>
  </div>
</template>

<script>
import SopFileUpload from './sopFileUpload'
import { sopListSearch, sopRecordDelete, downloadSopFile } from '@/api/qc/qc.js'

export default {
  name: 'SopListComponent',
  components: {
    SopFileUpload
  },
  props: {
    partNo: {
      type: String,
      default: ''
    },
    site: {
      type: [String, Number],
      default: ''
    },
    buNo: {
      type: String,
      default: ''
    },
    tableHeight: {
      type: Number,
      default: 200
    }
  },
  data () {
    return {
      dataForm: {},
      dataList: [],
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      sopFileUploadVisible: false,
      deleteLoading: false
    }
  },
  watch: {
    partNo: {
      handler (newVal) {
        if (newVal) {
          this.getDataList()
        }
      },
      immediate: true
    }
  },
  methods: {
    // 获取数据列表
    getDataList () {
      if (!this.partNo) {
        this.dataList = []
        this.totalPage = 0
        return
      }

      this.dataListLoading = true
      sopListSearch({
        page: this.pageIndex,
        limit: this.pageSize,
        partNo: this.partNo,
        site: this.site || this.$store.state.user.site
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list || []
          this.totalPage = data.page.totalCount || 0
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      }).catch(() => {
        this.dataList = []
        this.totalPage = 0
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 从文件库查询并关联到物料
    fileLibraryHandle () {
      if (!this.partNo) {
        this.$message.warning('请先选择物料')
        return
      }
      this.sopFileUploadVisible = true
      this.$nextTick(() => {
        this.$refs.sopFileUpload.init(this.partNo, this.site, this.buNo)
      })
    },
    // 打开外部链接（按物料编码）
    openExternalLink () {
      if (!this.partNo) {
        this.$message.warning('请先选择物料')
        return false
      }
      const baseUrl = window.SITE_CONFIG['processDataUrl'] || 'http://pdm.bt.in/#/public/processData'
      const targetUrl = `${baseUrl}/${this.partNo}`
      window.open(targetUrl, '_blank')
    },
    // 预览
    previewHandle (row) {
      if (!row.sopUrl) {
        this.$message.warning('该文件暂无预览路径')
        return
      }

      const fileName = row.sopName || row.sopUrl
      downloadSopFile(row.sopUrl).then(({ data }) => {
        this.$filePreview.previewFile(data, fileName).then(result => {
          if (result.message) {
            this.$message.success(result.message)
          }
        }).catch(error => {
          this.$message.error('文件预览失败：' + (error.message || '未知错误'))
        })
      }).catch(() => {
        this.$message.error('文件下载失败，请稍后重试')
      })
    },
    // 批量删除
    batchDeleteHandle () {
      if (this.dataListSelections.length === 0) {
        this.$message.warning('请先选择要删除的记录')
        return
      }

      this.$confirm(`确定要删除选中的${this.dataListSelections.length}条SOP记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteLoading = true
        const deletePromises = this.dataListSelections.map(row => {
          return sopRecordDelete({
            site: row.site,
            buNo: row.buNo,
            partNo: row.partNo,
            sopNo: row.sopNo
          })
        })

        Promise.all(deletePromises).then((responses) => {
          const successCount = responses.filter(({data}) => data && data.code === 0).length
          if (successCount === this.dataListSelections.length) {
            this.$message.success(`成功删除${successCount}条记录`)
          } else {
            this.$message.warning(`删除了${successCount}条记录，${this.dataListSelections.length - successCount}条删除失败`)
          }
          this.getDataList()
          this.deleteLoading = false
        }).catch(() => {
          this.$message.error('删除失败')
          this.deleteLoading = false
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.sop-list-component {
  padding: 10px;
}

.sop-external-link {
  margin-left: 10px;
  color: #17b3a3;
  text-decoration: underline;
  font-size: 13px;
  cursor: pointer;
}

.sop-external-link:visited,
.sop-external-link:active,
.sop-external-link:hover {
  color: #17b3a3;
}
</style>
