<template>
  <section class="pro-table">
    <!-- 表格 -->
    <dee-table
      v-if="sumRowShow"
      ref="table"
      :index-row="indexRow"
      :columns="tableColums"
      :data="tableData"
      :highlight-current-row="true"
      :options="tableOptions"
      :pagination="tablePagination"
      :summary-method="getSummaries"
      :selection-row="selectionRow"
      @selection-change="selectionChange"
      @row-click="rowClick"
      @pagination-size-change="paginationSizeChange"
      @pagination-current-change="paginationCurrentChange"
    >
      <!-- 操作按钮 -->
      <section slot="header" style="display: flex; align-items: center;">
        <dee-tools style="justify-content: flex-end;" :tools="tools" mode="normal" :collapse="false" />
      </section>
    </dee-table>
  </section>
</template>
<script>
import { post } from '@/utils/http'
export default {
  data() {
    return {
      // 加载中
      loading: false,
      // 搜索条件
      form: {},
      // 分页
      tablePagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0,
        pageSizes: [5, 10, 20, 50]
      },
      // 序号
      indexRow: { title: '序号', align: 'center', width: '70' },
      // 选中表格列
      selectionRow: [],
      // 所有可动态配置的表格列
      colums: [
        { minWidth: '100', title: '任务编号', show: true, key: 'tempWorkHour.billNo', sortable: true },
        { minWidth: '100', title: '工时类型', show: true, key: 'tempWorkHour.workType', sortable: true, fildProp: {
          type: 'DictDataVO',
          rule: {
            dictTypeCode: 'WorkType' }
        }
        },
        { minWidth: '70', title: '站位', show: true, key: 'tempWorkHour.extStandPosition.extcode', sortable: true },
        { minWidth: '100', title: '工作内容', show: true, key: 'tempWorkHour.workContent', sortable: true },
        { minWidth: '100', title: '开始时间', show: true, key: 'tempWorkHour.startTime', sortable: true },
        { minWidth: '100', title: '结束时间', show: true, key: 'tempWorkHour.endTime', sortable: true },
        { minWidth: '110', title: '本人工时(min)', show: true, key: 'workHour', sortable: true },
        { minWidth: '110', title: '完成工时(min)', show: true, key: 'tempWorkHour.workHours', sortable: true },
        { minWidth: '120', title: '工时状态', show: true, key: 'tempWorkHour.state', sortable: true, formatter(row, column) {
          if (row.tempWorkHour.state === 'Audited') {
            return '己审核'
          } else if (row.tempWorkHour.state === 'Pending_Review') {
            return '待审核'
          } else if (row.tempWorkHour.state === 'TF_Reviewing') {
            return '审核中'
          }
        }
        },
        { minWidth: '120', title: '是否确认', show: true, key: 'isConfirmCode', sortable: true, formatter(row, column) {
          if (row.isConfirmCode === 'Y') {
            return '已确认'
          } else {
            return '未确认'
          }
        }
        }
      ],
      // 默认展示的表格列
      tableColums: [],
      // 表格数据
      tableData: [],
      // 表格样式配置
      tableOptions: {
        stripe: true,
        border: true,
        height: '64vh',
        showSummary: true,
        summaryMethod: this.getSummaries
      },
      // 表格选中行
      selection: [],
      // 工具栏
      tools: [
      //   {
      //   name: '新增',
      //   icon: '/icons/c-add.png',
      //   handler: {
      //     click: () => this.$emit('open')
      //   }
      // }
      ],
      sumRowShow: false
    }
  },
  created() {
    this.setDefaultColums()
  },
  mounted() {
    // this.init()
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['table'].$refs['deeTable'].doLayout()
    })
  },
  methods: {
    getSummaries(param) {
      this.showSummary = true
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index]
        }
      })
      return sums
    },
    // 设置默认展示列
    setDefaultColums() {
      this.tableColums = this.colums.filter(item => item.show)
    },
    // 初始化数据
    init(form, page) {
      console.log(form, this.form)
      // 设置数据
      this.loading = true
      this.tableData = []
      form ? this.form = form : this.form
      const params = {
        'pageFrom': this.tablePagination.currentPage,
        'pageSize': this.tablePagination.pageSize,
        'searchItems': {
          'items': [
            {
              fieldName: 'dxUserInfoId',
              operator: 'EQ',
              value: localStorage.getItem('userId')
            },
            {
              fieldName: 'tempWorkHour.billNo',
              operator: 'LIKE',
              value: form.keyWord || ''
            }
          ],
          'operator': 'AND'
        },
        'openProps': [
          {
            'name': 'tempWorkHour',
            'openProps': [
              {
                'name': 'extStandPosition'
              }
            ]
          }
        ],
        'sortItem': [
          {
            'fieldName': 'modifyTime',
            'sortOrder': 'desc'
          }
        ]
      }
      if (form.state) {
        params.searchItems.items.push({
          'fieldName': 'tempWorkHour.state',
          'operator': 'EQ',
          'value': form.state
        })
      }
      if (form.isConfirmCode) {
        params.searchItems.items.push({
          'fieldName': 'isConfirmCode',
          'operator': 'EQ',
          'value': form.isConfirmCode
        })
      }
      if (form.actualEnd && form.actualEnd.length > 0) {
        params.searchItems.items.push({
          'fieldName': 'tempWorkHour.endTime',
          'operator': 'BTWN',
          'value': form.actualEnd[0],
          'value1': form.actualEnd[1]
        })
      }
      // 发送请求
      this.$api.searchApi('TempWorkHourAssign', params).then(res => {
        this.tableData = res.items.content
        this.tablePagination.total = res.items.totalElements
      }).catch(err => console.log(err)).finally(() => {
        this.loading = false
        this.$nextTick(() => {
          this.sumRowShow = true
        })
      })
    },
    // 确认
    confirmHandle() {
      if (!this.selectionRow.length) return this.$utils.showMessageWarning('请选择需要操作的数据')
      const confirmFlag = this.selectionRow.find(row => (row.isConfirmCode === 'Y' || row.isConfirmCode === '已确认'))
      if (confirmFlag) return this.$utils.showMessageWarning('已确认的数据无法再次进行确认,请重新选择')
      this.$confirm('是否对选中的数据进行确认?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const params = []
        this.selectionRow.map(row => {
          params.push({
            id: row.id,
            operator: 'MODIFY',
            isConfirmCode: 'Y'
          })
        })
        post(`/TempWorkHourAssign/recursions`, params).then(res => {
          this.$utils.showMessageSuccess('确认成功')
          this.tablePagination.currentPage = 1
          this.init(this.form)
        }).catch(err => {
          console.log(err)
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消确认'
        })
      })
    },
    // 选择项发生改变
    selectionChange(val) {
      this.selectionRow = val
    },
    // 分页每页条数切换
    paginationSizeChange(size) {
      this.tablePagination.pageSize = size
      this.init(this.form)
    },
    // 分页当前页切换
    paginationCurrentChange(page) {
      this.tablePagination.currentPage = page
      this.init(this.form)
    },
    // 行点击
    rowClick(row) {
      this.$emit('rowClick', row)
    }
  }
}
</script>