<!--
 * @Author: lb
 * @Date: 2022-03-30 14:28:54
 * @LastEditors: gtz
 * @LastEditTime: 2022-07-25 10:34:36
 * @Description: 在线物料使用记录
-->

<template>
  <div class="app-container">
    <head-form :form-config="headFormConfig" @headBtnClick="btnClick" />
    <base-table
      :top-btn-config="topBtnConfig"
      :page="listQuery.current"
      :limit="listQuery.size"
      :table-config="tableProps"
      :table-data="dataList"
      :is-loading="listLoading"
      @clickTopBtn="clickTopBtn"
    >
      <method-btn slot="handleBtn" :width="calculateWidth" :method-list="tableBtn" @clickBtn="handleClick" />
    </base-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList()"
    />

    <record-add-drawer
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getList"
      @destroy-me="handleDestroyDrawer"
    />
  </div>
</template>

<script>
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 i18n from '@/lang'
import { timeFormatter } from '@/filters'
import newBasicData from '@/filters/newBasicData'
import { list, del, getMaterialList, getEquipmentList } from '@/api/material-manage/usageRecord'

import RecordAddDrawer from './components/add-panel.vue'
/**
 * 表格表头配置项 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: 'delete',
    btnName: 'btn.delete'
  }
]
const tableProps = [
  {
    prop: 'equipmentName',
    label: i18n.t('module.materialManager.currentUsageRecord.equipmentName')
  },
  {
    prop: 'materialName',
    label: i18n.t('module.materialManager.currentUsageRecord.materialName')
  },
  {
    prop: 'materialCode',
    label: i18n.t('module.materialManager.currentUsageRecord.materialCode'),
    width: 180
  },
  {
    prop: 'num',
    label: i18n.t('module.materialManager.currentUsageRecord.num')
  },
  {
    prop: 'unit',
    label: i18n.t('module.materialManager.currentUsageRecord.unit'),
    filter: newBasicData('1')
  },
  // {
  //   prop: 'materialDateCode',
  //   label: i18n.t('module.materialManager.currentUsageRecord.materialPatch')
  // },
  {
    prop: 'userName',
    // label: '使用人'
    label: i18n.t('module.materialManager.currentUsageRecord.user')
  },
  {
    prop: 'useTime',
    label: i18n.t('module.materialManager.currentUsageRecord.materialUseTime'),
    filter: timeFormatter
  },
  {
    prop: 'remark',
    label: i18n.t('module.materialManager.currentUsageRecord.remark')
  }
]
export default {
  components: { HeadForm, Pagination, BaseTable, MethodBtn, RecordAddDrawer },
  data() {
    return {
      addOrUpdateVisible: false,
      topBtnConfig,
      tableBtn,
      trueWidth: 240,
      tableProps,
      dataList: [],
      total: 0,
      listLoading: false,
      listQuery: {
        current: 1,
        size: 20
      },
      headFormConfig: [
        {
          type: 'select',
          label: this.$t('module.materialManager.currentUsageRecord.equipmentName'),
          selectOptions: [],
          param: 'equipmentName',
          valueField: 'name',
          width: 200
        },
        {
          type: 'select',
          label: this.$t('module.materialManager.currentUsageRecord.materialName'),
          selectOptions: [],
          param: 'materialName',
          valueField: 'name',
          width: 200
        },
        {
          type: 'button',
          btnName: 'btn.search',
          name: 'search',
          color: 'primary'
        }
      ],
      headFormValue: {}
    }
  },
  computed: {
    calculateWidth() {
      return this.tableBtn.length * 40 // 操作列的每个按钮宽度40
    }
  },
  created() {
    const DEFAULT_QUERY_PARAM = {
      current: 1,
      size: 1000
    }
    getEquipmentList(DEFAULT_QUERY_PARAM).then(response => {
      this.headFormConfig[0].selectOptions = response.data
    })
    getMaterialList(DEFAULT_QUERY_PARAM).then(response => {
      this.headFormConfig[1].selectOptions = response.data?.records || []
    })
    this.getList()
  },
  methods: {
    getList() {
      const equipmentName = this.headFormValue.equipmentName ? this.headFormValue.equipmentName : ''
      const materialName = this.headFormValue.materialName ? this.headFormValue.materialName : ''

      list({ ...this.listQuery, equipmentName, materialName }).then(response => {
        if (response.data.records) {
          this.dataList = response.data.records
          this.total = response.data.total
        } else {
          this.total = 0
          this.dataList = []
        }
      })

      setTimeout(() => {
        this.addOrUpdateVisible = false
      }, 300)
    },

    addNew(data) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(data)
      })
    },

    handleEdit(id) {
      this.$router.push({
        path: 'currentUsageRecord/add',
        query: {
          redirect: '/material-manage/currentUsageRecord',
          title: this.$t('module.materialManager.currentUsageRecord.edit'),
          id
        }
      })
    },
    handleDelete(id) {
      del({ id }).then(response => {
        this.$message({
          message: this.$t('module.basicData.visual.success'),
          type: 'success',
          duration: 1500
        })
        this.handleSearch()
      })
    },
    handleDestroyDrawer() {
      setTimeout(() => {
        this.addOrUpdateVisible = false
      }, 300)
    },
    handleClick(raw) {
      if (raw.type === 'delete') {
        this.$confirm(
          `${this.$t('module.basicData.visual.TipsBefore')}${this.$t(
            'module.materialManager.currentUsageRecord.thisRecord'
          )}?`,
          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.listQuery.current = 1
                  this.getList()
                }
              })
            })
          })
          .catch(() => {})
      } else if (raw.type === 'edit') {
        // console.log('editing raw data: ', raw.data)
        this.addNew(raw.data)
      }
    },

    btnClick(val) {
      this.headFormValue = val
      // 如果点击的是搜索栏的其他按钮在这里继续写判断
      if (this.headFormValue.btnName === 'search') {
        this.getList()
      }
    },
    clickTopBtn(val) {
      if (val === 'add') {
        this.addNew(null)
      }
    }
  }
}
</script>
