<template>
  <a-row :gutter="24">
    <a-col :lg="6" :md="7" :sm="24" :xl="5">
      <a-card title="设备" :bordered="true">
        <a-tree :tree-data="deviceTypes" @select="handleSelect" />
      </a-card>
    </a-col>
    <a-col :lg="18" :md="17" :sm="24" :xl="19" style="padding-left: 0">
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :lg="7" :md="8" :sm="24" :xl="6">
                <a-form-item label="修程">
                  <j-dict-select-tag
                    v-model="queryParam.rapairRange"
                    dictCode="repair_range"
                    placeholder="请选择修程"
                  />
                </a-form-item>
              </a-col>
              <a-col :lg="7" :md="8" :sm="24" :xl="6">
                <span class="table-page-search-submitButtons" style="float: left; overflow: hidden">
                  <a-button icon="search" type="primary" @click="searchQuery">查询</a-button>
                  <a-button icon="reload" style="margin-left: 8px" type="primary" @click="searchReset">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button :disabled="canAdd !== true" icon="plus" type="primary" @click="handleAdd(selectedDeviceTypeId)"
            >新增
          </a-button>
<!--          <a-button icon="download" type="primary" @click="handleExportXls('检修规程')">导出</a-button>
          <a-upload
            :action="importExcelUrl"
            :headers="tokenHeader"
            :multiple="false"
            :showUploadList="false"
            name="file"
            @change="handleImportExcel"
          >
            <a-button icon="import" type="primary">导入</a-button>
          </a-upload>-->
          <!-- 高级查询区域 -->
          <j-super-query
            ref="superQueryModal"
            :fieldList="superFieldList"
            @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"
            :scroll="{ x: true }"
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            :pagination="ipagination"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            bordered
            class="j-table-force-nowrap"
            rowKey="id"
            size="middle"
            @change="handleTableChange"
          >
            <a-table
              slot="expandedRowRender"
              slot-scope="record"
              rowKey="id"
              :scroll="{ y: 450 }"
              width="500px"
              :columns="detailColumns"
              :dataSource="record.regularDetailList"
              :indentSize="0"
              :pagination="false"
            >
              <template #customColumn="text">
                <div class="custom-column" :style="{maxWidth: '140px'}">{{ text }}</div>
              </template>
              <template #content="text">
                <div class="custom-column" :style="{maxWidth: '360px'}">
                  {{ text }}
                </div>
              </template>
              <template slot="personalizedInspection" slot-scope="text">
                <a-icon v-if="text === 1" type="check" /><!--专检-->
              </template>
              <template slot="mutualInspection" slot-scope="text">
                <a-icon v-if="text === 2" type="check" /><!--互检-->
              </template>
              <template slot="measure" slot-scope="text">
                <a-icon v-if="text === '1'" type="check" />
              </template>

              <span slot="sub-action" slot-scope="text, record">
                <a @click="handleEditDetail(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="handleRegularDetail(record)">详情</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a-popconfirm
                        title="确定删除吗?"
                        :overlayStyle="{ width: '144px' }"
                        @confirm="() => handleDelete(record.id)"
                      >
                        <a>删除</a>
                      </a-popconfirm>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </span>
            </a-table>

            <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
                :preview="record.id"
                :src="getImgView(text)"
                alt=""
                height="25px"
                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" icon="download" size="small" type="primary" @click="downloadFile(text)">
                下载
              </a-button>
            </template>

            <span slot="action" slot-scope="text, record">
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleAddDetail(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-upload
                      :action="importDetailExcelUrl + '?pid=' + record.id"
                      :headers="tokenHeader"
                      :multiple="false"
                      :showUploadList="false"
                      name="file"
                      @change="handleImportExcel"
                    >
                      <a>导入</a>
                    </a-upload>
                  </a-menu-item>
                  <a-menu-item>
                    <a @click="handleExportXls('检修规程')">导出</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a-popconfirm
                      title="确定删除吗?"
                      :overlayStyle="{ width: '144px' }"
                      @confirm="() => handleDelete(record.id)"
                    >
                      <a>删除</a>
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </span>

          </a-table>
        </div>

        <regular-modal ref="modalForm" @ok="modalFormOk"></regular-modal>
        <regular-detail-modal ref="detailModal" @ok="modalFormOk"></regular-detail-modal>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import RegularModal from './modules/RegularModal'
import DeviceTree from '@comp/DeviceTree/index.vue'
import RegularDetailModal from '@views/regular/modules/RegularDetailModal.Style#Drawer.vue'
import RegularMaterialModal from '@views/regular/modules/RegularMaterialModal.vue'
import { getAction } from '@api/manage'

export default {
  name: 'RegularList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    RegularMaterialModal,
    RegularDetailModal,
    DeviceTree,
    RegularModal,
  },
  data() {
    return {
      canAdd: false,
      description: '检修规程管理页面',
      selectedDeviceTypeId: null,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 55,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '设备',
          align: 'center',
          dataIndex: 'deviceTypeId_dictText',
        },
        {
          title: '修程',
          align: 'center',
          dataIndex: 'rapairRange_dictText',
        },
        {
          title: '定义',
          align: 'center',
          dataIndex: 'ramark',
        },
        {
          title: '检修周期',
          align: 'center',
          width: 100,
          dataIndex: 'maintenanceCycle',
          customRender: function (t, r, index) {
            return `${t} ± ${r.bias}`
          },
        },
        {
          title: '作业时长',
          align: 'center',
          width: 100,
          dataIndex: 'duration',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          // fixed: 'right',
          width: 145,
          scopedSlots: { customRender: 'action' },
        },
      ],
      detailColumns: [
        {
          title: '#',
          align: 'center',
          width: 55,
          dataIndex: 'dispOrder',
        },
        {
          title: '检查类型',
          align: 'center',
          width: 90,
          dataIndex: 'checkType_dictText',
        },
        {
          title: '部件',
          align: 'center',
          width: 140,
          dataIndex: 'depard_dictText',
          scopedSlots: { customRender: 'customColumn' },
        },
        {
          title: '技能级别',
          align: 'center',
          width: 100,
          dataIndex: 'skillLevel_dictText',
        },
        {
          title: '检修要求',
          align: 'center',
          dataIndex: 'content',
          width: 360,
          scopedSlots: { customRender: 'content' },
        },
        {
          title: '修程',
          align: 'center',
          width: 75,
          dataIndex: 'repairRange_dictText',
        },
        {
          title: '专检',
          align: 'center',
          width: 60,
          dataIndex: 'personalizedInspection',
          scopedSlots: { customRender: 'personalizedInspection' },
        },
        {
          title: '互检',
          align: 'center',
          width: 60,
          dataIndex: 'mutualInspection',
          scopedSlots: { customRender: 'mutualInspection' },
        },
        {
          title: '检查',
          align: 'center',
          width: 60,
          dataIndex: 'inspection_dictText',
        },
        {
          title: '测量',
          align: 'center',
          width: 60,
          dataIndex: 'measure',
          scopedSlots: { customRender: 'measure' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'sub-action' },
        },
      ],
      url: {
        list: '/regular/regular/list',
        delete: '/regular/regular/delete',
        deleteBatch: '/regular/regular/deleteBatch',
        exportXlsUrl: '/regular/regularDetail/exportXls',
        importExcelUrl: 'regular/regular/importExcel',
        listDeviceType: '/regular/regular/deviceTypeTree',
        importDetailExcelUrl: 'regular/regularDetail/importExcel',
      },
      dictOptions: {},
      deviceTypes: [],
      superFieldList: [],
    }
  },
  beforeCreate() {
    this.disableMixinCreated = true
  },
  created() {
    this.getSuperFieldList()
    this.loadAllDeviceType()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    importDetailExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importDetailExcelUrl}`
    }
  },
  methods: {
    handleImport(record) {},
    handleAddDetail(record) {
      this.$refs.detailModal.add(record)
      this.$refs.detailModal.title = '新增检修项'
      this.$refs.detailModal.disableSubmit = false
    },
    handleEditDetail(record) {
      this.$refs.detailModal.edit(record)
      this.$refs.detailModal.title = '编辑检修项'
      this.$refs.detailModal.disableSubmit = false
    },
    handleRegularDetail(record) {
      this.$refs.detailModal.edit(record)
      this.$refs.detailModal.title = '详情'
      this.$refs.detailModal.disableSubmit = true
    },
    handleSelect(id, level) {
    //&& !level.node.$options.propsData.dataRef.children
    console.log('选择设备', id, level)
      if (id) {
        console.log('选择设备', id, level)
        this.selectedDeviceTypeId = id
        this.canAdd = true
        this.queryParam.deviceTypeId = id
        this.loadData()
      } else {
        this.selectedDeviceTypeId = null
        this.queryParam.deviceTypeId = null
        this.canAdd = false
        this.dataSource = []
      }
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'deviceTypeId', text: '设备', dictCode: '' })
      fieldList.push({ type: 'int', value: 'rapairRange', text: '修程', dictCode: 'repair_range' })
      fieldList.push({ type: 'string', value: 'ramark', text: '定义', dictCode: '' })
      fieldList.push({ type: 'int', value: 'maintenanceCycle', text: '检修周期', dictCode: '' })
      fieldList.push({ type: 'int', value: 'bias', text: '允许偏差', dictCode: '' })
      fieldList.push({ type: 'int', value: 'duration', text: '作业时长', dictCode: '' })
      this.superFieldList = fieldList
    },
    loadAllDeviceType() {
      getAction(this.url.listDeviceType, { calss: '1' }).then((res) => {
        if (res.success) {
          this.deviceTypes = this.convertToTreeSelect(res.result)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    convertToTreeSelect(data) {
      return data.map((item) => {
        const title = item.typeName + '(' + item.typeCode + ')' || 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
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.custom-column {
  white-space: normal; /* 允许换行 */
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
