<template>
  <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="dataList"
                placeholder="请选择设备类型"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="5" :md="7" :sm="24">
            <a-form-item label="部件">
              <a-tree-select
                v-model="queryParam.departId"
                :tree-data="dictOptions"
                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.repairRange" dictCode="repair_range" 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="handleAdd" type="primary" icon="plus">新增</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="deviceName" slot-scope="text,record">
          <div>{{record.deviceTypeId_dictText}}/{{record.departId_dictText}}</div>
        </template>
        <template slot="docfilePath" slot-scope="text,record">
          <div v-if="!text" @click="getRecord(record,'docfile')" >
            <a-upload v-if="!text" name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="uploadManualUrl" @change="handleUpload">
              <a-icon type="file-text"/>
            </a-upload>
          </div>
          <a-icon v-if="text" type="file-text" theme="twoTone" @click="handlePreview(text,'docfile')"/>
        </template>
        <template slot="photoPath" slot-scope="text,record">
          <div v-if="!text" @click="getRecord(record,'image')" >
            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="uploadManualUrl" @change="handleUpload">
              <a-icon type="picture"/>
            </a-upload>
          </div>
          <a-icon v-if="text"  type="picture" theme="twoTone" @click="handlePreview(text,'image')"/>
        </template>
        <template slot="videoPath" slot-scope="text,record">
          <div v-if="!text" @click="getRecord(record,'video')" >
            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="uploadManualUrl" @change="handleUpload">
              <a-icon type="video-camera"/>
            </a-upload>
          </div>
          <a-icon v-if="text"  type="video-camera" theme="twoTone" @click="handlePreview(text,'video')"/>
        </template>

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </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>

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

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ManualModal from './modules/ManualModal'
  import FilePreview from '@comp/FilePreview/index.vue'
  import { getAction, putAction } from '@api/manage'

  export default {
    name: 'ManualList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      FilePreview,
      ManualModal
    },
    data () {
      return {
        description: '作业指导书管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'作业项',
            align:"center",
            dataIndex: 'manualName'
          },
          {
            title:'设备',
            align:"center",
            dataIndex: 'deviceTypeId',
            scopedSlots: { customRender: 'deviceName' }
          },
          // {
          //   title:'部件',
          //   align:"center",
          //   dataIndex: 'departId_dictText'
          // },
          {
            title:'修程',
            align:"center",
            dataIndex: 'repairRange_dictText'
          },
          {
            title:'检修项/故障类型',
            align:"center",
            dataIndex: 'regularDetailId'
          },
          {
            title:'技术要求',
            align:"center",
            // width: 100,
            dataIndex: 'content'
          },
          {
            title:'文本资料',
            align:"center",
            dataIndex: 'docfilePath',
            scopedSlots: { customRender: 'docfilePath' }
          },
          {
            title:'图片资料',
            align:"center",
            dataIndex: 'photoPath',
            scopedSlots: { customRender: 'photoPath' }
          },
          {
            title:'视频资料',
            align:"center",
            dataIndex: 'videoPath',
            scopedSlots: { customRender: 'videoPath' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          edit: "/manual/manual/edit",
          list: "/manual/manual/list",
          delete: "/manual/manual/delete",
          deleteBatch: "/manual/manual/deleteBatch",
          exportXlsUrl: "/manual/manual/exportXls",
          importExcelUrl: "manual/manual/importExcel",
          uploadManual: "sys/upload/uploadMinioNew",
          listDeparts: '/device/buDeviceType/list/all',
          listDeviceType:"/device/buDeviceType/list/deviceType",
        },
        dictOptions:[],
        superFieldList:[],
        previewVisible: false,
        previewFileUrl: '',
        previewFileType: '',
        fileType: '',
        recordId: '',
        dataList: [],
      }
    },
    created() {
      this.getSuperFieldList();
      this.loadAllDeviceType();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      uploadManualUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.uploadManual}`;
      },
      pathMapping() {
        return {
          video: 'videoPath',
          image: 'photoPath',
          docfile: 'docfilePath',
        };
      },
    },
    watch: {
      'queryParam.deviceTypeId': {
        handler(newVal,oldVal) {
          if(newVal != null && newVal != undefined) {
            this.loadDeparts();
          }
        }
      }
    },
    methods: {
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'deviceTypeId',text:'设备',dictCode:''})
        fieldList.push({type:'string',value:'departId',text:'部件',dictCode:''})
        fieldList.push({type:'int',value:'repairRange',text:'修程',dictCode:''})
        fieldList.push({type:'string',value:'regularDetailId',text:'检修项(故障类型)',dictCode:''})
        fieldList.push({type:'Text',value:'content',text:'文字说明',dictCode:''})
        fieldList.push({type:'string',value:'docfilePath',text:'文本资料地址',dictCode:''})
        fieldList.push({type:'string',value:'photoPath',text:'图片资料地址',dictCode:''})
        fieldList.push({type:'string',value:'videoPath',text:'视频资料地址',dictCode:''})
        fieldList.push({type:'int',value:'deleteFlag',text:'是否删除0否1是',dictCode:''})
        fieldList.push({type:'string',value:'description',text:'指导书描述',dictCode:''})
        this.superFieldList = fieldList
      },
      handlePreview(fileUrl,fileType) {
        this.previewFileUrl = fileUrl;
        this.previewFileType = fileType;
        this.previewVisible = true;
      },
      // 关闭预览弹窗
      handleClosePreview() {
        this.previewVisible = false;
        this.previewFileUrl = "";
        this.previewFileType = "";
      },
      handleUpload(info) {
        if (info.file.status === "done") {
          // 上传成功
          let fileUrl = info.file.response.message; // 获取后端返回的文件 URL
          this.updateRecord(fileUrl)
        } else if (info.file.status === "error") {
          // 上传失败
          this.$message.error("文件上传失败");
        }
      },
      updateRecord(fileUrl) {
        const formData = {
          id: this.recordId,
          [this.pathMapping[this.fileType]]: fileUrl,
        };

        putAction(this.url.edit, formData).then((res) => {
          if (res.success) {
            this.$message.success('文件上传成功');
            this.loadData();
          } else {
            this.$message.warning(res.message);
          }
        });
      },
      getRecord(record,ftype){
        this.fileType = ftype;
        this.recordId = record.id
      },
      loadAllDeviceType() {
        getAction(this.url.listDeviceType).then((res) => {
          if (res.success) {
            this.dataList = this.convertToTreeSelect(res.result)
          } else {
            this.$message.error(res.message)
          }
        })
      },
      convertToTreeSelect (data) {
        return data.map(item => {
          // 创建基本节点
          const node = {
            key: item.id,
            value: item.id,
            title: item.typeName
          };
          // 如果有子节点，递归处理
          if (item.subTypes && item.subTypes.length > 0) {
            node.children = this.convertToTreeSelect(item.subTypes);
          }
          return node;
        });
      },
      loadDeparts(id) {
        getAction(this.url.listDeparts,{pid:this.queryParam.deviceTypeId,calss:2}).then((res) => {
          if (res.success) {
            if(id) {
              const targetItem = res.result.find(item => item.id === id);
              const subTypes = targetItem.subTypes;
              this.dictOptions = this.convertToTreeSelect(subTypes)
            }else {
              this.dictOptions = this.convertToTreeSelect(res.result)
            }
          } else {
            this.$message.error(res.message)
          }
        })
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>