<template>
  <a-row :gutter="24">
    <a-col :span="6">
      <a-card :bordered="false">
        <device-type-tree :max-level="3" @select-device="handleSelect" title="设备树" />
      </a-card>
    </a-col>
    <a-col :span="18">
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <!-- <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :xl="4" :lg="5" :md="7" :sm="24">
                <a-form-item label="设备">
                  <a-tree-select
                    :trigger-change="true"
                    v-model="queryParam.deviceTypeId"
                    :tree-data="deviceTypes"
                    placeholder="请选择设备类型"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="4" :lg="5" :md="7" :sm="24">
                <a-form-item label="部件">
                  <a-tree-select
                    :trigger-change="true"
                    v-model="queryParam.departTypeId"
                    :tree-data="devicePartTypes"
                    placeholder="请选择部件类型"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="4" :lg="5" :md="7" :sm="24">
                <a-form-item label="故障类型">
                  <j-dict-select-tag
                    type="list"
                    v-model="queryParam.breakdownType"
                    dictCode="breakdown_type"
                    placeholder="请选择故障类型"
                  />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div> -->
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button @click="handleAddData" type="primary" icon="plus" v-if="allowAdd">新增</a-button>
          <a-button type="primary" icon="download" @click="handleExportXls('故障知识库')">导出</a-button>
          <a-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a-button type="primary" icon="import">导入</a-button>
          </a-upload>
          <!-- 高级查询区域 -->
          <j-super-query
            :fieldList="superFieldList"
            ref="superQueryModal"
            @handleSuperQuery="handleSuperQuery"
          ></j-super-query>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
          </a-dropdown>
        </div>

        <!-- table区域-begin -->
        <div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
            <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
            >项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>

          <a-table
            ref="table"
            size="middle"
            :scroll="{ x: true }"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            class="j-table-force-nowrap"
            @change="handleTableChange"
          >
            <template slot="filePath" slot-scope="text">
              <a-icon
                v-if="getFileType(text) === 'docfile'"
                type="file-text"
                theme="twoTone"
                @click="handlePreview(text, 'docfile')"
              />
              <a-icon
                v-else-if="getFileType(text) === 'image'"
                type="picture"
                theme="twoTone"
                @click="handlePreview(text, 'image')"
              />
              <a-icon
                v-else-if="getFileType(text) === 'video'"
                type="video-camera"
                theme="twoTone"
                @click="handlePreview(text, 'video')"
              />
            </template>

            <span slot="action" slot-scope="text, record">
                <a @click="handleEdit(record)">编辑</a>

                <a-divider type="vertical" />
                <a-dropdown>
                  <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
                  <a-menu slot="overlay">
                    <a-menu-item>
                      <a @click="handleDetail(record)">详情</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                        <a>删除</a>
                      </a-popconfirm>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </span>
          </a-table>
        </div>

        <device-breakdown-dossier-modal ref="modalForm" @ok="modalFormOk"></device-breakdown-dossier-modal>
        <FilePreview
          :visible="previewVisible"
          :fileUrl="previewFileUrl"
          :fileType="previewFileType"
          @close="handleClosePreview"
        />
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import DeviceBreakdownDossierModal from './modules/DeviceBreakdownDossierModal'
import { getAction } from '@api/manage'
import FilePreview from '@comp/FilePreview/index.vue'
import DeviceTypeTree from '@/components/DeviceTypeTree/index.vue'
export default {
  name: 'DeviceBreakdownDossierList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    FilePreview,
    DeviceBreakdownDossierModal,
    DeviceTypeTree,
  },
  data() {
    return {
      selectedPartId: null,
      allowAdd: false,
      description: '故障知识库管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '设备类型',
          align: 'center',
          dataIndex: 'deviceTypeId_dictText',
        },
        {
          title: '部件类型',
          align: 'center',
          dataIndex: 'departTypeId_dictText',
        },
        {
          title: '故障类型',
          align: 'center',
          dataIndex: 'breakdownType_dictText',
        },
        {
          title: '故障编码',
          align: 'center',
          dataIndex: 'breakCode',
        },
        {
          title: '故障表现与影响',
          align: 'center',
          dataIndex: 'description',
        },
        {
          title: '故障原因',
          align: 'center',
          dataIndex: 'reason',
        },
        {
          title: '解决方法',
          align: 'center',
          dataIndex: 'solve',
        },
        {
          title: '材料1',
          align: 'center',
          dataIndex: 'instruction1',
          scopedSlots: { customRender: 'filePath' },
        },
        {
          title: '材料2',
          align: 'center',
          dataIndex: 'instruction2',
          scopedSlots: { customRender: 'filePath' },
        },
        {
          title: '材料3',
          align: 'center',
          dataIndex: 'instruction3',
          scopedSlots: { customRender: 'filePath' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      deviceTypes: [],
      devicePartTypes: [],
      url: {
        list: '/device/deviceBreakdownDossier/list',
        delete: '/device/deviceBreakdownDossier/delete',
        deleteBatch: '/device/deviceBreakdownDossier/deleteBatch',
        exportXlsUrl: '/device/deviceBreakdownDossier/exportXls',
        importExcelUrl: 'device/deviceBreakdownDossier/importExcel',
        listAllDeviceType: '/device/buDeviceType/list/all',
        listDeviceType: '/device/buDeviceType/list/deviceType',
      },
      previewVisible: false,
      previewFileUrl: '',
      previewFileType: '',
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
    this.loadAllDeviceType()
  },
  watch: {
    'queryParam.deviceTypeId': {
      handler(newVal, oldVal) {
        if (newVal != null && newVal != undefined) {
          this.loadDevicePartType()
        }
      },
    },
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    handleAddData(){
      console.log("selectedPartId",this.selectedPartId)
      this.handleAdd(this.selectedPartId)
    },
    handleSelect(key, level){
      console.log('key', key, level)
      // if(level >= 1){
        // 选择部件
      // this.selectedPartId = key[0]
      this.allowAdd = key.length !== 0;
      // } else{
      //   this.allowAdd = false
      // }
      //27号线的设备层级复杂，在此不做判断
      this.queryParam.deviceTypeId = key[0]
      this.loadData()
      this.queryParam = {}
    },
    getFileType(filePath) {
      if (!filePath) return 'xxx'
      const ext = filePath.split('.').pop().toLowerCase()
      const textExt = ['txt', 'doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'md']
      const imageExt = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
      const videoExt = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv']

      if (textExt.includes(ext)) return 'docfile'
      if (imageExt.includes(ext)) return 'image'
      if (videoExt.includes(ext)) return 'video'
      return 'xxx'
    },
    handlePreview(fileUrl, fileType) {
      this.previewFileUrl = fileUrl
      this.previewFileType = fileType
      this.previewVisible = true
    },
    // 关闭预览弹窗
    handleClosePreview() {
      this.previewVisible = false
      this.previewFileUrl = ''
      this.previewFileType = ''
    },
    convertToTreeSelect(data) {
      return data.map((item) => {
        const title = item.typeName || item.title || '未知标题'
        // 创建基本节点
        const node = {
          key: item.id,
          value: item.id,
          title: title,
        }
        // 如果有子节点，递归处理
        if (item.subTypes && item.subTypes.length > 0) {
          node.children = this.convertToTreeSelect(item.subTypes)
        }
        return node
      })
    },
    loadAllDeviceType() {
      getAction(this.url.listDeviceType).then((res) => {
        if (res.success) {
          this.deviceTypes = this.convertToTreeSelect(res.result)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    loadDevicePartType() {
      getAction(this.url.listAllDeviceType, { pid: this.queryParam.deviceTypeId, calss: 2 }).then((res) => {
        if (res.success) {
          this.devicePartTypes = this.convertToTreeSelect(res.result)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'deviceTypeId', text: '设备类型', dictCode: '' })
      fieldList.push({ type: 'string', value: 'departTypeId', text: '部件类型', dictCode: '' })
      fieldList.push({ type: 'int', value: 'breakdownType', text: '故障类型', dictCode: '' })
      fieldList.push({ type: 'string', value: 'breakCode', text: '故障编码', dictCode: '' })
      fieldList.push({ type: 'Text', value: 'description', text: '故障表现与影响', dictCode: '' })
      fieldList.push({ type: 'Text', value: 'reason', text: '故障原因', dictCode: '' })
      fieldList.push({ type: 'Text', value: 'solve', text: '解决方法', dictCode: '' })
      fieldList.push({ type: 'string', value: 'instruction1', text: '材料1', dictCode: '' })
      fieldList.push({ type: 'string', value: 'instruction2', text: '材料2', dictCode: '' })
      fieldList.push({ type: 'string', value: 'instruction3', text: '材料3', dictCode: '' })
      this.superFieldList = fieldList
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
