<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="handleClose"
    :width="width"
  >
    <component
      :is="pluginComponent"
      ref="plugin"
      :type="type"
      :code="code"
      :setting-json="pluginData"
      :workingsubclass-code="code"
      @submit="handleChildSubmit"
    />
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">{{ $t(key('cancel')) }}</el-button>
      <el-button type="primary" size="small" @click="handleFormSubmit">{{ $t(key('confirm')) }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { i18nMixin } from '@/composables/useI18n'

function isJson (value) {
  if (typeof value !== 'string') return false
  try {
    JSON.parse(value)
    return true
  } catch (e) {
    return false
  }
}

function parseSetting (value, fallback = { process: {} }) {
  if (value === undefined || value === null || value === '') return JSON.parse(JSON.stringify(fallback))
  if (typeof value === 'object') return JSON.parse(JSON.stringify(value))
  if (isJson(value)) return JSON.parse(value)
  return JSON.parse(JSON.stringify(fallback))
}

const WaitPlugin = {
  name: 'ProcessStepWaitPlugin',
  mixins: [i18nMixin('page.production_master_data.process_model.process_step')],
  props: { settingJson: { default: '' } },
  data () {
    return {
      json: { process: {} },
      form: { time: undefined, time_range: undefined, alert: '0' },
      rules: {
        time: [{ pattern: /^[0-9]\d*$/, message: '请输入大于等于 0 的整数', trigger: 'change' }],
        time_range: [{ pattern: /^[0-9]\d*$/, message: '请输入大于等于 0 的整数', trigger: 'change' }]
      }
    }
  },
  watch: {
    settingJson: {
      handler (val) {
        const json = parseSetting(val, { process: {} })
        this.json = json
        this.form = {
          time: json.process && json.process.time !== undefined ? json.process.time : undefined,
          time_range: json.process && json.process.time_range !== undefined ? json.process.time_range : undefined,
          alert: json.process && json.process.alert !== undefined ? json.process.alert : '0'
        }
      },
      immediate: true
    },
    form: {
      handler (val) {
        this.json = { process: { ...val } }
      },
      deep: true
    }
  },
  methods: {
    handleFormSubmit () {
      this.$refs.form.validate(valid => {
        if (!valid) {
          this.$message.error(this.$t(this.key('validation_fail')))
          return
        }
        this.$emit('submit', this.json)
      })
    }
  },
  template: `
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="mini">
      <el-form-item label="静置时间" prop="time">
        <el-input v-model="form.time" placeholder="请输入静置时间" clearable>
          <template slot="append">分钟</template>
        </el-input>
      </el-form-item>
      <el-form-item label="精度范围" prop="time_range">
        <el-input v-model="form.time_range" placeholder="请输入精度范围" clearable>
          <template slot="append">分钟</template>
        </el-input>
      </el-form-item>
    </el-form>
  `
}

const JsonPlugin = {
  name: 'ProcessStepJsonPlugin',
  mixins: [i18nMixin('page.production_master_data.process_model.process_step')],
  props: {
    settingJson: { default: '' },
    type: { type: String, default: '' },
    code: { type: String, default: '' }
  },
  data () {
    return {
      activeTab: 'process',
      json: { process: {} },
      textarea: '{}'
    }
  },
  watch: {
    settingJson: {
      handler (val) {
        this.json = parseSetting(val, { process: {} })
        this.textarea = JSON.stringify(this.json.process || {}, null, 2)
      },
      immediate: true
    }
  },
  methods: {
    handleFormSubmit () {
      if (!this.textarea) {
        this.$message.info('输入内容不能为空')
        return
      }
      try {
        this.json.process = JSON.parse(this.textarea)
        this.$emit('submit', this.json)
      } catch (e) {
        this.$message.error(this.$t(this.key('json_format_error')))
      }
    }
  },
  template: `
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="设定值" name="process">
        <el-alert
          v-if="type || code"
          :title="[type, code].filter(Boolean).join(' / ')"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom:12px"
        />
        <el-input v-model="textarea" type="textarea" :rows="15" placeholder="请输入内容" />
      </el-tab-pane>
      <el-tab-pane label="json" name="json">
        <tree-view :data="json" />
      </el-tab-pane>
    </el-tabs>
  `
}

const FormationPlugin = {
  name: 'ProcessStepFormationPlugin',
  props: {
    settingJson: { default: '' },
    workingsubclassCode: { type: String, default: '' }
  },
  data () {
    return {
      activeTab: 'process',
      json: { action: 'start', time: new Date(), process: [], setting: {} },
      globalSetting: {},
      tableData: [],
      stationList: [
        { label: '结束', value: '6' },
        { label: '恒流充电', value: '1' },
        { label: '恒流恒压充电', value: '2' },
        { label: '搁置', value: '3' },
        { label: '恒流放电', value: '4' },
        { label: '循环', value: '5' },
        { label: '恒流恒压放电', value: '12' }
      ],
      timeOverList: [
        { label: '', value: '' },
        { label: 'OFF', value: 'OFF' },
        { label: 'TYPE_A', value: 'TYPE_A' },
        { label: 'TYPE_B', value: 'TYPE_B' }
      ],
      globalFields: [
        { prop: 'contact_check', label: '接触检查报警', unit: 'PIN' },
        { prop: 'curve_sampling_time', label: '曲线取样时间', unit: 's' },
        { prop: 'device_emg_voltage', label: '急停电压', unit: 'mV' },
        { prop: 'alarm_temperature_upper', label: '库位温度上限', unit: '℃' },
        { prop: 'fire_temperature_upper', label: '库位消防上限', unit: '℃' },
        { prop: 'upper_charging_voltage', label: '充电上限电压', unit: 'mV' },
        { prop: 'lower_charging_voltage', label: '充电下限电压', unit: 'mV' },
        { prop: 'upper_charging_current', label: '充电上限电流', unit: 'mA' },
        { prop: 'lower_charging_current', label: '充电下限电流', unit: 'mA' },
        { prop: 'upper_charging_capacity', label: '充电上限容量', unit: 'mA/h' },
        { prop: 'lower_charging_capacity', label: '充电下限容量', unit: 'mA/h' },
        { prop: 'upper_discharge_voltage', label: '放电上限电压', unit: 'mV' },
        { prop: 'lower_discharge_voltage', label: '放电下限电压', unit: 'mV' },
        { prop: 'upper_discharge_current', label: '放电上限电流', unit: 'mA' },
        { prop: 'lower_discharge_current', label: '放电下限电流', unit: 'mA' },
        { prop: 'upper_discharge_capacity', label: '放电上限容量', unit: 'mA/h' },
        { prop: 'lower_discharge_capacity', label: '放电下限容量', unit: 'mA/h' }
      ],
      processColumns: [
        { prop: 'station', label: '工步状态', width: 120, type: 'select', options: 'stationList' },
        { prop: 'time', label: '时间(秒)', width: 120 },
        { prop: 'current', label: '电流(mA)', width: 120 },
        { prop: 'upperVoltage', label: '上限电压(mV)', width: 120 },
        { prop: 'lowerVoltage', label: '下限电压(mV)', width: 120 },
        { prop: 'stop_DeltaVoltage', label: 'ΔV(mV)', width: 100 },
        { prop: 'stop_Current', label: '终止电流(mA)', width: 120 },
        { prop: 'stop_Capacity', label: '终止容量(mA/h)', width: 130 },
        { prop: 'cct_begin', label: 'CCT下限(s)', width: 100 },
        { prop: 'cct_end', label: 'CCT上限(s)', width: 100 },
        { prop: 'time_over', label: 'TIMEOVER', width: 120, type: 'select', options: 'timeOverList' },
        { prop: 'temperature', label: '温度(℃)', width: 100 },
        { prop: 'upperTemperature', label: '温度上限(℃)', width: 120 },
        { prop: 'lowerTemperature', label: '温度下限(℃)', width: 120 },
        { prop: 'pressure', label: '压力kg', width: 100 }
      ]
    }
  },
  watch: {
    settingJson: {
      handler (val) {
        const parsed = parseSetting(val, {
          action: 'start',
          time: new Date(),
          process: [],
          setting: { contact_check: '0', curve_sampling_time: 10 }
        })
        parsed.process = Array.isArray(parsed.process) ? parsed.process : []
        parsed.setting = parsed.setting || {}
        this.json = parsed
        this.globalSetting = { ...parsed.setting }
        for (const key of this.globalFields.map(item => item.prop)) {
          if (Object.prototype.hasOwnProperty.call(parsed, key) && !Object.prototype.hasOwnProperty.call(this.globalSetting, key)) {
            this.$set(this.globalSetting, key, parsed[key])
          }
        }
        this.tableData = parsed.process.map(row => ({
          ...row,
          station: row.station !== undefined && row.station !== null ? String(row.station) : '',
          time_over: row.time_over !== undefined && row.time_over !== null ? String(row.time_over) : ''
        }))
      },
      immediate: true
    },
    globalSetting: {
      handler () {
        this.syncJson()
      },
      deep: true
    },
    tableData: {
      handler () {
        this.syncJson()
      },
      deep: true
    }
  },
  methods: {
    syncJson () {
      const setting = {}
      Object.keys(this.globalSetting || {}).forEach(key => {
        const value = this.globalSetting[key]
        if (value !== '' && value !== undefined && value !== null) {
          setting[key] = this.toNumberIfNumeric(value)
        }
      })
      const process = this.tableData.map(row => {
        const item = {}
        Object.keys(row).forEach(key => {
          const value = row[key]
          if (value !== '' && value !== undefined && value !== null) {
            item[key] = key === 'time_over' ? value : this.toNumberIfNumeric(value)
          }
        })
        return item
      })
      if (process[0] && setting.contact_check !== undefined) {
        process[0].contact_check = setting.contact_check
      }
      this.json = {
        ...this.json,
        process,
        setting
      }
    },
    toNumberIfNumeric (value) {
      if (value === '' || value === null || value === undefined) return value
      return /^-?\d+(\.\d+)?$/.test(String(value)) ? Number(value) : value
    },
    rowClassName ({ row }) {
      const station = String(row.station)
      if (station === '5') return 'formation-row-cycle'
      if (station === '1') return 'formation-row-charge'
      if (station === '2') return 'formation-row-charge-cv'
      if (station === '3') return 'formation-row-rest'
      if (station === '4') return 'formation-row-discharge'
      return ''
    },
    addRow () {
      if (this.tableData.some(row => String(row.station) === '6')) {
        this.$message.info('已有结束工步，不能新增')
        return
      }
      this.tableData.push({ station: '' })
    },
    removeRow (index) {
      this.tableData.splice(index, 1)
    },
    moveUp (index) {
      if (index <= 0) return
      const row = this.tableData.splice(index, 1)[0]
      this.tableData.splice(index - 1, 0, row)
    },
    moveDown (index) {
      if (index >= this.tableData.length - 1) return
      const row = this.tableData.splice(index, 1)[0]
      this.tableData.splice(index + 1, 0, row)
    },
    stationChange (row) {
      if (String(row.station) === '5') {
        Object.keys(row).forEach(key => {
          if (key !== 'station') this.$set(row, key, '')
        })
      }
      if (String(row.station) === '6') {
        const index = this.tableData.indexOf(row)
        this.tableData = this.tableData.slice(0, index + 1)
      }
    },
    showMsg (message) {
      this.$message.warning(message)
    },
    validateProcess () {
      if (!this.tableData.some(row => String(row.station) === '6')) {
        this.$message.info('检测到没有添加结束工步')
        return false
      }
      const process = this.json.process || []
      for (let n = 0; n < process.length; n++) {
        const row = process[n]
        const station = Number(row.station)
        const miss = name => {
          this.showMsg(`第${n + 1}工步的必填项 【${name}】 没有填写`)
          return false
        }
        if ((this.workingsubclassCode === 'HC' || this.workingsubclassCode === 'FR') && station !== 6) {
          if (row.pressure === undefined || row.pressure === '') return miss('压力')
          if (row.temperature === undefined || row.temperature === '') return miss('温度')
        }
        if (station === 3) {
          if (row.time === undefined || row.time === '') return miss('工作时间')
        } else if (station === 12 || station === 2) {
          if (row.time === undefined || row.time === '') return miss('工作时间')
          if (row.current === undefined || row.current === '') return miss('电流')
          if (row.stop_Current === undefined || row.stop_Current === '') return miss('终止电流')
          if (station === 12 && (row.lowerVoltage === undefined || row.lowerVoltage === '')) return miss('下限电压')
          if (station === 2 && (row.upperVoltage === undefined || row.upperVoltage === '')) return miss('上限电压')
        } else if (station === 4 || station === 1) {
          if (row.time === undefined || row.time === '') return miss('工作时间')
          if (row.current === undefined || row.current === '') return miss('电流')
          if (station === 4 && (row.lowerVoltage === undefined || row.lowerVoltage === '')) return miss('下限电压')
          if (station === 1 && (row.upperVoltage === undefined || row.upperVoltage === '')) return miss('上限电压')
        }
      }
      return true
    },
    handleFormSubmit () {
      this.syncJson()
      if (!this.validateProcess()) return
      this.$emit('submit', this.json)
    }
  },
  template: `
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="设定值" name="process">
        <el-divider content-position="left">全局配置</el-divider>
        <el-form :model="globalSetting" size="mini" label-width="130px" class="formation-global-form">
          <el-row :gutter="12">
            <el-col v-for="item in globalFields" :key="item.prop" :span="8">
              <el-form-item :label="item.label">
                <el-input v-model="globalSetting[item.prop]" placeholder="请输入内容" clearable>
                  <el-button slot="append">{{ item.unit }}</el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-divider content-position="left">设置工步</el-divider>
        <el-button type="primary" icon="el-icon-plus" size="mini" style="margin-bottom:10px" @click="addRow">新增一行</el-button>
        <el-table
          :data="tableData"
          border
          stripe
          size="mini"
          height="350"
          :row-class-name="rowClassName"
          style="width:100%"
        >
          <el-table-column width="56" fixed>
            <template slot-scope="{ $index }">
              <i v-if="$index > 0" class="el-icon-sort-up formation-sort" @click="moveUp($index)" />
              <i v-if="$index < tableData.length - 1" class="el-icon-sort-down formation-sort" @click="moveDown($index)" />
            </template>
          </el-table-column>
          <el-table-column label="工步" width="56" fixed>
            <template slot-scope="{ $index }">{{ $index + 1 }}</template>
          </el-table-column>
          <el-table-column
            v-for="column in processColumns"
            :key="column.prop"
            :label="column.label"
            :width="column.width"
            :fixed="column.prop === 'station'"
          >
            <template slot-scope="{ row }">
              <el-select
                v-if="column.type === 'select'"
                v-model="row[column.prop]"
                size="mini"
                clearable
                @change="column.prop === 'station' ? stationChange(row) : undefined"
              >
                <el-option
                  v-for="option in $data[column.options]"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <el-input v-else v-model="row[column.prop]" size="mini" type="number" clearable />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template slot-scope="{ $index }">
              <el-button type="text" size="mini" style="color:#F56C6C" @click="removeRow($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="json" name="json">
        <tree-view :data="json" />
      </el-tab-pane>
    </el-tabs>
  `
}

export default {
  name: 'ProcessStepSettingDialog',
  components: { WaitPlugin, JsonPlugin, FormationPlugin },
  mixins: [i18nMixin('page.production_master_data.process_model.process_step')],
  props: {
    type: { type: String, default: '' },
    code: { type: String, default: '' },
    title: { type: String, default: '' },
    width: { type: String, default: '50%' },
    visible: { type: Boolean, default: false },
    pluginData: { default: '' }
  },
  computed: {
    pluginComponent () {
      if (this.type === 'WaitPlugin') return 'WaitPlugin'
      if (this.type === 'FormationPlugin') return 'FormationPlugin'
      return 'JsonPlugin'
    }
  },
  methods: {
    handleClose () {
      this.$emit('close')
    },
    handleFormSubmit () {
      this.$refs.plugin && this.$refs.plugin.handleFormSubmit()
    },
    handleChildSubmit (data) {
      this.$emit('submit', data)
    }
  }
}
</script>

<style scoped>
.formation-global-form /deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 8px;
}
.formation-sort {
  cursor: pointer;
  margin-right: 4px;
  color: #409EFF;
}
/deep/ .formation-row-cycle {
  background-color: #ffc0ff !important;
}
/deep/ .formation-row-charge {
  background-color: #ffff00 !important;
}
/deep/ .formation-row-charge-cv {
  background-color: #ffffc0 !important;
}
/deep/ .formation-row-rest {
  background-color: #e0e0e0 !important;
}
/deep/ .formation-row-discharge {
  background-color: #c0c0c0 !important;
}
</style>
