<template>
  <d2-container>
    <template #header>
      <el-page-header @back="$router.go(-1)" :content="flowName" style="margin: 10px 0" />
    </template>

    <el-descriptions
      v-if="flowInfo"
      class="margin-top"
      :title="$t(key('flow_info'))"
      :column="4"
      direction="vertical"
      border
    >
      <template #title>
        <span style="color: #409EFF; font-size: 14px;">| {{ $t(key('flow_info')) }}</span>
      </template>
      <el-descriptions-item :label="$t(key('flow_name'))">{{ flowInfo.name }}</el-descriptions-item>
      <el-descriptions-item :label="$t(key('category'))">{{ flowInfo.flow_category_name }}</el-descriptions-item>
      <el-descriptions-item :label="$t(key('product'))">{{ flowInfo.product_model_name }}</el-descriptions-item>
      <el-descriptions-item :label="$t(key('batch_bound'))">
        <el-tag v-if="isBindingBatch" size="small">{{ $t(key('yes')) }}</el-tag>
        <el-tag v-else size="small" type="info">{{ $t(key('no')) }}</el-tag>
      </el-descriptions-item>
    </el-descriptions>

    <div class="card-toolbar">
      <strong v-for="(btn, index) in toolbarButtons" :key="index">
        <el-button
          v-if="btn.hasPermission && __judgeToolbarButton(btn.key)"
          :type="btn.type"
          :size="btn.size || 'mini'"
          :icon="btn.icon"
          @click="btn.onClick"
          :style="btn.cssStyle"
        >
          {{ $t(btn.label) }}
        </el-button>
      </strong>
    </div>

    <page-table
      ref="pageTable"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="[]"
      :row-buttons="[]"
      :pagination="null"
      auto-height
      :table-attrs="{ border: true }"
    >
      <template #col-up="{ row, index }">
        <i
          v-show="index > 0"
          v-if="$permission('/production_configuration/technology_model/technology_flow_process/sort')"
          class="el-icon-sort-up"
          style="cursor: pointer"
          @click="handleMoveUp(row, index)"
        />
      </template>
      <template #col-down="{ row, index }">
        <i
          v-show="index < tableData.length - 1"
          v-if="$permission('/production_configuration/technology_model/technology_flow_process/sort')"
          class="el-icon-sort-down"
          style="cursor: pointer"
          @click="handleMoveDown(row, index)"
        />
      </template>
      <template #col-sort="{ row }">
        {{ row.sort }}
      </template>
      <template #col-handle="{ row, index }">
        <strong v-for="(btn, btnIdx) in rowOperationButtons" :key="btnIdx">
          <i
            :class="btn.icon"
            :style="btn.cssStyle"
            v-if="$permission(btn.auth) && __judgeRowButton(row, btn.key)"
            @click="btn.onClick(row, index)"
          >
            {{ $t(btn.label) }}
          </i>
        </strong>
      </template>
    </page-table>

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

    <technology-flow-model
      :visible.sync="settingVisible"
      :title="settingTitle"
      :type="settingType"
      :code="settingCode"
      :width="settingWidth"
      :plugin-data="settingPluginData"
      @close="settingVisible = false"
      @submit="handleSettingSubmit"
    />

    <result-param
      :visible.sync="resultVisible"
      :title="resultTitle"
      :workingsubclass-id="resultWorkingsubclassId"
      :flow-process-id="resultFlowProcessId"
      @close="resultVisible = false"
    />

    <temperature-compensation
      :visible.sync="temperatureVisible"
      :title="temperatureTitle"
      :flow-process-id="temperatureFlowProcessId"
      @close="temperatureVisible = false"
    />

    <calculation-script
      :visible.sync="calculationVisible"
      :title="calculationTitle"
      :flow-process-id="calculationFlowProcessId"
      @close="calculationVisible = false"
    />

    <el-drawer
      :title="$t(key('view_log'))"
      :visible.sync="drawer"
      size="35%"
      :with-header="false"
    >
      <div style="margin: 20px">
        <div
          v-for="(item, index) in operationLogs"
          :key="index"
          style="padding-bottom: 20px; margin-bottom: 30px"
        >
          <div style="margin-bottom: 10px; color: rgba(0,0,0,.36); font-size: 14px">
            <i class="el-icon-star-on" style="color: #409EFF" />
            <span style="margin-right: 10px; margin-left: 2px">{{ item.nyr_date }}</span>
            <span>{{ item.week }}</span>
          </div>
          <div style="margin-bottom: 10px; display: flex; align-items: center; justify-content: flex-start">
            <div style="margin-right: 10px"><el-avatar size="small"> user </el-avatar></div>
            <div style="color: #8BCF70">{{ item.username }}</div>
          </div>
          <div style="margin-left: 40px; margin-bottom: 10px">
            <span>{{ item.action_name }}</span>
            <span style="color: rgba(0,0,0,.36); font-size: 14px">
              <span style="margin-left: 10px; margin-right: 5px">{{ item.yr_date }}</span>
              <span>{{ item.ampm }}</span>
              <span style="margin-left: 5px">{{ item.time }}</span>
            </span>
          </div>
          <div style="margin-left: 40px; margin-bottom: 10px" v-if="item.process_name">
            <span style="color: rgba(0,0,0,.36); font-size: 14px">
              {{ $t(key('log_operation_step')) }}{{ item.process_name }}
            </span>
          </div>
        </div>
      </div>
    </el-drawer>
  </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 {
  getProcessCardAll,
  createProcessCard,
  editProcessCard,
  deleteProcessCard,
  moveUp,
  moveDown,
  setSetting
} from '@/api/production-master-data/process-routing-card'
import { getWorkingsubclassAll } from '@/api/production-master-data/process-step'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'
import TechnologyFlowModel from './components/technology-flow-model.vue'
import ResultParam from './components/result-param.vue'
import TemperatureCompensation from './components/temperature-compensation.vue'
import CalculationScript from './components/calculation-script.vue'

export default {
  name: 'production-master-data-process-routing-card',
  components: { PageTable, PageDialogForm, TechnologyFlowModel, ResultParam, TemperatureCompensation, CalculationScript },
  mixins: [i18nMixin('page.production_master_data.process_model.process_routing.card'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      flowId: '',
      flowName: '',
      flowInfo: null,
      isBindingBatch: false,
      tableData: [],
      drawer: false,
      operationLogs: [],
      workingsubclassOptions: [],
      workingsubclassRawData: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      settingVisible: false,
      settingTitle: '',
      settingType: '',
      settingCode: '',
      settingWidth: '60%',
      settingPluginData: {},
      settingRowId: '',
      resultVisible: false,
      resultTitle: '',
      resultWorkingsubclassId: '',
      resultFlowProcessId: '',
      temperatureVisible: false,
      temperatureTitle: '',
      temperatureFlowProcessId: '',
      calculationVisible: false,
      calculationTitle: '',
      calculationFlowProcessId: '',
      formData: {
        workingsubclass_id: '',
        code: '',
        name: '',
        pin_check: '0'
      },
      rules: {
        workingsubclass_id: [
          { required: true, message: this.key('select_process_unit'), trigger: 'change' }
        ],
        code: [
          { required: true, message: this.key('enter_step_code'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('length_1_100'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.key('enter_step_name'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('length_1_100'), trigger: 'blur' }
        ]
      },
      columns: [],
      toolbarButtons: [],
      rowOperationButtons: [],
      formCols: [
        [
          {
            type: 'select',
            prop: 'workingsubclass_id',
            label: this.key('process_unit'),
            placeholder: this.key('select_process_unit'),
            clearable: true,
            filterable: true,
            style: { width: '90%' },
            options: [],
            onChange: this.onWorkingsubclassChange
          }
        ],
        [
          {
            type: 'input',
            prop: 'code',
            label: this.key('step_code'),
            placeholder: this.key('enter_step_code'),
            clearable: true,
            disabled: false,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            prop: 'name',
            label: this.key('step_name'),
            placeholder: this.key('enter_step_name'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'select',
            prop: 'pin_check',
            label: this.key('pin_check'),
            placeholder: this.key('select_pin_check'),
            clearable: false,
            style: { width: '90%' },
            options: [
              { label: this.$t(this.key('enable')), value: '1' },
              { label: this.$t(this.key('disable')), value: '0' }
            ]
          }
        ]
      ]
    }
  },
  created () {
    this.flowId = this.$route.params.flow_id || ''
    this.flowName = this.$route.query.flow_name || ''
    this.columns = useTableColumns([
      { prop: 'up', label: '', slot: 'up', width: 40 },
      { prop: 'down', label: '', slot: 'down', width: 40 },
      { prop: 'sort', label: this.key('sort'), slot: 'sort', width: 80 },
      { prop: 'code', label: this.key('step_code'), minWidth: 120 },
      { prop: 'name', label: this.key('step_name'), minWidth: 140 },
      { prop: 'workingsubclass_name', label: this.key('process_unit_name'), minWidth: 140 },
      { prop: 'handle', label: this.key('operation'), slot: 'handle', width: 500 }
    ])

    const btns = useTableButtons({
      toolbar: [
        {
          key: 'add',
          label: this.key('add_step'),
          icon: 'el-icon-plus',
          type: 'primary',
          auth: '/production_configuration/technology_model/technology_flow_process/create',
          onClick: this.openAdd
        },
        {
          key: 'viewLog',
          label: this.key('view_log'),
          icon: 'el-icon-view',
          type: 'warning',
          auth: '/production_configuration/technology_model/technology_flow_process/view_log',
          onClick: this.openLog
        }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons

    this.rowOperationButtons = [
      {
        key: 'edit',
        label: this.key('edit'),
        icon: 'el-icon-edit',
        cssStyle: { marginRight: '10px', cursor: 'pointer' },
        auth: '/production_configuration/technology_model/technology_flow_process/edit',
        onClick: this.openEdit
      },
      {
        key: 'delete',
        label: this.key('delete'),
        icon: 'el-icon-delete',
        cssStyle: { color: 'red', marginRight: '10px', cursor: 'pointer' },
        auth: '/production_configuration/technology_model/technology_flow_process/delete',
        onClick: this.handleDelete
      },
      {
        key: 'setting',
        label: this.key('setting'),
        icon: 'el-icon-setting',
        cssStyle: { color: '#409EFF', marginRight: '10px', cursor: 'pointer' },
        auth: '/production_configuration/technology_model/technology_flow_process/setting',
        onClick: this.openSettingDrawer
      },
      {
        key: 'resultParam',
        label: this.key('result_param'),
        icon: 'el-icon-s-promotion',
        cssStyle: { color: '#E6A23C', marginRight: '10px', cursor: 'pointer' },
        auth: '/production_configuration/technology_model/technology_flow_process/result_params',
        onClick: this.openResultParamDrawer
      },
      {
        key: 'temperature',
        label: this.key('temperature'),
        icon: 'el-icon-magic-stick',
        cssStyle: { color: '#67C23A', marginRight: '10px', cursor: 'pointer' },
        auth: '/production_configuration/technology_model/technology_flow_process/temperature',
        onClick: this.openTemperatureDrawer
      },
      {
        key: 'calculationScript',
        label: this.key('calculation_script'),
        icon: 'el-icon-monitor',
        cssStyle: { color: '#67C23A', marginRight: '10px', cursor: 'pointer' },
        auth: '/production_configuration/technology_model/technology_flow_process/calculation_script',
        onClick: this.openCalculationScriptDrawer
      }
    ]

    if (this.flowId) {
      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 getProcessCardAll({ flow_id: this.flowId })
        const data = res.data || res || {}
        this.tableData = data.process || []
        this.flowInfo = data.flow_data || null
        this.flowName = this.flowName || (this.flowInfo && this.flowInfo.name) || ''
        this.isBindingBatch = data.is_binding_batch === 1
        this.operationLogs = data.technology_flow_operate_log || []
      } finally {
        this.loading = false
      }
    },
    __judgeToolbarButton (key) {
      if (key === 'add' && this.isBindingBatch) return false
      return true
    },
    __judgeRowButton (row, key) {
      if (key === 'setting' && row.setting_plugin) return true
      if (key === 'delete' && !this.isBindingBatch) return true
      if (key === 'temperature' &&
        ['FORMATION', 'YC', 'HC', 'IC', 'FORMATION_SS'].indexOf(row.device_category_code) !== -1) {
        return true
      }
      if (key === 'resultParam') return true
      if (key === 'calculationScript') return true
      if (key === 'edit') return true
      return false
    },
    async handleMoveUp (row, index) {
      if (this.isBindingBatch) {
        this.$message.warning(this.$t(this.key('batch_bound_no_move')))
        return
      }
      if (index <= 0) return
      try {
        await moveUp({
          flow_id: this.flowId,
          move_id: row.id,
          quilt_move_id: this.tableData[index - 1].id,
          move_sort: row.sort,
          quilt_move_sort: this.tableData[index - 1].sort
        })
        this.fetchData()
      } catch (e) { /* 拦截器已处理 */ }
    },
    async handleMoveDown (row, index) {
      if (this.isBindingBatch) {
        this.$message.warning(this.$t(this.key('batch_bound_no_move')))
        return
      }
      if (index >= this.tableData.length - 1) return
      try {
        await moveDown({
          flow_id: this.flowId,
          move_id: row.id,
          quilt_move_id: this.tableData[index + 1].id,
          move_sort: row.sort,
          quilt_move_sort: this.tableData[index + 1].sort
        })
        this.fetchData()
      } catch (e) { /* 拦截器已处理 */ }
    },
    loadWorkingsubclassOptions () {
      if (this.workingsubclassOptions.length > 0) return Promise.resolve()
      return getWorkingsubclassAll().then(res => {
        const list = this.normalizeResponse(res).list
        this.workingsubclassRawData = list
        this.workingsubclassOptions = list.map(item => ({
          label: item.name,
          value: item.id
        }))
        this.formCols[0][0].options = this.workingsubclassOptions
      })
    },
    onWorkingsubclassChange (value) {
      if (!value) return
      const raw = this.workingsubclassRawData.find(item => item.id === value)
      if (!raw) return
      const wsCode = raw.code
      const wsName = raw.name

      const identicalData = this.tableData.filter(
        v => v.workingsubclass_code === wsCode
      )

      if (identicalData.length > 0) {
        const firstCode = identicalData[0].code
        const firstName = identicalData[0].name
        const len = identicalData.length
        this.formData.code = firstCode + '_' + len
        this.formData.name = firstName + '_' + len
      } else {
        this.formData.code = this.flowId + '_' + wsCode
        this.formData.name = this.flowId + '_' + wsName
      }

      const autoPinDevices = ['IC', 'HC', 'YC', 'OCV01', 'OCV02', 'OCV03', 'OCV04', 'OCV05', 'OCV06', 'DCIR', 'FORMATION', 'FORMATION_SS']
      this.formData.pin_check = autoPinDevices.includes(wsCode) ? '1' : '0'
    },
    resetForm () {
      this.formData = { workingsubclass_id: '', code: '', name: '', pin_check: '0' }
      this.editId = ''
      this.$nextTick(() => {
        this.formCols[0][0].disabled = false
        this.formCols[1][0].disabled = false
        this.formCols[2][0].disabled = false
      })
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_step')
      this.loadWorkingsubclassOptions().then(() => {
        this.$nextTick(() => {
          this.$refs.dialogForm && this.$refs.dialogForm.reset()
          this.resetForm()
          this.dialogVisible = true
        })
      })
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_step')
      this.editId = row.id
      this.formData = {
        workingsubclass_id: row.workingsubclass_id || '',
        code: row.code,
        name: row.name,
        pin_check: row.pin_check !== undefined ? String(row.pin_check) : '0'
      }
      this.loadWorkingsubclassOptions().then(() => {
        this.$nextTick(() => {
          this.formCols[0][0].disabled = true
          this.formCols[1][0].disabled = true
          this.formCols[2][0].disabled = true
        })
      })
      this.dialogVisible = true
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await createProcessCard({ ...this.formData, flow_id: this.flowId })
        } else {
          await editProcessCard({ ...this.formData, id: this.editId, flow_id: this.flowId })
        }
        this.$message.success(this.$t(this.key('operation_success')))
        this.dialogVisible = false
        this.fetchData()
      } finally {
        this.submitting = false
      }
    },
    onDialogClose () {
      this.resetForm()
    },
    async handleDelete (row, index) {
      const cancelled = await this.$confirmAction(
        {
          message: this.key('confirm_delete'),
          title: this.key('tip')
        },
        () => deleteProcessCard({ id: [row.id], flow_id: this.flowId })
      )
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
      this.fetchData()
    },
    openLog () {
      this.drawer = true
    },
    openSettingDrawer (row) {
      this.settingRowId = row.id
      this.settingTitle = `【${row.name}】${this.$t(this.key('setting'))}`
      this.settingType = row.setting_plugin || ''
      this.settingCode = row.workingsubclass_code || row.code || ''
      this.settingWidth = row.setting_plugin_width ? `${row.setting_plugin_width}%` : '35%'
      this.settingPluginData = row.setting || {}
      this.settingVisible = true
    },
    openResultParamDrawer (row) {
      this.resultTitle = `【${row.name}】${this.$t(this.key('result_param'))}`
      this.resultWorkingsubclassId = row.workingsubclass_id || ''
      this.resultFlowProcessId = row.id || ''
      this.resultVisible = true
    },
    openTemperatureDrawer (row) {
      this.temperatureTitle = `【${row.name}】${this.$t(this.key('temperature'))}`
      this.temperatureFlowProcessId = row.id || ''
      this.temperatureVisible = true
    },
    openCalculationScriptDrawer (row) {
      this.calculationTitle = `【${row.name}】${this.$t(this.key('calculation_script'))}`
      this.calculationFlowProcessId = row.id || ''
      this.calculationVisible = true
    },
    async handleSettingSubmit (data) {
      await setSetting({
        id: this.settingRowId,
        flow_id: this.flowId,
        setting: JSON.stringify(data)
      })
      this.$message.success(this.$t(this.key('operation_success')))
      this.settingVisible = false
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.card-toolbar {
  margin-bottom: 15px;
  margin-top: -10px;
}
/deep/ .el-page-header__content {
  font-weight: bold;
}
</style>
