<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('enter_code'))"
              clearable
              style="width:180px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('name'))">
            <el-input
              v-model="search.name"
              :placeholder="$t(key('enter_name'))"
              clearable
              style="width:180px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('category'))">
            <el-select
              v-model="search.flow_category_id"
              :placeholder="$t(key('select_category'))"
              clearable
              filterable
              size="mini"
              style="width:180px"
              @focus="loadSearchCategories"
            >
              <el-option
                v-for="item in searchCategoryOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t(key('product'))">
            <el-select
              v-model="search.product_model_id"
              :placeholder="$t(key('select_product'))"
              clearable
              filterable
              size="mini"
              style="width:180px"
              @focus="loadSearchProducts"
            >
              <el-option
                v-for="item in searchProductOptions"
                :key="item.product_model_id"
                :label="item.name"
                :value="item.product_model_id"
              />
            </el-select>
          </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"
      help-url="/help/process-routing"
      :help-text="$t(ckey('help'))"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    />

    <page-dialog-form
      ref="dialogForm"
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :width="'35%'"
      :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 {
  getProcessRoutingList,
  createProcessRouting,
  editProcessRouting,
  deleteProcessRouting,
  copyProcessRouting
} from '@/api/production-master-data/process-routing'
import { getProcessCategoryAll } from '@/api/production-master-data/process-category'
import { getProductBatteryAll } from '@/api/production-master-data/product-management'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'

export default {
  name: 'production-master-data-process-routing',
  components: { PageTable, PageDialogForm },
  mixins: [i18nMixin('page.production_master_data.process_model.process_routing'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      search: { code: '', name: '', flow_category_id: '', product_model_id: '' },
      pagination: { current: 1, size: 10, total: 0 },
      formData: {
        code: '',
        name: '',
        flow_category_id: '',
        product_model_id: '',
        remark: ''
      },
      categoryOptions: [],
      productOptions: [],
      searchCategoryOptions: [],
      searchProductOptions: [],
      rules: {
        code: [
          { required: true, message: this.key('enter_code'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('remark_length'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.key('enter_name'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('remark_length'), trigger: 'blur' }
        ],
        flow_category_id: [
          { required: true, message: this.key('select_category'), trigger: 'change' }
        ],
        product_model_id: [
          { required: true, message: this.key('select_product'), trigger: 'change' }
        ]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      formCols: [
        [
          {
            type: 'input',
            prop: 'code',
            label: this.key('code'),
            placeholder: this.key('enter_code'),
            clearable: true,
            disabled: false,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'name',
            label: this.key('name'),
            placeholder: this.key('enter_name'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'select',
            prop: 'flow_category_id',
            label: this.key('category'),
            placeholder: this.key('select_category'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: []
          }
        ],
        [
          {
            type: 'select',
            prop: 'product_model_id',
            label: this.key('product'),
            placeholder: this.key('select_product'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: []
          }
        ],
        [
          {
            type: 'input',
            prop: 'remark',
            inputType: 'textarea',
            autosize: { minRows: 2, maxRows: 6 },
            label: this.key('remark'),
            placeholder: this.key('enter_remark'),
            clearable: true,
            style: { width: '90%' }
          }
        ]
      ]
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'code', label: this.key('code'), minWidth: 120 },
      { prop: 'name', label: this.key('name'), minWidth: 140 },
      { prop: 'flow_category_name', label: this.key('category'), minWidth: 120 },
      { prop: 'product_model_code', label: this.key('product'), minWidth: 140 },
      { prop: 'remark', label: this.key('remark'), minWidth: 120 },
      { prop: 'username', label: this.key('creator'), minWidth: 100 },
      { prop: 'create_time', label: this.key('create_time'), width: 160 },
      { prop: '_actions', label: this.key('operation'), width: 240, fixed: 'right' }
    ])
    const btns = useTableButtons({
      toolbar: [
        {
          key: 'add',
          label: this.key('add'),
          icon: 'el-icon-plus',
          type: 'primary',
          auth: '/production_configuration/technology_model/technology_flow/create',
          onClick: this.openAdd
        }
      ],
      row: [
        {
          key: 'edit',
          label: this.key('edit'),
          icon: 'el-icon-edit',
          auth: '/production_configuration/technology_model/technology_flow/edit',
          onClick: this.openEdit
        },
        {
          key: 'setProcess',
          label: this.key('set_process'),
          icon: 'el-icon-s-operation',
          color: 'primary',
          auth: '/production_configuration/technology_model/technology_flow/set_process',
          onClick: this.openProcessCard
        },
        {
          key: 'copy',
          label: this.key('copy'),
          icon: 'el-icon-document-copy',
          color: 'warning',
          auth: '/production_configuration/technology_model/technology_flow/copy',
          onClick: this.handleCopy
        },
        {
          key: 'delete',
          label: this.key('delete'),
          icon: 'el-icon-delete',
          color: 'danger',
          auth: '/production_configuration/technology_model/technology_flow/delete',
          onClick: this.handleDelete
        }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.fetchData()
  },
  methods: {
    normalizeResponse (res) {
      const getTotal = (source, fallback) => {
        if (!source) return fallback
        const total = source.count ?? source.total ?? source.total_count ?? source.record_count
        const value = Number(total)
        return Number.isNaN(value) ? fallback : value
      }
      const containers = [res, res && res.data, res && res.data && res.data.data].filter(Boolean)
      for (const item of containers) {
        if (Array.isArray(item)) {
          return { list: item, total: getTotal(res, item.length) }
        }
        const list = item.data || item.list || item.rows || item.records || item.items
        if (Array.isArray(list)) {
          return { list, total: getTotal(item, getTotal(res, list.length)) }
        }
      }
      return { list: [], total: 0 }
    },
    async fetchData () {
      this.loading = true
      try {
        const res = await getProcessRoutingList({
          ...this.search,
          page_no: this.pagination.current,
          page_size: this.pagination.size
        })
        const data = this.normalizeResponse(res)
        this.tableData = data.list
        this.pagination.total = data.total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { code: '', name: '', flow_category_id: '', product_model_id: '' }
      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
    },
    resetForm () {
      this.formData = {
        code: '',
        name: '',
        flow_category_id: '',
        product_model_id: '',
        remark: ''
      }
      this.editId = ''
      this.$nextTick(() => {
        this.formCols[0][0].disabled = false
      })
    },
    loadDialogCategories () {
      if (this.categoryOptions.length > 0) return
      getProcessCategoryAll().then(res => {
        this.categoryOptions = this.normalizeResponse(res).list.map(item => ({
          label: item.name,
          value: item.id
        }))
        this.formCols[2][0].options = this.categoryOptions
      })
    },
    loadDialogProducts () {
      if (this.productOptions.length > 0) return
      getProductBatteryAll().then(res => {
        this.productOptions = this.normalizeResponse(res).list.map(item => ({
          label: item.name,
          value: item.product_model_id
        }))
        this.formCols[3][0].options = this.productOptions
      })
    },
    loadSearchCategories () {
      if (this.searchCategoryOptions.length > 0) return
      getProcessCategoryAll().then(res => {
        this.searchCategoryOptions = this.normalizeResponse(res).list
      })
    },
    loadSearchProducts () {
      if (this.searchProductOptions.length > 0) return
      getProductBatteryAll().then(res => {
        this.searchProductOptions = this.normalizeResponse(res).list
      })
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_title')
      this.$nextTick(() => {
        this.$refs.dialogForm && this.$refs.dialogForm.reset()
        this.resetForm()
        this.loadDialogCategories()
        this.loadDialogProducts()
        this.dialogVisible = true
      })
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_title')
      this.editId = row.id
      this.formData = {
        code: row.code,
        name: row.name,
        flow_category_id: row.flow_category_id || '',
        product_model_id: row.product_model_id || '',
        remark: row.remark || ''
      }
      this.loadDialogCategories()
      this.loadDialogProducts()
      this.$nextTick(() => {
        this.formCols[0][0].disabled = true
      })
      this.dialogVisible = true
    },
    openProcessCard (row) {
      this.$router.push({
        name: 'production_configuration-technology_model-technology_flow-process',
        params: { flow_id: row.id },
        query: { flow_name: row.name }
      })
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await createProcessRouting(this.formData)
        } else {
          await editProcessRouting({ ...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) {
      if (row.is_binding_batch === 1) {
        this.$message.warning(this.$t(this.key('batch_bound_no_delete')))
        return
      }
      const cancelled = await this.$confirmAction(
        {
          message: this.key('confirm_delete'),
          title: this.key('tip')
        },
        () => deleteProcessRouting({ id: [row.id] })
      )
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
      this.pagination.current = Math.min(
        this.pagination.current,
        Math.ceil((this.pagination.total - 1) / this.pagination.size) || 1
      )
      this.fetchData()
    },
    async handleCopy (row) {
      const cancelled = await this.$confirmAction(
        {
          message: this.key('confirm_copy'),
          title: this.key('tip')
        },
        () => copyProcessRouting({ id: [row.id] })
      )
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
      this.pagination.current = 1
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.search-bar {
  padding: 10px 0;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
</style>
