<template>
  <a-card :bordered="false">
    <div v-show="visible">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="负责人">
                <a-input v-model="queryParam.keyword" placeholder="请输入设备新号/名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :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="6" :sm="24">
              <a-form-item label="起始日期">
                <a-date-picker
                  v-model="queryParam.searchStartTime"
                  style="width: 100%"
                  :format="BaseTool.Date.PICKER_NORM_DATETIME_PATTERN"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="结束日期">
                <a-date-picker
                  v-model="queryParam.searchEndTime"
                  style="width: 100%"
                  :format="BaseTool.Date.PICKER_NORM_DATETIME_PATTERN"
                />
              </a-form-item>
            </a-col>
            <a-col :md="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('check-polling-jobs-add')" type="primary" icon="plus" @click="$refs.baseModal.base()">新增</a-button>
        <a-button style="margin-left: 8px" v-if="($auth('check-spot-jobs-export') || $auth('check-polling-jobs-export'))" type="primary" icon="download" @click="doExport">导出</a-button>
        <a-button style="margin-left: 8px" v-if="($auth('check-spot-jobs-export') || $auth('check-polling-jobs-export'))" type="success" @click="handleSeven">近七日</a-button>
        <a-button style="margin-left: 8px" v-if="($auth('check-spot-jobs-export') || $auth('check-polling-jobs-export'))" type="success" @click="handleMonth">近30天</a-button>
        <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0 && ($auth('check-spot-jobs-edit') || $auth('check-polling-jobs-edit'))">
          <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"
        :columns="columns"
        :scroll="{x: 1, y: BaseTool.Constant.scrollY }"
        :data="loadData"
        :alert="options.alert"
        :rowSelection="options.rowSelection"
        showPagination="auto"
      >
        <span slot="action" slot-scope="record">
          <template>
            <a @click="handleView(record)">查看</a>
            <template v-if="record.status === DictCache.VALUE.CHECK_JOB_STATUS.NOT_EXECUTE">
              <a-divider type="vertical" />
              <a @click="handleFinish(record)">完成</a>
            </template>
            <template v-if="record.status != DictCache.VALUE.CHECK_JOB_STATUS.NOT_EXECUTE">
              <a-divider type="vertical" />
              <a @click="handleEdit(record)">修改</a>
            </template>
            <!--          <a-divider type="vertical" />-->
            <!--          <a-popconfirm v-if="$auth('check-jobs-del')" title="是否要删除该条数据？" @confirm="batchDelete(record.id)">-->
            <!--            <a>删除</a>-->
            <!--          </a-popconfirm>-->
          </template>
        </span>
        <span slot="status" slot-scope="text">
          <badge
            :status="DictCache.COLOR.JOB_STATUS[text]"
            :text="statusMap[text]" />
        </span>
        <span slot="stopFlag" slot-scope="text">
          <badge
            :status="DictCache.COLOR.YES_NO[text]"
            :text="sbStatusMap[text]" />
        </span>
      </s-table>
    </div>
    <base-form :check-type="checkType" ref="baseModal" @ok="handleOk"/>
    <detail :check-type="checkType" ref="detailModal" @ok="handleOk"/>
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseForm from './modules/BaseForm'
import Detail from './modules/Detail'
import { queryNum, getCheckJobPage, deleteCheckJobs, fetchCheckJob, exportCheckJob, executeJob } from '@/api/check/checkjob'
import BaseTool from '@/utils/tool'

export default {
  name: 'CheckJobList',
  components: {
    STable,
    Ellipsis,
    BaseForm,
    Detail
  },
  props: {
    /**
     * 检查类型： 1-负责 2-巡检
     */
    checkType: {
      type: Number,
      default: 1
    },
    filter: {
      type: Number,
      default: -1
    }
  },
  data () {
    this.names = ['负责', '巡检']
    return {
      visible: true,
      // 查询参数
      queryParam: {
        type: this.checkType,
        searchStartTime: null,
        searchEndTime: null,
        filter: this.filter
      },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return `${(this.$refs.table.localPagination.current - 1) * this.$refs.table.localPagination.pageSize + index + 1}`
          },
          checked: true,
          width: '100px'
        },
        {
          title: '设备新号',
          dataIndex: 'sbNo',
          checked: true,
          width: '150px'
        },
        {
          title: '设备名称',
          dataIndex: 'sbName',
          checked: true,
          width: '200px'
        },
        // {
        // title: '计划单号',
        // dataIndex: 'planNo',
        // checked: true
        // },
        {
          title: '任务名称',
          dataIndex: 'name',
          checked: true,
          width: '200px'
        },
        {
          title: '计划周期',
          dataIndex: 'period',
          checked: true,
          width: '150px',
          customRender: (text, record, index) => {
            return text + this.BaseTool.Table.getMapText(this.periodTypeMap, record.periodType)
          }
        },
        /*        {
          title: '计划名称',
          dataIndex: 'planName',
          checked: true
        }, */
        {
          title: '负责人',
          dataIndex: 'checkUserName',
          checked: true,
          width: '150px'
        },

        // {
        // title: '负责部件',
        // dataIndex: 'partName',
        // checked: true
        // },
        {
          title: '执行日期',
          dataIndex: 'startTime',
          checked: true,
          width: '200px'
        },
      /*  {
          title: '截至日期',
          dataIndex: 'endTime',
          checked: true,
          width: '200px'
        },*/
        {
          title: '标准工时',
          dataIndex: 'standardHours',
          checked: true,
          width: '200px'
        },
        {
          title: '实际工时',
          dataIndex: 'realHours',
          checked: true,
          width: '200px'
        },
        {
          title: '实际开始时间',
          dataIndex: 'actualStartTime',
          checked: true,
          width: '200px'
        },
        {
          title: '实际结束时间',
          dataIndex: 'actualEndTime',
          checked: true,
          width: '200px'
        },
        {
          title: '任务状态',
          dataIndex: 'status',
          width: '100px',
          fixed: 'right',
          checked: true,
          scopedSlots: { customRender: 'status' }
        },
        // {
        //  title: '是否停机',
        //  dataIndex: 'stopFlag',
        //  checked: true,
        //  scopedSlots: { customRender: 'stopFlag' }
        // },
     /*   {
          title: '创建人名称',
          dataIndex: 'createdUserName'
        },
        {
          title: '创建时间',
          dataIndex: 'createdTime',
          checked: true
        },*/
        {
          title: '操作',
          key: 'action',
          width: '150px',
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'action' },
          checked: true
        }
      ],
      // 下拉框map
      statusMap: {},
      sbStatusMap: {},
      periodTypeMap: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        parameter = {
          ...parameter,
          ...this.queryParam,
          dataScope: {
            sortBy: 'asc',
            sortName: 'start_time'
          }
        }
        return getCheckJobPage(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 () {
    // 下拉框map
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_JOB_STATUS)
    this.sbStatusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.YES_NO)
    this.periodTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_PLAN_PERIOD_TYPE)
    this.tableOption()
  },
  methods: {
    tableOption () {
      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]
      }
      deleteCheckJobs(ids).then(res => {
        this.$message.info('删除成功')
        this.handleOk()
        this.$refs.table.clearSelected()
      })
    },
    handleEdit (record) {
      fetchCheckJob({ id: record.id }).then(res => {
        const modal = this.$refs.baseModal
        modal.base(res.data)
      })
    },
    handleFinish (record) {
      fetchCheckJob({ id: record.id }).then(res => {
        const modal = this.$refs.baseModal
        modal.base(res.data)
      })
    },
    handleExecute (record) {
      executeJob({ id: record.id }).then(res => {
        this.handleOk()
      })
    },
    handleView (record) {
      this.visible = false
      fetchCheckJob({ id: record.id }).then(res => {
        const modal = this.$refs.detailModal
        modal.base(res.data)
      })
    },
    handleOk () {
      this.visible = true
      this.queryParam.searchStartTime = this.queryParam.searchStartTime ? this.queryParam.searchStartTime.format(this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN) : null
      this.queryParam.searchEndTime = this.queryParam.searchEndTime ? this.queryParam.searchEndTime.format(this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN) : null
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm () {
      this.queryParam = {
      }
      this.$refs.table.refresh(true)
    },
    handleSeven () {
      this.queryParam.searchStartTime = this.BaseTool.Date.formatter(this.getBeforeDate(0), this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      this.queryParam.searchEndTime = this.BaseTool.Date.formatter(this.getBeforeDate(-7), this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      console.log(this.queryParam.searchStartTime)
      console.log(this.queryParam.searchEndTime)
      this.$refs.table.refresh()
    },
    handleMonth () {
      this.queryParam.searchStartTime = this.BaseTool.Date.formatter(this.getBeforeDate(0), this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      this.queryParam.searchEndTime = this.BaseTool.Date.formatter(this.getBeforeDate(-30), this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      console.log(this.queryParam.searchStartTime)
      console.log(this.queryParam.searchEndTime)
      this.$refs.table.refresh()
    },
    getBeforeDate (num, time) {
      const n = num
      let d = ''
      if (time) {
        d = new Date(time)
      } else {
        d = new Date()
      }
      let year = d.getFullYear()
      let mon = d.getMonth() + 1
      let day = d.getDate()
      if (day <= n) {
        if (mon > 1) {
          mon = mon - 1
        } else {
          year = year - 1
          mon = 12
        }
      }
      d.setDate(d.getDate() - n)
      year = d.getFullYear()
      mon = d.getMonth() + 1
      day = d.getDate()
      const s = year + '-' + (mon < 10 ? ('0' + mon) : mon) + '-' + (day < 10 ? ('0' + day) : day)
      return s
    },
    doExport () {
      const parameter = {
        ...this.queryParam,
        searchStartTime: this.queryParam.searchStartTime ? this.queryParam.searchStartTime.format(this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN) : null,
        searchEndTime: this.queryParam.searchEndTime ? this.queryParam.searchEndTime.format(this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN) : null
      }
      exportCheckJob(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    }
  }
}
</script>
