<template>
  <d2-container>
    <div class="inspection-records-page">
      <aside class="category-panel" v-loading="treeLoading">
        <el-input
          v-model.trim="categoryFilter"
          size="mini"
          :placeholder="$t(key('enter_device_category_name'))"
          clearable
          class="category-filter"
        />
        <el-tree
          v-if="deviceCategoryTree.length"
          ref="categoryTree"
          :data="deviceCategoryTree"
          show-checkbox
          highlight-current
          default-expand-all
          node-key="id"
          :expand-on-click-node="false"
          :default-checked-keys="currentCategoryId ? [currentCategoryId] : []"
          :current-node-key="currentCategoryId"
          :filter-node-method="filterCategoryNode"
          @node-click="handleCategoryClick"
          @check-change="handleCategoryCheckChange"
        >
          <template #default="{ node, data }">
            <span class="category-node">
              <span>{{ node.label }}</span>
              <span class="category-code">({{ data.code || '-' }})</span>
            </span>
          </template>
        </el-tree>
        <el-result v-else icon="info" :title="$t(key('no_data'))" sub-title="" />
      </aside>

      <section class="records-panel">
        <div class="records-context">
          <span class="context-label">{{ $t(key('current_device_category')) }}</span>
          <strong>{{ currentCategoryLabel || '-' }}</strong>
        </div>
        <div class="search-bar">
          <el-form :inline="true" :model="search" size="mini">
            <el-form-item :label="$t(key('device_code'))">
              <el-input v-model.trim="search.device_code" :placeholder="$t(key('enter_device_code'))" clearable style="width:210px" @keyup.enter.native="onSearch" />
            </el-form-item>
            <el-form-item :label="$t(key('device_name'))">
              <el-input v-model.trim="search.device_name" :placeholder="$t(key('enter_device_name'))" clearable style="width:210px" @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>

        <page-table
          ref="pageTable"
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :toolbar-buttons="toolbarButtons"
          :row-buttons="rowButtons"
          :pagination="pagination"
          auto-height
          @page-change="onPageChange"
        >
          <template #col-check_result="{ row }">
            <el-tag v-if="row.check_result" :type="row.check_result === 'OK' ? 'success' : 'danger'" size="mini">{{ row.check_result }}</el-tag>
            <span v-else>-</span>
          </template>
        </page-table>
      </section>
    </div>

    <el-dialog :title="dialogTitleText" :visible.sync="dialogVisible" width="980px" :close-on-click-modal="false" @close="resetDialog">
      <el-form ref="recordForm" :model="recordForm" :rules="recordRules" inline size="mini" label-width="90px">
        <el-form-item :label="$t(key('implementation_people'))" prop="implementation_people">
          <el-input v-model.trim="recordForm.implementation_people" :placeholder="$t(key('enter_implementation_people'))" clearable style="width:220px" />
        </el-form-item>
        <el-form-item :label="$t(key('class_please'))" prop="class_please">
          <el-select v-model="recordForm.class_please" :placeholder="$t(key('please_select_class_please'))" clearable style="width:160px">
            <el-option :label="$t(key('day_shift'))" value="早" />
            <el-option :label="$t(key('night_shift'))" value="夜" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t(key('inspection_item_name'))">
          <el-input v-model.trim="itemSearch.name" :placeholder="$t(key('enter_inspection_item_name'))" clearable style="width:220px" @keyup.enter.native="loadInspectionItems" />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" @click="loadInspectionItems">{{ $t(key('search')) }}</el-button>
          <el-button icon="el-icon-refresh" @click="resetItemSearch">{{ $t(key('reset')) }}</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="itemsLoading" :data="inspectionItems" border height="430" size="mini">
        <el-table-column prop="sort" :label="$t(key('sort'))" width="70" />
        <el-table-column prop="name" :label="$t(key('inspection_item_name'))" min-width="150" />
        <el-table-column prop="standard" :label="$t(key('standard'))" min-width="150" show-overflow-tooltip />
        <el-table-column prop="check_method" :label="$t(key('check_method'))" min-width="130" show-overflow-tooltip />
        <el-table-column prop="unit" :label="$t(key('unit'))" width="90" />
        <el-table-column prop="val" :label="$t(key('inspection_value'))" min-width="160">
          <template #default="{ row }">
            <el-input v-model.trim="row.val" size="mini" :placeholder="$t(key('enter_inspection_value'))" clearable />
          </template>
        </el-table-column>
        <el-table-column prop="result" :label="$t(key('inspection_result'))" width="130">
          <template #default="{ row }">
            <el-switch v-model="row.result" active-value="OK" inactive-value="NG" active-text="OK" inactive-text="NG" />
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer">
        <el-button @click="dialogVisible = false">{{ $t(key('cancel')) }}</el-button>
        <el-button type="primary" :loading="submitting" @click="submitRecord">{{ $t(key('confirm')) }}</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { useTableButtons } from '@/composables/useTableButtons'
import { i18nMixin } from '@/composables/useI18n'
import PageTable from '@/components/page-table'
import { getEquipmentCategoryALL } from '@/api/equipment-management/equipment-category'
import { getList, createItem } from '@/api/equipment-management/inspection-records'
import { getAll as getInspectionItemsAll } from '@/api/equipment-management/inspection-items'

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

function readList (res) {
  const data = res && res.data !== undefined ? res.data : res
  if (Array.isArray(data)) return data
  if (data && Array.isArray(data.data)) return data.data
  return []
}

function normalizeCategories (list) {
  return (Array.isArray(list) ? list : []).map((item, index) => ({
    id: item.id || item.value,
    value: item.id || item.value,
    label: item.name || item.label,
    name: item.name || item.label,
    code: item.code || '',
    index,
    children: []
  }))
}

export default {
  name: 'equipment-management-inspection-records',
  components: { PageTable },
  mixins: [i18nMixin('page.equipment_management.inspection_management.inspection_records')],
  data () {
    return {
      loading: false,
      treeLoading: false,
      submitting: false,
      itemsLoading: false,
      tableData: [],
      categoryFilter: '',
      deviceCategoryTree: [],
      currentCategoryId: '',
      currentCategory: null,
      search: { device_code: '', device_name: '' },
      pagination: { current: 1, size: 10, total: 0 },
      dialogVisible: false,
      currentDevice: null,
      recordForm: { implementation_people: '', class_please: '' },
      itemSearch: { name: '' },
      inspectionItems: [],
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      recordRules: {
        implementation_people: [{ required: true, message: this.$t(this.key('enter_implementation_people')), trigger: 'blur' }],
        class_please: [{ required: true, message: this.$t(this.key('please_select_class_please')), trigger: 'change' }]
      }
    }
  },
  computed: {
    currentCategoryLabel () {
      if (!this.currentCategory) return ''
      return `${this.currentCategory.label}${this.currentCategory.code ? ` (${this.currentCategory.code})` : ''}`
    },
    dialogTitleText () {
      const name = this.currentDevice ? `${this.currentDevice.device_code || ''} ${this.currentDevice.device_name || ''}`.trim() : ''
      return `${this.$t(this.key('add_inspection_record'))}${name ? ` - ${name}` : ''}`
    }
  },
  watch: {
    categoryFilter (val) {
      if (this.$refs.categoryTree) this.$refs.categoryTree.filter(val)
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'device_code', label: this.key('device_code'), minWidth: 140, fixed: 'left' },
      { prop: 'device_name', label: this.key('device_name'), minWidth: 150, fixed: 'left' },
      { prop: 'device_category_name', label: this.key('device_category'), minWidth: 140 },
      { prop: 'check_time', label: this.key('last_inspection_time'), minWidth: 160 },
      { prop: 'check_result', label: this.key('last_inspection_result'), slot: 'check_result', minWidth: 140 },
      { prop: 'item_total', label: this.key('last_item_total'), minWidth: 150 },
      { prop: 'item_ng_number', label: this.key('last_ng_total'), minWidth: 150 },
      { prop: 'item_ng_rate', label: this.key('last_ng_rate'), minWidth: 150 },
      { prop: '_actions', label: this.key('operation'), width: 150, fixed: 'right' }
    ], { selectionWidth: 0 })
    const btns = useTableButtons({
      row: [
        { key: 'create', label: this.key('add_inspection_record'), icon: 'el-icon-plus', auth: '/device_management/device_check/device_check_record/create', onClick: this.openCreate }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.loadDeviceCategories()
  },
  methods: {
    async loadDeviceCategories () {
      this.treeLoading = true
      try {
        const res = await getEquipmentCategoryALL({ no_denglu_sign: 'no' })
        const list = normalizeCategories((res && res.data) || res)
        this.deviceCategoryTree = list
        if (list.length) {
          this.setCurrentCategory(list[0], false)
          this.$nextTick(() => {
            if (this.$refs.categoryTree) {
              this.$refs.categoryTree.setCheckedKeys([this.currentCategoryId])
              this.$refs.categoryTree.setCurrentKey(this.currentCategoryId)
            }
          })
          this.fetchData()
        }
      } finally {
        this.treeLoading = false
      }
    },
    setCurrentCategory (category, shouldFetch = true) {
      this.currentCategory = category
      this.currentCategoryId = category ? category.id : ''
      this.pagination.current = 1
      if (shouldFetch) this.fetchData()
    },
    filterCategoryNode (value, data) {
      if (!value) return true
      const text = String(value).toLowerCase()
      return String(data.label || '').toLowerCase().includes(text) || String(data.code || '').toLowerCase().includes(text)
    },
    handleCategoryClick (data) {
      this.setCurrentCategory(data)
      this.$nextTick(() => {
        if (this.$refs.categoryTree) this.$refs.categoryTree.setCheckedKeys([data.id])
      })
    },
    handleCategoryCheckChange (data, checked) {
      if (!checked) return
      if (this.$refs.categoryTree) this.$refs.categoryTree.setCheckedKeys([data.id])
      if (String(data.id) !== String(this.currentCategoryId)) this.setCurrentCategory(data)
    },
    buildSearchParams () {
      return { ...this.search, device_category_id: this.currentCategoryId }
    },
    async fetchData () {
      if (!this.currentCategoryId) {
        this.tableData = []
        this.pagination.total = 0
        return
      }
      this.loading = true
      try {
        const res = await getList({ ...this.buildSearchParams(), page_no: this.pagination.current, page_size: this.pagination.size })
        const page = readPageData(res)
        this.tableData = page.list
        this.pagination.total = page.total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { device_code: '', device_name: '' }
      this.pagination.current = 1
      this.fetchData()
    },
    onPageChange (page) {
      this.pagination.current = page.current
      this.pagination.size = page.size
      this.fetchData()
    },
    openCreate (row) {
      this.currentDevice = row
      this.dialogVisible = true
      this.resetDialog(false)
      this.loadInspectionItems()
    },
    resetDialog (clearDevice = true) {
      this.recordForm = { implementation_people: '', class_please: '' }
      this.itemSearch = { name: '' }
      this.inspectionItems = []
      if (clearDevice) this.currentDevice = null
    },
    resetItemSearch () {
      this.itemSearch = { name: '' }
      this.loadInspectionItems()
    },
    async loadInspectionItems () {
      if (!this.currentDevice || !this.currentDevice.device_category_id) return
      this.itemsLoading = true
      try {
        const res = await getInspectionItemsAll({
          device_category_id: this.currentDevice.device_category_id,
          name: this.itemSearch.name
        })
        this.inspectionItems = readList(res).map(item => ({
          ...item,
          val: '',
          result: 'OK'
        }))
      } finally {
        this.itemsLoading = false
      }
    },
    submitRecord () {
      this.$refs.recordForm.validate(async valid => {
        if (!valid) return
        if (!this.inspectionItems.length) {
          this.$message.warning(this.$t(this.key('inspection_items_empty')))
          return
        }
        this.submitting = true
        try {
          await createItem({
            deviceCheckItemsData: JSON.stringify(this.inspectionItems),
            device_category_id: this.currentDevice.device_category_id,
            device_code: this.currentDevice.device_code,
            class_please: this.recordForm.class_please,
            implementation_people: this.recordForm.implementation_people,
            status: 1
          })
          this.$message.success(this.$t(this.key('operation_success')))
          this.dialogVisible = false
          this.fetchData()
        } finally {
          this.submitting = false
        }
      })
    }
  }
}
</script>

<style scoped>
.inspection-records-page {
  display: flex;
  gap: 16px;
  height: 100%;
  min-height: 560px;
}
.category-panel {
  flex: 0 0 260px;
  min-width: 220px;
  border-right: 1px solid #ebeef5;
  padding: 10px 14px 10px 0;
  overflow: auto;
}
.category-filter {
  margin-bottom: 12px;
}
.category-node {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  max-width: 190px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.category-code {
  color: #909399;
  font-size: 12px;
}
.records-panel {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
}
.records-context {
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 30px;
  margin-bottom: 8px;
  color: #303133;
}
.context-label {
  color: #909399;
}
.search-bar {
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 10px;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
/deep/ .d2-container-full__body {
  overflow: hidden;
}
</style>
