<!-- 图库管理 -->
<template>
  <div class="draw-management">
    <template v-if="!addOrUpdateVisible && !detailVisible">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()">
        <el-form-item label="名称">
          <el-input v-model="dataForm.keyword" placeholder="名称" clearable />
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker v-model="dataForm.date" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="物料" prop="productId">
          <product-component v-model="dataForm.productId" :product-id.sync="dataForm.productId"></product-component>
        </el-form-item>
        <el-form-item>
          <el-button @click="search()">查询</el-button>
          <el-button v-if="isAuth('pro:drawing:save')" type="primary"
            @click="addOrUpdateHandle(0, false)">上传图纸</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="dataList" border v-loading="dataListLoading" style="width: 100%;">
        <el-table-column label="序号" type="index" width="50" align="center">
        </el-table-column>
        <!-- <el-table-column
          prop="drawingCode"
          header-align="center"
          align="center"
          min-width="100"
          :show-tooltip-when-overflow="true"
          label="图纸编码">
        </el-table-column> -->
        <el-table-column prop="drawingName" header-align="center" align="center" min-width="120"
          :show-tooltip-when-overflow="true" label="图纸名称">
        </el-table-column>
        <el-table-column prop="drawingNo" header-align="center" align="center" min-width="120"
          :show-tooltip-when-overflow="true" label="图号">
        </el-table-column>
        <el-table-column prop="version" header-align="center" align="center" min-width="120"
          :show-tooltip-when-overflow="true" label="版本">
        </el-table-column>
        <el-table-column header-align="center" align="center" min-width="60" label="图纸文件">
          <template slot-scope="scope">
            <el-button v-if="scope.row.attachList && scope.row.attachList.length" type="text" size="small"
              @click="openImagePreview(scope.row.attachList)">
              查看({{ scope.row.attachList.length }})
            </el-button>
            <el-button v-else type="text" size="small" disabled>
              查看(0)
            </el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="productName"
          header-align="center"
          align="center"
          min-width="140"
          :show-tooltip-when-overflow="true"
          label="对应物料">
        </el-table-column>
        <el-table-column
          prop="source"
          header-align="center"
          align="center"
          min-width="200"
          :show-overflow-tooltip="true"
          label="来源">
        </el-table-column> -->
        <el-table-column prop="createTime" header-align="center" align="center" min-width="160" label="上传时间">
        </el-table-column>
        <el-table-column prop="creatorName" header-align="center" align="center" min-width="100" label="上传人">
        </el-table-column>
        <el-table-column prop="notes" header-align="center" align="center" min-width="180" :show-overflow-tooltip="true"
          label="备注">
        </el-table-column>
        <el-table-column prop="state" header-align="center" align="center" width="100" label="状态">
          <template slot-scope="scope">
            <el-tag :type="Number(scope.row.state) === 1 ? 'success' : 'danger'" disable-transitions>
              {{ Number(scope.row.state) === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" width="160" label="操作">
          <template slot-scope="scope">
            <!-- 查看 -->
            <el-button type="text" size="small" @click="detailHandle(scope.row.drawingId)">查看</el-button>
            <!-- 启用/停用 -->
            <el-button v-if="isAuth('pro:drawing:update')" type="text" size="small" @click="toggleState(scope.row)">
              {{ Number(scope.row.state) === 1 ? '停用' : '启用' }}
            </el-button>
            <!-- 打印 -->
            <el-button v-if="scope.row.attachList && scope.row.attachList.length" type="text" size="small"
              class="print-btn" @click="printImages(scope.row.attachList)">打印</el-button>
          </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">
      </el-pagination>
    </template>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"
      @onChose="onChose"></add-or-update>
    <detail v-if="detailVisible" ref="detail" @onChose="onChose" />
    <preview-component v-if="previewVisible" ref="preview" @onChose="onChose"></preview-component>
    <image-preview ref="imagePreview" />
  </div>
</template>

<script>
import AddOrUpdate from './draw-add-or-update'
import Detail from './draw-detail'
import { getDrawList } from '@/api/product'
import { printImages as printImagesUtil } from '@/utils/print-images'
import ProductComponent from '@/views/modules/common/product-component'
import PreviewComponent from '@/views/modules/common/preview-component.vue'
import ImagePreview from '@/views/modules/common/image-preview.vue'
import ImageViewerMixin from '@/views/modules/common/mixins/image-viewer-mixin'
import { isAuth } from '@/utils'
export default {
  name: 'draw-management',
  mixins: [ImageViewerMixin],
  components: {
    ProductComponent,
    AddOrUpdate,
    Detail,
    PreviewComponent,
    ImagePreview
  },
  data() {
    return {
      addOrUpdateVisible: false,
      previewVisible: false,
      detailVisible: false,
      dataForm: {
        keyword: ''
      },
      optionsProducts: [],
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: []
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    // 权限判断（从 utils 导入并暴露给模板使用）
    isAuth,
    onChose() {
      this.addOrUpdateVisible = false
      this.detailVisible = false
    },
    // 查询
    search() {
      this.pageIndex = 1
      this.getDataList()
    },
    // 获取数据列表
    getDataList() {
      this.addOrUpdateVisible = false
      this.dataListLoading = true
      let params = {
        'current': this.pageIndex,
        'size': this.pageSize,
        'keyword': this.dataForm.keyword,
        'createTime': this.dataForm.createTime ? this.dataForm.createTime : null,
        'productId': this.dataForm.productId ? this.dataForm.productId : null
      }
      getDrawList(params).then(({ data }) => {
        if (data && data.code === '200') {
          this.dataList = data.data.records
          this.totalPage = Number(data.data.total)
        } else {
          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
    },
    // 新增 / 修改
    addOrUpdateHandle(id, display) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, display)
      })
    },
    // 删除
    deleteHandle(id) {
      if (!id) return
      let ids = []
      ids.push(id)
      this.$confirm(`确定删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/biz-service/drawing/delete`),
          method: 'DELETE',
          data: ids
        }).then(({ data }) => {
          if (data && data.code === '200') {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => { })
    },
    // 启用/停用
    toggleState(row) {
      if (!row || !row.drawingId) return
      const current = Number(row.state)
      const targetState = current === 1 ? 2 : 1
      const actionText = targetState === 1 ? '启用' : '停用'
      this.$confirm(`确定${actionText}该图纸?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/biz-service/drawing/update'),
          method: 'POST',
          data: {
            drawingId: row.drawingId,
            state: targetState
          }
        }).then(({ data }) => {
          if (data && data.code === '200') {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data && data.msg ? data.msg : '操作失败')
          }
        })
      }).catch(() => { })
    },
    // 预览
    previewFile(fileName, url) {
      this.previewVisible = true
      this.$nextTick(() => {
        this.$refs.preview.init(fileName, url)
      })
    },

    // 详情
    detailHandle(id) {
      this.detailVisible = true
      this.$nextTick(() => {
        this.$refs.detail.init(id)
      })
    },

    // 打印图片
    printImages(attachList = []) {
      printImagesUtil(attachList, this)
    }
  }
}
</script>

<style scoped>
.print-btn {
  color: #11C26D;
}
</style>
