<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form ref="form" :inline="true" :model="form" size="mini">
          <el-form-item :label="$t(key('battery_id'))" prop="battery_ids">
            <el-input
              v-model="form.battery_ids"
              :placeholder="$t(key('enter_battery_id'))"
              class="battery-input"
              clearable
            >
              <el-button slot="append" icon="el-icon-document-add" @click="openBatchInput" />
            </el-input>
          </el-form-item>

          <el-form-item
            v-show="showProcess"
            :label="$t(key('select_process_to_change'))"
            prop="next_process_code"
          >
            <el-select
              v-model="form.next_process_code"
              filterable
              clearable
              :placeholder="$t(key('please_select_process'))"
              style="width:220px"
              @change="syncProcessOptions"
            >
              <el-option
                v-for="item in processOptions"
                :key="item.id || item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t(key('clear_class_sign'))" prop="classname_sign">
            <el-radio v-model="form.classname_sign" label="1">{{ $t(key('yes')) }}</el-radio>
            <el-radio v-model="form.classname_sign" label="2">{{ $t(key('no')) }}</el-radio>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              :disabled="loading"
              :loading="loading"
              @click="verifyData"
            >
              {{ $t(key('verify_data')) }}
            </el-button>
            <el-button icon="el-icon-refresh" :disabled="loading" @click="resetForm">
              {{ $t(key('reset')) }}
            </el-button>
            <el-button type="warning" :disabled="loading" @click="changeProcess">
              {{ $t(key('change_process')) }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <page-table
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="[]"
      :row-buttons="[]"
      :pagination="null"
      :table-attrs="{ size: 'mini', rowKey: 'id', highlightCurrentRow: true }"
      auto-height
      @selection-change="onSelectionChange"
    >
      <template #empty>
        <el-empty :description="$t('暂无数据')" :image-size="80" />
      </template>
    </page-table>

    <el-dialog :title="$t(key('multi_battery_input'))" :visible.sync="dialogVisible" width="520px">
      <el-form>
        <el-form-item :label="$t(key('input_rule'))">
          <el-input v-model="dialogBatteryIds" type="textarea" :rows="8" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="mini" @click="dialogVisible = false">{{ $t(key('cancel')) }}</el-button>
        <el-button size="mini" type="primary" @click="confirmBatchInput">{{ $t(key('confirm')) }}</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { i18nMixin } from '@/composables/useI18n'
import PageTable from '@/components/page-table'
import {
  verifyBatteryProcessInfo,
  changeBatteryProcess
} from '@/api/planning-production/process-execution'

export default {
  name: 'planning-production-process-execution',
  components: { PageTable },
  mixins: [i18nMixin('page.planning_production.production_monitoring.process_execution')],
  data () {
    return {
      loading: false,
      showProcess: false,
      form: {
        battery_ids: '',
        classname_sign: '2',
        next_process_code: '',
        processOptions: []
      },
      processOptions: [],
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogBatteryIds: ''
    }
  },
  computed: {
    columns () {
      return useTableColumns([
        { prop: 'battery_id', label: this.key('battery_id'), minWidth: 180 },
        { prop: 'batch', label: this.key('batch'), minWidth: 150, showOverflowTooltip: true },
        { prop: 'tray', label: this.key('tray'), minWidth: 100, showOverflowTooltip: true },
        { prop: 'lot', label: this.key('lot'), minWidth: 80, showOverflowTooltip: true },
        { prop: 'class', label: this.key('class_type'), minWidth: 80, showOverflowTooltip: true },
        { prop: 'classname', label: this.key('class'), minWidth: 80, showOverflowTooltip: true },
        { prop: 'process_code', label: this.key('previous_process'), minWidth: 180 },
        { prop: 'next_process_code', label: this.key('current_process'), minWidth: 180, showOverflowTooltip: true }
      ], {
        selectionWidth: 55,
        indexWidth: 55
      }).map(col => {
        if (col.type === 'index') col.label = this.key('sort')
        return col
      })
    }
  },
  methods: {
    ensureBatteryInput () {
      if (this.form.battery_ids) return true
      this.$message.warning(this.$t(this.key('please_enter_battery_id_data')))
      return false
    },
    openBatchInput () {
      this.form.battery_ids = ''
      this.dialogBatteryIds = ''
      this.showProcess = false
      this.processOptions = []
      this.dialogVisible = true
    },
    confirmBatchInput () {
      const value = this.dialogBatteryIds
        .trim()
        .split('\n')
        .map(item => item.trim())
        .filter(Boolean)
        .join(',')
      this.form.battery_ids = value
      this.dialogVisible = false
    },
    syncProcessOptions () {
      this.form.processOptions = this.processOptions
    },
    normalizeProcessPayload (res) {
      const payload = res && res.code !== undefined && res.data !== undefined ? res.data : res
      if (
        payload &&
        !Array.isArray(payload) &&
        payload.data &&
        !Array.isArray(payload.data) &&
        (payload.data.flow_process || payload.data.data)
      ) {
        return payload.data
      }
      return payload || {}
    },
    normalizeProcessRows (payload) {
      if (Array.isArray(payload)) return payload
      return Array.isArray(payload.data) ? payload.data : []
    },
    verifyData () {
      if (!this.ensureBatteryInput()) return
      this.loading = true
      verifyBatteryProcessInfo(this.form)
        .then(res => {
          const data = this.normalizeProcessPayload(res)
          this.processOptions = data.flow_process || []
          this.tableData = this.normalizeProcessRows(data)
          this.showProcess = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    changeProcess () {
      if (!this.ensureBatteryInput()) return
      if (!this.form.next_process_code) {
        this.$message.warning(this.$t(this.key('please_select_process')))
        return
      }
      this.loading = true
      changeBatteryProcess(this.form)
        .then(res => {
          const data = this.normalizeProcessPayload(res)
          this.tableData = this.normalizeProcessRows(data)
          this.$message.success(this.$t(this.key('change_process_success')))
        })
        .finally(() => {
          this.loading = false
        })
    },
    resetForm () {
      this.$refs.form.resetFields()
      this.showProcess = false
      this.processOptions = []
      this.tableData = []
    },
    onSelectionChange (rows) {
      this.selectedRows = rows
    }
  }
}
</script>

<style scoped>
.search-bar {
  margin-bottom: -18px;
}
.battery-input {
  width: 360px;
}
</style>
