<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('process_unit'))">
            <el-select v-model="search.workingsubclass_id" :placeholder="$t(key('please_select'))" clearable filterable style="width:180px">
              <el-option v-for="item in workingsubclassOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('inspection_type'))">
            <el-select v-model="search.type" :placeholder="$t(key('please_select'))" clearable filterable style="width:180px">
              <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('time_range'))">
            <el-date-picker
              v-model="search.create_time"
              type="datetimerange"
              :range-separator="$t(key('to'))"
              :start-placeholder="$t(key('start_date'))"
              :end-placeholder="$t(key('end_date'))"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              style="width:360px"
            />
          </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/first-article-inspection-configuration"
      :help-text="$t(ckey('help'))"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    />

    <page-dialog-form
      ref="dialogForm"
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="560px"
      :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"
    >
      <el-form-item prop="is_need">
        <template #label>
          <span>{{ $t(key('is_required')) }}</span>
          <el-tooltip effect="dark" :content="$t(key('is_required_tooltip'))" placement="top-start">
            <i class="el-icon-question" />
          </el-tooltip>
        </template>
        <el-radio-group v-model="formData.is_need">
          <el-radio :label="1">{{ $t(key('yes')) }}</el-radio>
          <el-radio :label="0">{{ $t(key('no')) }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </page-dialog-form>

    <setting-items-dialog :visible.sync="itemsDialogVisible" :setting-row="currentSetting" @saved="fetchData" />
  </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 {
  fetchFirstArticleInspectionConfigurationList,
  createFirstArticleInspectionConfiguration,
  editFirstArticleInspectionConfiguration,
  deleteFirstArticleInspectionConfiguration,
  getQualityCategoryAll,
  getWorkingsubclassAll
} from '@/api/quality-management/first-article-inspection-configuration'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'
import SettingItemsDialog from './components/SettingItemsDialog'

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-first-article-inspection-configuration',
  components: { PageTable, PageDialogForm, SettingItemsDialog },
  mixins: [i18nMixin('page.quality_management.first_article_inspection_configuration'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      itemsDialogVisible: false,
      currentSetting: null,
      editId: '',
      handleType: 'create',
      search: { workingsubclass_id: undefined, type: undefined, create_time: undefined },
      order: { order_type: undefined, order_field: undefined },
      pagination: { current: 1, size: 10, total: 0 },
      workingsubclassOptions: [],
      categoryOptions: [],
      formData: { workingsubclass_id: undefined, quality_category_id: undefined, note: '', is_need: 0 },
      rules: {
        workingsubclass_id: [{ required: true, message: this.key('process_unit_required'), trigger: 'change' }],
        quality_category_id: [{ required: true, message: this.key('inspection_type_required'), trigger: 'change' }]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: []
    }
  },
  computed: {
    formCols () {
      return [
        [
          { type: 'select', prop: 'workingsubclass_id', label: this.key('process_unit'), placeholder: this.key('please_select'), options: this.workingsubclassOptions.map(item => ({ label: item.name, value: item.id })), clearable: true, style: { width: '90%' } }
        ],
        [
          { type: 'select', prop: 'quality_category_id', label: this.key('inspection_type'), placeholder: this.key('please_select'), options: this.categoryOptions.map(item => ({ label: item.name, value: item.id })), 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: 'workingsubclass_name', label: this.key('process_unit'), minWidth: 150, sortable: 'custom', showOverflowTooltip: true },
      { prop: 'quality_category_name', label: this.key('inspection_type'), minWidth: 150, sortable: 'custom', showOverflowTooltip: true },
      { prop: 'nickname', label: this.key('creator'), minWidth: 130, sortable: 'custom', showOverflowTooltip: true },
      { prop: 'create_date', label: this.key('create_time'), minWidth: 160, sortable: 'custom', showOverflowTooltip: true },
      { prop: 'note', label: this.key('remark'), minWidth: 150, sortable: 'custom', showOverflowTooltip: true },
      { prop: '_actions', label: this.key('operation'), width: 220, fixed: 'right' }
    ])
    const btns = useTableButtons({
      toolbar: [
        { key: 'add', label: this.key('add'), icon: 'el-icon-plus', type: 'primary', auth: '/quality_control/first_inspection/setting/add', onClick: this.openAdd },
        { key: 'batch_delete', label: this.key('delete'), icon: 'el-icon-delete', type: 'danger', auth: '/quality_control/first_inspection/setting/delete', onClick: this.handleBatchDelete }
      ],
      row: [
        { key: 'edit', label: this.key('edit'), icon: 'el-icon-edit', auth: '/quality_control/first_inspection/setting/update', onClick: this.openEdit },
        { key: 'configure_item', label: this.key('configure_item'), icon: 'el-icon-setting', auth: '/quality_control/first_inspection/setting/update', onClick: this.openItemsDialog },
        { key: 'delete', label: this.key('delete'), icon: 'el-icon-delete', color: 'danger', auth: '/quality_control/first_inspection/setting/delete', onClick: this.handleDelete }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.fetchOptions()
    this.fetchData()
  },
  methods: {
    async fetchOptions () {
      const [workingsubclassRes, categoryRes] = await Promise.all([getWorkingsubclassAll(), getQualityCategoryAll()])
      this.workingsubclassOptions = this.normalizeList(workingsubclassRes)
      this.categoryOptions = this.normalizeList(categoryRes)
    },
    normalizeList (res) {
      if (Array.isArray(res)) return res
      if (res && Array.isArray(res.data)) return res.data
      if (res && res.data && Array.isArray(res.data.data)) return res.data.data
      if (res && Array.isArray(res.list)) return res.list
      return []
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await fetchFirstArticleInspectionConfigurationList({
          ...this.search,
          ...this.order,
          page_no: this.pagination.current,
          page_size: this.pagination.size
        })
        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 = { workingsubclass_id: undefined, type: undefined, create_time: undefined }
      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 = { workingsubclass_id: undefined, quality_category_id: undefined, note: '', is_need: 0 }
      this.editId = ''
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_title')
      this.$nextTick(() => {
        this.$refs.dialogForm && this.$refs.dialogForm.reset()
        this.resetForm()
        this.dialogVisible = true
      })
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_title')
      this.editId = row.id
      this.formData = {
        workingsubclass_id: row.workingsubclass_id,
        quality_category_id: row.quality_category_id,
        note: row.note || '',
        is_need: Number(row.is_need || 0)
      }
      this.dialogVisible = true
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await createFirstArticleInspectionConfiguration(this.formData)
        } else {
          await editFirstArticleInspectionConfiguration({ ...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()
    },
    openItemsDialog (row) {
      this.currentSetting = row
      this.itemsDialogVisible = true
    },
    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
      }, () => deleteFirstArticleInspectionConfiguration({ 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
      }, () => deleteFirstArticleInspectionConfiguration({ 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;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
</style>
