<!--
 * @Author: gtz
 * @Date: 2022-03-11 11:17:22
 * @LastEditors: gtz
 * @LastEditTime: 2022-07-27 11:12:40
 * @Description: file content
 * @FilePath: \mt-bus-fe\src\views\FactoryManage\ShiftManager.vue
-->
<template>
  <div class="app-container">
    <head-form
      :form-config="headFormConfig"
      @headBtnClick="btnClick"
      @importFile="importFile"
      @importFileError="importFileError"
    />
    <base-table
      :top-btn-config="topBtnConfig"
      :page="listQuery.current"
      :limit="listQuery.size"
      :table-config="tableProps"
      :table-data="dataList"
      :is-loading="listLoading"
      @clickTopBtn="clickTopBtn"
    >
      <!-- :toggle-custom-index="true" -->
      <method-btn slot="handleBtn" :width="trueWidth" :method-list="tableBtn" @clickBtn="handleClick" />
    </base-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList()"
    />
    <shiftManager-add
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      :work-shop-list="workShopList"
      :team-list="teamList"
      :shift-list="shiftList"
      @refreshDataList="getList"
    />
    <shiftManager-import
      v-if="importVisible"
      ref="import"
      :data-list-in="importFileData"
      :work-shop-list="workShopList"
      :team-list="teamList"
      :shift-list="shiftList"
      @refreshDataList="getList"
    />
  </div>
</template>

<script>
import Vue from 'vue'
import i18n from '@/lang'
import { list, del, getWorkShopList, getShiftList, getTeamList, getExcelExample } from '@/api/team-manage/shift'
import HeadForm from '@/components/basicData/HeadForm'
import BaseTable from '@/components/BaseTable'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import MethodBtn from '@/components/BaseTable/subcomponents/MethodBtn'
import shiftManagerAdd from './components/ShiftManager-add'
// import shiftManagerLine from './components/ShiftManager-line'
// import shiftManagerDetail from './components/ShiftManager-detail'
import shiftManagerStatus from './components/ShiftManager-status'
import shiftManagerImport from './components/ShiftManager-import'
import { timeFormatter } from '@/filters'
/**
 * 表格表头配置项 TypeScript接口注释
 * tableConfig<ConfigItem> = []
 *
 * Interface ConfigItem = {
 *  prop: string,
 *  label: string,
 *  width: string,
 *  align: string,
 *  subcomponent: function,
 *  filter: function
 * }
 *
 *
 */
const topBtnConfig = [
  {
    type: 'add',
    btnName: 'btn.add'
  }
]

const tableBtn = [
  {
    type: 'edit',
    btnName: 'btn.edit'
  },
  {
    type: 'detail',
    btnName: 'btn.detail'
  },
  {
    type: 'delete',
    btnName: 'btn.delete'
  }
]
const tableProps = [
  {
    prop: 'planHandoverTime',
    label: i18n.t('module.teamManager.shift.onlineTime'),
    filter: timeFormatter,
    align: 'center'
  },
  {
    prop: 'planOfflineTime',
    label: i18n.t('module.teamManager.shift.offlineTime'),
    filter: timeFormatter,
    align: 'center'
  },
  {
    prop: 'className',
    label: i18n.t('module.teamManager.shift.teamName'),
    align: 'center'
  },
  {
    prop: 'classCode',
    label: i18n.t('module.teamManager.shift.teamCode'),
    align: 'center'
  },
  {
    prop: 'planSection',
    label: i18n.t('module.teamManager.shift.lineOrProcess'),
    align: 'center',
    // subcomponent: shiftManagerLine
    subcomponent: {
      props: {
        injectData: {
          type: Object,
          default: () => ({})
        }
      },
      render: function(h) {
        const processStr = this.injectData['planSection'].join(',')
        return h(
          'el-popover',
          {
            props: {
              width: 200,
              trigger: 'hover',
              title: i18n.t('module.teamManager.shift.readMore'),
              placement: 'top',
              content: processStr
            },
            style: {
              cursor: 'pointer'
            }
          },
          [h('span', { slot: 'reference' }, processStr.length > 10 ? processStr.slice(0, 10) + '...' : processStr)]
        )
      }
    }
  },
  {
    prop: 'planTeamName',
    label: i18n.t('module.teamManager.shift.handoverTeam'),
    align: 'center'
  },
  {
    prop: 'planTeamLeader',
    label: i18n.t('module.teamManager.shift.handoverMonitor'),
    align: 'center'
  },
  {
    prop: 'handoverStatus',
    label: i18n.t('module.teamManager.shift.status'),
    align: 'center',
    subcomponent: shiftManagerStatus
  },
  // {
  //   prop: 'id',
  //   label: i18n.t('module.teamManager.shift.detail'),
  //   align: 'center',
  //   subcomponent: shiftManagerDetail
  // },
  {
    prop: 'remark',
    label: i18n.t('module.teamManager.shift.remark'),
    align: 'center'
  }
]

export default {
  name: 'ShiftPlanManage',
  components: { Pagination, BaseTable, MethodBtn, HeadForm, shiftManagerAdd, shiftManagerImport },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      topBtnConfig,
      importVisible: false,
      addOrUpdateVisible: false,
      tableBtn,
      trueWidth: 120,
      tableProps,
      dataList: [],
      workShopList: [],
      teamList: [],
      shiftList: [],
      importFileData: [],
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 20,
        planHandoverBegTime: null,
        planHandoverEndTime: null,
        planTeamId: null
      },
      headFormConfig: [
        {
          type: 'datePicker',
          label: this.$t('module.teamManager.shift.planTime'),
          dateType: 'daterange',
          rangeSeparator: '-',
          startPlaceholder: this.$t('module.orderManage.order.StartTime'),
          endPlaceholder: this.$t('module.orderManage.order.EndTime'),
          param: 'timeSlot'
        },
        {
          type: 'button',
          btnName: 'btn.search',
          name: 'search',
          color: 'primary'
        },
        {
          type: 'button',
          btnName: 'btn.exportTemplate',
          name: 'exportTemplate',
          color: 'success'
        },
        {
          type: 'uploadButton',
          btnName: 'btn.import',
          name: 'import',
          color: 'success',
          action: '/api/team/team-record-plan/importTeamPlan'
        }
      ],
      headFormValue: {},
      index: 1
    }
  },
  created() {
    const params = {
      current: 1,
      size: 500
    }
    getWorkShopList(params).then(response => {
      if (response.code === 0 && response.data.records) {
        this.workShopList = response.data.records
        Vue.set(this.tableProps[8], 'workShopList', this.workShopList)
        getTeamList(params).then(res => {
          if (res.code === 0 && res.data.records) {
            this.teamList = res.data.records
            Vue.set(this.tableProps[8], 'teamList', this.teamList)
            // Vue.set(this.keyName[1], 'option', this.teamList.map(item => {
            //   return { value: item.id, label: item.name }
            // }))
            getShiftList(params).then(res => {
              this.shiftList = res.data.records
              Vue.set(this.tableProps[8], 'shiftList', this.shiftList)
              this.getList()
            })
          }
        })
      }
    })
  },
  methods: {
    handleClick(raw) {
      if (raw.type === 'delete') {
        this.$confirm(`${this.$t('module.basicData.visual.TipsBefore')}?`, this.$t('module.basicData.visual.Tips'), {
          confirmButtonText: this.$t('module.basicData.visual.confirmButtonText'),
          cancelButtonText: this.$t('module.basicData.visual.cancelButtonText'),
          type: 'warning'
        })
          .then(() => {
            del({ id: raw.data.id }).then(response => {
              this.$message({
                message: this.$t('module.basicData.visual.success'),
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getList()
                }
              })
            })
          })
          .catch(() => {})
      } else if (raw.type === 'edit') {
        this.addNew(raw.data.id)
      } else if (raw.type === 'detail') {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(raw.data.id, true)
        })
      }
    },
    getList() {
      this.importVisible = false
      this.addOrUpdateVisible = false
      this.listLoading = true
      this.listQuery.planHandoverBegTime = this.headFormValue.timeSlot ? this.headFormValue.timeSlot[0] : null
      this.listQuery.planHandoverEndTime = this.headFormValue.timeSlot ? this.headFormValue.timeSlot[1] : null
      this.$nextTick(() => {
        list(this.listQuery).then(response => {
          if (response.data.records) {
            this.dataList = response.data.records // .map(item => ({ ...item, index: this.index++ }))
          } else {
            this.dataList.splice(0, this.dataList.length)
          }
          this.total = response.data.total
          this.listLoading = false
        })
      })
    },
    // 新增 / 修改
    addNew(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 导出模板
    exportTemplate() {
      getExcelExample().then(response => {
        let fileName = ''
        const contentDisposition = response.headers['content-disposition']
        if (contentDisposition) {
          fileName = contentDisposition.slice(contentDisposition.indexOf('filename=') + 9)
        }
        const blob = new Blob([response.data])
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = e => {
          const a = document.createElement('a')
          a.download = fileName
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      })
    },
    // 导入
    importFile(res) {
      if (res.response.code === 1) {
        this.$message({
          type: 'warning',
          duration: 1000,
          message: res.response.msg,
          onClose: () => {
            this.importFileData = res.response.data
            this.importVisible = true
            this.$nextTick(() => {
              this.$refs.import.init()
            })
          }
        })
      } else {
        this.importFileData = res.response.data
        this.importVisible = true
        this.$nextTick(() => {
          this.$refs.import.init()
        })
      }
    },
    importFileError() {
      this.$message.error(this.$t('module.teamManager.shift.errorImport'))
    },
    btnClick(val) {
      this.headFormValue = val
      // 如果点击的是搜索栏的其他按钮在这里继续写判断
      if (this.headFormValue.btnName === 'search') {
        this.getList()
      } else if (this.headFormValue.btnName === 'exportTemplate') {
        this.exportTemplate()
      }
    },
    clickTopBtn(val) {
      if (val === 'add') {
        this.addNew() // 新增
      }
    }
  }
}
</script>
