<template>
  <a-card :bordered="false">
    <a-row :gutter="8" v-show="visible">
      <a-col :span="24">
        <div>
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">
                <a-col :md="8" :sm="24">
                  <a-form-item label="关键字">
                    <a-input v-model.trim="queryParam.keyword" placeholder="请输入设备名称"/>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="设备新号">
                    <a-input v-model.trim="queryParam.no"/>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="设备型号">
                    <a-input v-model.trim="queryParam.model"/>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="测量设备编号">
                    <a-input v-model.trim="queryParam.cardNo" />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="使用部门">
                    <a-input v-model.trim="queryParam.useDept" />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="出厂编号">
                    <a-input v-model.trim="queryParam.zzh"/>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="管理状态">
                    <a-select v-model="queryParam.status" placeholder="请选择">
                      <a-select-option
                        v-for="(label,value) in statusMap"
                        :key="value"
                        :label="label"
                        :value="parseInt(value)">{{ label }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="检定日期范围">
                    <a-range-picker v-model="dateRangeCheck" :style="{width: '256px'}" />
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="24">
                  <a-form-item label="有效日期范围">
                    <a-range-picker v-model="dateRange" :style="{width: '256px'}" />
                  </a-form-item>
                </a-col>
                <a-col :md="6 || 24" :sm="24">
                  <span class="table-page-search-submitButtons">
                    <a-button type="primary" @click="handleOk()">查询</a-button>
                    <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>

          <div class="table-operator">
            <a-button v-if="$auth('sb-infos-add')" type="primary" icon="plus" @click="handleAdd">新增</a-button>
            <a-button style="margin-left: 8px" v-if="$auth('sb-infos-export')" type="primary" icon="upload" @click="doImport">新增导入</a-button>
            <a-button style="margin-left: 8px" v-if="$auth('sb-infos-export')" type="primary" icon="upload" @click="doImportForUpdate">修改导入</a-button>
            <a-button style="margin-left: 8px" v-if="$auth('sb-infos-export')" type="primary" icon="download" @click="doExport">导出</a-button>
            <a-button style="margin-left: 8px" v-if="$auth('sb-infos-export')" type="primary" icon="download" @click="doExportMeasure">检定导出</a-button>
            <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0 && $auth('sb-infos-del')">
              <a-menu slot="overlay">
                <a-popconfirm title="是否要删除所选数据？" @confirm="batchDelete()">
                  <a-menu-item key="1"><a-icon type="delete" /><a>删除</a></a-menu-item>
                </a-popconfirm>
              </a-menu>
              <a-button style="margin-left: 8px">
                批量操作 <a-icon type="down" />
              </a-button>
            </a-dropdown>
          </div>

          <s-table
            ref="table"
            size="default"
            rowKey="id"
            :widthSpace="true"
            :columns="columns"
            :data="loadData"
            :alert="options.alert"
            :rowSelection="options.rowSelection"
            :scroll="{x: 1500, y: BaseTool.Constant.scrollY}"
            showPagination="auto"
          >
            <span slot="action" slot-scope="record">
              <template>
                <div>
                  <a-dropdown>
                    <a-menu slot="overlay">
                      <a-menu-item key="0">
                        <a @click="handleMeasure(record)">查看</a>
                      </a-menu-item>
                      <a-menu-item key="1">
                        <a v-if="$auth('sb-infos-edit')" @click="handleEdit(record)">修改</a>
                      </a-menu-item>
                    </a-menu>
                    <a-button> 操作 <a-icon type="down" /> </a-button>
                  </a-dropdown>
                </div>
              </template>
            </span>
            <span slot="status" slot-scope="text">
              <badge
                :status="DictCache.COLOR.SB_INFO_STATUS[text]"
                :text="statusMap[text]" />
            </span>
          </s-table>
        </div>

      </a-col>
    </a-row>
    <base-form ref="baseModal" @ok="handleOk"/>
    <detail ref="detailModal" @ok="handleOk"/>
    <download-modal ref="downloadModal"/>
    <import-form-update ref="importModalUpdate" @ok="handleOk"/>
    <preview-modal ref="previewModal"/>
    <import-form-add ref="importModal" @ok="handleOk"/>
    <detail-sb-measure ref="detailSbMeasureModal" @ok="handleOk"/>
  </a-card>

</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseForm from './modules/BaseForm'
import Detail from './modules/Detail'
import DownloadModal from '@/views/download/DownloadModal'
import PreviewModal from '@/views/preview/PreviewModal'
import {
  getSbInfoPage,
  deleteSbInfos,
  fetchSbInfo,
  exportSbInfoMeasure,
  exportSbInfoMeasureTwo
} from '@/api/sb/measure'
import { fetchSbTypeTree } from '@/api/sb/type'
import ImportFormAdd from './modules/ImportFormAdd'
import ImportFormUpdate from './modules/ImportFormUpdate'
import DetailSbMeasure from '@/views/sb/measurelog/modules/DetailSbCheck'

export default {
  name: 'MeasureSbInfoList',
  components: {
    STable,
    Ellipsis,
    BaseForm,
    Detail,
    DownloadModal,
    PreviewModal,
    ImportFormAdd,
    ImportFormUpdate,
    DetailSbMeasure
  },
  props: {
    seatNumber: {
      type: Number,
      default: null
    },
    statusList: {
      type: Array,
      default: () => {
        return null
      }
    }
  },
  data () {
    return {
      dateRange: [],
      dateRangeCheck: [],
      deptUserList: [],
      // 查询参数
      queryParam: {
        seatNumber: this.seatNumber,
        statusList: this.statusList
      },
      depreciationTypeMap: {},
      visible: true,
      statusMap: {},
      measureMap: {},
      expandedKeys: [],
      selectedKeys: [],
      sourceTypeMap: {},
      treeData: [],
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 120,
          checked: true,
          customRender: (text, record, index) => {
            return `${(this.$refs.table.localPagination.current - 1) * this.$refs.table.localPagination.pageSize + index + 1}`
          }
        },
        {
          title: '测量设备编号',
          dataIndex: 'cardNo',
          width: 150,
          checked: true
        },
        {
          title: '设备名称',
          checked: true,
          width: 200,
          dataIndex: 'name'
        },
        {
          title: '出厂编号',
          checked: true,
          width: 200,
          dataIndex: 'zzh'
        },
        {
          title: '规格型号',
          checked: true,
          width: 200,
          dataIndex: 'model'
        },
        {
          title: '要求准确度等级',
          dataIndex: 'zz',
          width: 150,
          checked: true
        },

        {
          title: '使用部门',
          checked: true,
          width: 200,
          dataIndex: 'useDept'
        },
        {
          title: '使用地点',
          checked: true,
          width: 200,
          dataIndex: 'cph'
        },
        {
          title: '准确度等级',
          checked: true,
          width: 200,
          dataIndex: 'fdjxh'
        },
        {
          title: '检定日期',
          checked: true,
          width: 200,
          dataIndex: 'checkDate'
        },
        {
          title: '检定周期',
          checked: true,
          width: 200,
          dataIndex: 'checkPeriod',
          customRender: (text, record, index) => {
            if (record.checkPeriod == null) {
              return '未知'
            } else {
              return text + '月'
            }
          }
        },
        {
          title: '有效日期',
          dataIndex: 'nextCheckDate',
          width: 150,
          checked: true
        },
        {
          title: '生产厂商',
          dataIndex: 'producerId',
          width: 150,
          checked: true
        },
        {
          title: '检定单位',
          dataIndex: 'dph',
          width: 150,
          checked: true
        },
        {
          title: '检定人',
          dataIndex: 'zaiz',
          width: 150,
          checked: true
        },
        {
          title: '检定结论',
          dataIndex: 'rlType',
          width: 150,
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Object.getField(this.measureMap, text)
          }
        },
        {
          title: '是否周检',
          dataIndex: 'color',
          width: 150,
          checked: true,
          customRender: (text, record, index) => {
            if (text === 0) {
              return '否'
            } else {
              return '是'
            }
          }
        },
        {
          title: '检定证书编号',
          dataIndex: 'sbdh',
          width: 150,
          checked: true
        },
        {
          title: '检定校准记录',
          dataIndex: 'zbh',
          width: 150,
          checked: true
        },
        {
          title: '预警天数',
          dataIndex: 'seatNumber',
          width: 150,
          checked: true
        },
        {
          title: '是否固定资产',
          dataIndex: 'isFinancing',
          width: 150,
          checked: true,
          customRender: (text, record, index) => {
            if (text === 0) {
              return '否'
            } else {
              return '是'
            }
          }
        },
        {
          title: '固定资产编号',
          dataIndex: 'financingNo',
          width: 150,
          checked: true
        },
        {
          title: '设备新号',
          dataIndex: 'no',
          width: 150,
          checked: true
        },
        {
          title: '检定截止',
          dataIndex: 'restDay',
          width: 100,
          fixed: 'right',
          checked: true,
          customRender: (text, record, index) => {
            if (record.nextCheckDate == null) {
              return '未知'
            } else {
              return this.BaseTool.Date.getCountBetween(new Date(), record.nextCheckDate, 1) + '天'
            }
          }
        },
        {
          title: '管理状态',
          checked: true,
          dataIndex: 'status',
          width: 100,
          fixed: 'right',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          key: 'action',
          checked: true,
          fixed: 'right',
          align: 'center',
          width: '100',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        parameter = {
          ...parameter,
          ...this.queryParam,
          dataScope: {
            sortBy: 'asc,asc',
            sortName: 'status,next_check_date'
          }
        }
        return getSbInfoPage(Object.assign(parameter, this.queryParam))
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  created () {
    this.tableOption()
    this.measureMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_MEASURE_RESULT)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_MEASURE_STATUS)
    this.isFinancingMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_IS_FINANCING)
  },
  methods: {
    tableOption () {
      this.setTree()
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: false,
                name: record.id
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    batchDelete (id) {
      let ids = []
      if (this.BaseTool.String.isBlank(id)) {
        const length = this.selectedRows.length
        if (length === 0) {
          this.$message.info('请选择要删除的记录')
          return
        }
        ids = this.selectedRows.map(item => item.id)
      } else {
        ids = [id]
      }
      deleteSbInfos(ids).then(res => {
        this.$message.info('删除成功')
        this.handleOk()
        this.$refs.table.clearSelected()
      })
    },
    handleEdit (record) {
      fetchSbInfo({ id: record.id }).then(res => {
        this.visible = false
        const modal = this.$refs.baseModal
        modal.base(res.data)
      })
    },
    handleAdd () {
      this.visible = false
      this.$refs.baseModal.base()
    },
    handleAddRelate () {
      this.visible = false
      this.$refs.baseModal.base()
    },
    handleMeasure (record) {
      this.visible = false
      const modal = this.$refs.detailSbMeasureModal
      modal.base(record)
    },
    handleView (record) {
      fetchSbInfo({ id: record.id }).then(res => {
        this.visible = false
        const modal = this.$refs.detailModal
        modal.base(res.data)
      })
    },
    handleOk () {
      this.visible = true
      this.setTree()
      if (this.dateRange != null) {
        this.queryParam.nextCheckDateStart = this.dateRange[0]
        this.queryParam.nextCheckDateEnd = this.dateRange[1]
        this.queryParam.nextCheckDateStart = this.queryParam.nextCheckDateStart ? this.queryParam.nextCheckDateStart.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
        this.queryParam.nextCheckDateEnd = this.queryParam.nextCheckDateEnd ? this.queryParam.nextCheckDateEnd.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
      }
      if (this.dateRangeCheck != null) {
        this.queryParam.checkDateStart = this.dateRangeCheck[0]
        this.queryParam.checkDateEnd = this.dateRangeCheck[1]
        this.queryParam.checkDateStart = this.queryParam.checkDateStart ? this.queryParam.checkDateStart.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
        this.queryParam.checkDateEnd = this.queryParam.checkDateEnd ? this.queryParam.checkDateEnd.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
      }
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm () {
      this.queryParam = {
        seatNumber: this.seatNumber,
        statusList: this.statusList
      }
      this.dateRange = []
      this.dateRangeCheck = []
      this.visible = true
      this.$refs.table.refresh(true)
    },
    doExport () {
      if (this.dateRange != null) {
        this.queryParam.nextCheckDateStart = this.dateRange[0]
        this.queryParam.nextCheckDateEnd = this.dateRange[1]
        this.queryParam.nextCheckDateStart = this.queryParam.nextCheckDateStart ? this.queryParam.nextCheckDateStart.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
        this.queryParam.nextCheckDateEnd = this.queryParam.nextCheckDateEnd ? this.queryParam.nextCheckDateEnd.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
      }
      if (this.dateRangeCheck != null) {
        this.queryParam.checkDateStart = this.dateRangeCheck[0]
        this.queryParam.checkDateEnd = this.dateRangeCheck[1]
        this.queryParam.checkDateStart = this.queryParam.checkDateStart ? this.queryParam.checkDateStart.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
        this.queryParam.checkDateEnd = this.queryParam.checkDateEnd ? this.queryParam.checkDateEnd.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
      }
      const parameter = {
        ...this.queryParam
      }
      exportSbInfoMeasure(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    doExportMeasure () {
      if (this.dateRange != null) {
        this.queryParam.nextCheckDateStart = this.dateRange[0]
        this.queryParam.nextCheckDateEnd = this.dateRange[1]
        this.queryParam.nextCheckDateStart = this.queryParam.nextCheckDateStart ? this.queryParam.nextCheckDateStart.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
        this.queryParam.nextCheckDateEnd = this.queryParam.nextCheckDateEnd ? this.queryParam.nextCheckDateEnd.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
      }
      if (this.dateRangeCheck != null) {
        this.queryParam.checkDateStart = this.dateRangeCheck[0]
        this.queryParam.checkDateEnd = this.dateRangeCheck[1]
        this.queryParam.checkDateStart = this.queryParam.checkDateStart ? this.queryParam.checkDateStart.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
        this.queryParam.checkDateEnd = this.queryParam.checkDateEnd ? this.queryParam.checkDateEnd.format(this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
      }
      const parameter = {
        ...this.queryParam
      }
      exportSbInfoMeasureTwo(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    setTree (record = {}) {
      fetchSbTypeTree().then(res => {
        this.treeData = res.data
      })
    },
    onSelect: function (selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.queryParam.typeId = selectedKeys.length > 0 ? selectedKeys[0] : ''
      this.$refs.table.refresh(true)
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    doImport () {
      this.$refs.importModal.base(null, null)
    },
    doImportForUpdate () {
      this.$refs.importModalUpdate.base(null, null)
    }
  }
}
</script>
