<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-input v-model="queryParam.zbh" placeholder="请输入设备旧号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="设备等级">
                <a-select v-model="queryParam.sblevel" placeholder="请选择">
                  <a-select-option
                    v-for="(label,value) in levelMap"
                    :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-tree-select
                  style="width: 100%"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  :treeData="treeData"
                  :treeNodeFilterProp="'title'"
                  :showSearch="true"
                  v-model="queryParam.typeId"
                  placeholder="请选择"
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="维护等级">
                <a-select v-model="queryParam.standardLevel" placeholder="请选择">
                  <a-select-option
                    v-for="(label,value) in standardLevelMap"
                    :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-select v-model="queryParam.periodType" placeholder="请选择">
                  <a-select-option
                    v-for="(label,value) in periodTypeMap"
                    :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-input v-model="queryParam.checkUserName" 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" type="success" @click="handleSeven">本周</a-button>
        <a-button style="margin-left: 8px" type="success" @click="handleMonth">本月</a-button>
        <a-button style="margin-left: 8px" type="success" @click="handleTuiCalendar">日历图</a-button>
        <a-button style="margin-left: 8px" type="primary" @click="handleExecuteBatch" v-if="selectedRowKeys.length > 0">
          <a-icon style="margin-left: 8px" type="plus"/>
          批量接收
        </a-button>
        <a-button style="margin-left: 8px" type="primary" v-if="selectedRowKeys.length > 0" @click="handleFinishBatch">
          <a-icon type="plus"/>
          批量完成
        </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="handleExecute(record)">接收</a>
            </template>
            <template v-if="record.status === DictCache.VALUE.CHECK_JOB_STATUS.EXECUTING">
              <a-divider type="vertical" />
              <a @click="handleFinish(record)">完成</a>
            </template>
            <template v-if="record.status == DictCache.VALUE.CHECK_JOB_STATUS.NOT_EXECUTE || record.status === DictCache.VALUE.CHECK_JOB_STATUS.EXECUTING">
              <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 { getCheckJobPage, deleteCheckJobs, fetchCheckJob, exportCheckJob, executeJob, executeJobBatch, finishJobBatch, queryTuiCalendarIgnores } from '@/api/check/checkjob'
import { fetchSbTypeTree } from '@/api/sb/type'
import DictCache from '@/utils/dict'

export default {
  name: 'CheckJobList',
  components: {
    STable,
    Ellipsis,
    BaseForm,
    Detail
  },
  props: {
    /**
     * 检查类型： 1-负责 2-巡检
     */
    checkType: {
      type: Number,
      default: 1
    },
    filter: {
      type: Number,
      default: -1
    },
    status: {
      type: Number,
      default: null
    },
    receiveOvertime: {
      type: Boolean,
      default: null
    },
    statusList: {
      type: Array,
      default: () => {
        return [DictCache.VALUE.CHECK_JOB_STATUS.NOT_EXECUTE, DictCache.VALUE.CHECK_JOB_STATUS.EXECUTING]
      }
    }
  },
  data () {
    this.names = ['负责', '巡检']
    return {
      visible: true,
      // 查询参数
      queryParam: {
        type: this.checkType,
        searchStartTime: null,
        searchEndTime: null,
        filter: this.filter,
        status: this.status,
        receiveOvertime: this.receiveOvertime,
        statusList: this.statusList
      },
      treeData: [],
      // 表头
      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: 'standardNo',
          checked: true,
          width: '150px'
        },
        {
          title: '设备新号',
          dataIndex: 'sbNo',
          checked: true,
          width: '150px'
        },
        {
          title: '设备名称',
          dataIndex: 'sbName',
          checked: true,
          width: '200px'
        },
        {
          title: '设备部位',
          dataIndex: 'partName',
          checked: true,
          width: '150px'
        },
        {
          title: '维护等级',
          dataIndex: 'standardLevel',
          width: '100px',
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Table.getMapText(this.standardLevelMap, text)
          }
        },
        {
          title: '任务要求',
          dataIndex: 'requirement',
          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: 'endTime',
          checked: true,
          width: '200px'
        }, */
        {
          title: '标准工时',
          dataIndex: 'standardHours',
          checked: true,
          width: '200px'
        },
        {
          title: '实际工时',
          dataIndex: 'realHours',
          checked: true,
          width: '200px'
        },
        {
          title: '实际结束时间',
          dataIndex: 'actualEndTime',
          checked: true,
          width: '200px'
        },
        {
          title: '执行日期',
          dataIndex: 'startTime',
          checked: true,
          fixed: 'right',
          width: '200px'
        },
        {
          title: '实际执行日期',
          dataIndex: 'actualStartTime',
          checked: true,
          fixed: 'right',
          width: '200px',
          customRender: (text, record, index) => {
            return (text == null ? '暂无' : this.BaseTool.Date.formatter(text, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN))
          }
        },
        {
          title: '是否延期',
          dataIndex: 'receiveOvertime',
          checked: true,
          fixed: 'right',
          width: '100px',
          customRender: (text, record, index) => {
            return ((text === null || text === 0) ? '否' : '是')
          }
        },
        {
          title: '任务状态',
          dataIndex: 'status',
          width: '100px',
          fixed: 'right',
          checked: true,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          key: 'action',
          width: '150px',
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'action' },
          checked: true
        }
      ],
      // 下拉框map
      levelMap: {},
      standardLevelMap: {},
      statusMap: {},
      sbStatusMap: {},
      periodTypeMap: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        parameter = {
          ...parameter,
          ...this.queryParam,
          dataScope: {
          }
        }
        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.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_LEVEL)
    this.standardLevelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_PLAN_LEVEL)
    fetchSbTypeTree().then(res => {
      this.treeData = res.data
    })
    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) {
      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.BaseTool.Date.formatter(this.queryParam.searchStartTime, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN) : null
      this.queryParam.searchEndTime = this.queryParam.searchEndTime ? this.BaseTool.Date.formatter(this.queryParam.searchEndTime, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN) : null
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm () {
      this.queryParam = {
        type: this.checkType,
        searchStartTime: null,
        searchEndTime: null,
        filter: this.filter,
        status: this.status,
        statusList: this.statusList
      }
      this.$refs.table.refresh(true)
    },
    handleSeven () {
      var now = new Date()
      var nowTime = now.getTime()
      var day = now.getDay()
      var oneDayTime = 24 * 60 * 60 * 1000
      // 显示周一
      var MondayTime = nowTime - (day - 1) * oneDayTime
      // 显示周日
      var SundayTime = nowTime + (7 - day) * oneDayTime
      // 初始化日期时间
      var monday = new Date(MondayTime)
      var sunday = new Date(SundayTime)
      this.queryParam.searchStartTime = this.BaseTool.Date.formatter(monday, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      this.queryParam.searchEndTime = this.BaseTool.Date.formatter(sunday, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      this.$refs.table.refresh()
    },
    handleMonth () {
      var now = new Date() // 当前日期
      var nowMonth = now.getMonth() // 当前月
      var nowYear = now.getFullYear() // 当前年
      // 本月的开始时间
      var monthStartDate = new Date(nowYear, nowMonth, 1)
      // 本月的结束时间
      var monthEndDate = new Date(nowYear, nowMonth + 1, 0)
      this.queryParam.searchStartTime = this.BaseTool.Date.formatter(monthStartDate, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      this.queryParam.searchEndTime = this.BaseTool.Date.formatter(monthEndDate, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      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
    },

    handleExecuteBatch () {
      let ids = []
      const length = this.selectedRowKeys.length
      if (length === 0) {
        this.$message.info('请选择记录')
        return
      }
      console.log(this.selectedRowKeys)
      ids = this.selectedRowKeys
      executeJobBatch(ids).then(res => {
        this.$message.info('接收成功')
        this.handleOk()
      })
    },
    handleFinishBatch () {
      let ids = []
      const length = this.selectedRowKeys.length
      if (length === 0) {
        this.$message.info('请选择记录')
        return
      }
      ids = this.selectedRowKeys
      finishJobBatch(ids).then(res => {
        this.$message.info('完成成功')
        this.handleOk()
      })
    },
    handleTuiCalendar () {
      const that = this
      queryTuiCalendarIgnores({ type: 2 }).then(res => {
        const a = document.createElement('a')
        a.target = '_blank'
        a.href = '/tui-calendar/checkJobCalendar.html?'
        localStorage.setItem('calendarList', JSON.stringify(res.data.calendarList))
        var scheduleList = res.data.scheduleList
        scheduleList.forEach((item) => {
          item.start = that.BaseTool.Moment(item.start, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
          item.end = that.BaseTool.Moment(item.end, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        })
        localStorage.setItem('scheduleList', JSON.stringify(scheduleList))
        a.click()
      })
    },
    doExport () {
      const parameter = {
        ...this.queryParam,
        searchStartTime: this.queryParam.searchStartTime,
        searchEndTime: this.queryParam.searchEndTime
      }
      exportCheckJob(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    }
  }
}
</script>
