<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('code'))">
            <el-input
              v-model="search.code"
              :placeholder="$t(key('please_enter'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('name'))">
            <el-input
              v-model="search.name"
              :placeholder="$t(key('please_enter'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="onSearch">
              {{ $t(key('search')) }}
            </el-button>
            <el-button icon="el-icon-refresh" @click="onReset">
              {{ $t(key('reset')) }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <page-table
      ref="pageTable"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="toolbarButtons"
      :row-buttons="rowButtons"
      :pagination="pagination"
      :table-attrs="{ highlightCurrentRow: true }"
      :table-listeners="{ 'sort-change': handleSort }"
      help-url="/help/quality-management/inspection-type-management"
      :help-text="$t(ckey('help'))"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    />

    <page-dialog-form
      ref="dialogForm"
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="520px"
      :form-cols="formCols"
      :form-data="formData"
      :rules="rules"
      label-width="120px"
      :submitting="submitting"
      :confirm-text="key('confirm')"
      :cancel-text="key('cancel')"
      @submit="onDialogSubmit"
      @close="onDialogClose"
    />
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { useTableButtons } from '@/composables/useTableButtons'
import { i18nMixin } from '@/composables/useI18n'
import { confirmMixin } from '@/composables/useConfirmHandle'
import {
  fetchInspectionTypeManagementList,
  createInspectionTypeManagement,
  editInspectionTypeManagement,
  deleteInspectionTypeManagement
} from '@/api/quality-management/inspection-type-management'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'

function readList (res) {
  if (Array.isArray(res)) return { list: res, total: res.length }
  const data = res && res.data ? res.data : res
  if (Array.isArray(data)) return { list: data, total: data.length }
  const list = (data && (data.list || data.rows || data.records || data.data)) || []
  const total = data && (data.total || data.count || list.length)
  return { list: Array.isArray(list) ? list : [], total: Number(total) || 0 }
}

export default {
  name: 'quality-management-inspection-type-management',
  components: { PageTable, PageDialogForm },
  mixins: [i18nMixin('page.quality_management.inspection_type_management'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      search: { code: '', name: '' },
      pagination: { current: 1, size: 10, total: 0 },
      order: {
        order_type: undefined,
        order_field: undefined
      },
      formData: { code: '', name: '', note: '' },
      rules: {
        code: [
          { required: true, message: this.key('required'), trigger: 'blur' },
          { min: 2, message: this.key('length_min_2'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.key('required'), trigger: 'blur' },
          { min: 2, message: this.key('length_min_2'), trigger: 'blur' }
        ]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      formCols: [
        [
          {
            type: 'input',
            prop: 'code',
            label: this.key('code'),
            placeholder: this.key('please_enter'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'name',
            label: this.key('name'),
            placeholder: this.key('please_enter'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'note',
            label: this.key('remark'),
            placeholder: this.key('please_enter'),
            clearable: true,
            style: { width: '90%' }
          }
        ]
      ]
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'code', label: this.key('code'), minWidth: 130, sortable: 'custom', showOverflowTooltip: true },
      { prop: 'name', label: this.key('name'), minWidth: 130, sortable: 'custom', showOverflowTooltip: true },
      { prop: 'nickname', label: this.key('nickname'), minWidth: 130, sortable: 'custom', showOverflowTooltip: true },
      { prop: 'create_date', label: this.key('create_date'), minWidth: 150, sortable: 'custom', showOverflowTooltip: true },
      { prop: 'note', label: this.key('remark'), minWidth: 130, sortable: 'custom', showOverflowTooltip: true },
      { prop: '_actions', label: this.key('operation'), width: 160, fixed: 'right' }
    ])
    const btns = useTableButtons({
      toolbar: [
        {
          key: 'add',
          label: this.key('add'),
          icon: 'el-icon-plus',
          type: 'primary',
          auth: '/quality_control/first_inspection/category/add',
          onClick: this.openAdd
        },
        {
          key: 'batch_delete',
          label: this.key('delete'),
          icon: 'el-icon-delete',
          type: 'danger',
          auth: '/quality_control/first_inspection/category/delete',
          needSelection: true,
          onClick: this.handleBatchDelete
        }
      ],
      row: [
        {
          key: 'edit',
          label: this.key('edit'),
          icon: 'el-icon-edit',
          auth: '/quality_control/first_inspection/category/update',
          onClick: this.openEdit
        },
        {
          key: 'delete',
          label: this.key('delete'),
          icon: 'el-icon-delete',
          color: 'danger',
          auth: '/quality_control/first_inspection/category/delete',
          onClick: this.handleDelete
        }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.fetchData()
  },
  methods: {
    async fetchData () {
      this.loading = true
      try {
        const params = {
          ...this.search,
          ...this.order,
          page_no: this.pagination.current,
          page_size: this.pagination.size,
          page: this.pagination.current,
          size: this.pagination.size
        }
        const res = await fetchInspectionTypeManagementList(params)
        const { list, total } = readList(res)
        this.tableData = list
        this.pagination.total = total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { code: '', name: '' }
      this.pagination.current = 1
      this.fetchData()
    },
    onPageChange (page) {
      this.pagination.current = page.current
      this.pagination.size = page.size
      this.fetchData()
    },
    onSelect (rows) {
      this.selectedRows = rows
    },
    handleSort ({ column, prop, order }) {
      this.order = {
        order_type: column && order ? (order === 'ascending' ? 'asc' : 'desc') : undefined,
        order_field: column && order ? prop : undefined
      }
      this.fetchData()
    },
    resetForm () {
      this.formData = { code: '', name: '', note: '' }
      this.editId = ''
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_title')
      this.resetForm()
      this.dialogVisible = true
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_title')
      this.editId = row.id
      this.formData = { ...{ code: '', name: '', note: '' }, ...row }
      this.dialogVisible = true
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await createInspectionTypeManagement(this.formData)
        } else {
          await editInspectionTypeManagement({ ...this.formData, id: this.editId })
        }
        this.$message.success(this.$t(this.key('operation_success')))
        this.dialogVisible = false
        this.fetchData()
      } finally {
        this.submitting = false
      }
    },
    onDialogClose () {
      this.resetForm()
    },
    async handleDelete (row) {
      const cancelled = await this.$confirmAction({
        message: this.key('confirm_delete'),
        title: this.key('tip'),
        confirmButtonText: this.key('confirm'),
        cancelButtonText: this.key('cancel'),
        closeOnClickModal: false
      }, () => deleteInspectionTypeManagement({ id: [row.id] }))
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
      this.fetchData()
    },
    async handleBatchDelete () {
      if (!this.selectedRows.length) {
        this.$message.error(this.$t(this.key('select_operate_data')))
        return
      }
      const cancelled = await this.$confirmAction({
        message: this.key('confirm_delete'),
        title: this.key('tip'),
        confirmButtonText: this.key('confirm'),
        cancelButtonText: this.key('cancel'),
        closeOnClickModal: false
      }, () => deleteInspectionTypeManagement({ id: this.selectedRows.map(item => item.id) }))
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.search-bar {
  padding: 10px 0;
}
.spc-chart-panel {
  height: 320px;
  margin-bottom: 12px;
  border: 1px solid #ebeef5;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
</style>
