<template>
  <el-form class="form" ref="form" v-bind="{ labelWidth, size: 'small' }" :model="formData" :rules="rules">
    <el-row :gutter="10">
      <el-col :span="12">
        <el-form-item label="指标标准">
          <el-select
            v-model="formData.standardId"
            filterable
            :placeholder="message.standardId"
            clearable
            @change="onStandardChange"
            :disabled="!typeId"
            style="width:100%"
          >
            <el-option v-for="item in standards" :key="item.id" :label="item.standardName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-button type="text" size="small">另存为指标标准</el-button>
      </el-col>
    </el-row>
    <el-form-item label="指标参数" prop="standardNames">
      <el-input :value="standardParamNames" type="textarea" rows="3" disabled />
    </el-form-item>
    <BaseTable
      ref="table"
      :columns="cols"
      :data="formData.items"
      style="padding-left:0;padding-right:0; min-height: 600px;"
      v-loading="loading.standardParam"
    >
      <template v-slot:target="{ row }">
        <el-form-item
          :show-message="false"
          label-width="0"
          style="margin-bottom:0"
          v-if="String(row.id).startsWith('__new__')"
        >
          <el-select
            v-model="row.targetId"
            placeholder="请选择参数名称"
            clearable
            @change="() => onParamChange(row)"
            style="width:100%"
          >
            <el-option v-for="param of params" :label="param.targetName" :value="param.targetId" :key="param.id" />
          </el-select>
        </el-form-item>
        <span v-else>
          {{ row.targetName }}
        </span>
      </template>
      <template v-slot:threshold="{ row }">
        <el-row type="flex">
          <el-col>
            <el-form-item :show-message="false" label-width="0" style="margin-bottom:0">
              <el-input-number
                v-model="row.lowerLimit"
                placeholder="下限"
                v-bind="getDefalutNumberProp()"
                :controls="false"
              />
            </el-form-item>
          </el-col>
          <span style="padding: 0 3px">~</span>
          <el-col>
            <el-form-item :show-message="false" label-width="0" style="margin-bottom:0">
              <el-input-number
                v-model="row.upperLimit"
                placeholder="上限"
                v-bind="getDefalutNumberProp()"
                :controls="false"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template v-slot:timeRange="{ row }">
        <el-form-item :show-message="false" label-width="0" style="margin-bottom:0">
          <el-time-picker
            v-model="row.timeRange"
            is-range
            range-separator="~"
            style="width: 100%"
            format="HH:mm"
            value-format="HH:mm"
            size="small"
            prefix-icon=""
            arrow-control
            :clearable="false"
            @change="($event) => onTimeRangeChange($event, row)"
          />
        </el-form-item>
      </template>
      <template v-slot:level="{ row }">
        <el-form-item :show-message="false" label-width="0" style="margin-bottom:0">
          <el-select
            v-model="row.warningLevel"
            placeholder="请选择监预警级别"
            clearable
            @change="() => onLevelChange(row)"
            style="width:100%"
          >
            <el-option v-for="level of levels" :label="level.notes" :value="level.id" :key="level.id" />
          </el-select>
        </el-form-item>
      </template>
      <template v-slot:push="{ row }">
        <el-form-item :show-message="false" label-width="0" style="margin-bottom:0">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="row.istidings"
            size="small"
            style="user-select:none"
          />
        </el-form-item>
      </template>
      <template v-slot:action="{ row, index }">
        <el-form-item :show-message="false" label-width="0" style="margin-bottom:0">
          <el-button type="text" icon="el-icon-plus" @click="onAdd" v-if="index === formData.items.length - 1" />
          <el-button type="text" icon="el-icon-delete" @click="() => onDel(row)" v-if="formData.items.length !== 1" />
        </el-form-item>
      </template>
    </BaseTable>
  </el-form>
</template>

<script lang="ts">
import { Vue, Component, ModelSync, Prop, Watch } from 'vue-property-decorator'
import BaseDialog from '@/components/BaseDialog/index.vue'
import BaseTable from '@/components/BaseTable/index.vue'
import { ElForm } from 'element-ui/types/form'
import { getDefalutNumberProp } from '@/utils/constant'
import { IStandard, IStandardParam } from '../../api/common'
import { standardParamPage } from '../../api/standard'
import { ElTableColumn } from 'element-ui/types/table-column'
import { ElTable } from 'element-ui/types/table'
import moment from 'moment'
import { IDictionary } from '@/api/common'
import { uniqBy } from 'lodash'
import { alignLeft } from '../../utils'

export interface IFormData {
  standardId: number
  items: IThreshold[]
}

export interface IThreshold extends Partial<IStandardParam> {
  timeRange?: (string | Date)[]
}

const getObjectConfig = (value: any) => ({ writable: true, configurable: true, value })
const format = 'HH:mm'
const getDefaultThreshold = (
  id,
  object: IThreshold = {
    /** 有效开始时段 */
    biginTime: undefined,
    /** 有效结束时段 */
    endTime: undefined,
    /** 是否启用0否，1是 */
    isstart: 1,
    /** 是否发送消息（0否，1是） */
    istidings: 1,
    /** 下容差 */
    lowTolerance: undefined,
    /** 下限 */
    lowerLimit: undefined,
    /** 指标表ID */
    targetId: undefined,
    /** 指标单位 */
    targetUnit: undefined,
    /** 上容差 */
    upTolerance: undefined,
    /** 上限 */
    upperLimit: undefined,
    /** 预警级别，字典ID */
    warningLevel: undefined,
    /** 预警级别名称 */
    warningName: undefined
  }
) => {
  const { biginTime = '00:00', endTime = '23:59' } = object
  return Object.defineProperties(
    { ...object, biginTime, endTime },
    {
      id: getObjectConfig(id),
      timeRange: getObjectConfig([moment(biginTime, format).toDate(), moment(endTime, format).toDate()])
    }
  )
}

@Component({ name: 'ThresholdForm', components: { BaseDialog, BaseTable } })
export default class ThresholdForm extends Vue {
  @ModelSync('value', 'change', { type: Object, default: () => ({ standardId: undefined, items: [] }) })
  formData!: IFormData
  @Prop({ type: String, default: '8em' }) labelWidth!: string
  @Prop({ type: Array, default: () => ({}) }) standards!: IStandard[]
  @Prop({ type: Array, default: () => ({}) }) levels!: IDictionary[]
  @Prop({ type: Number }) typeId!: number

  getDefalutNumberProp = getDefalutNumberProp
  $refs!: { form: ElForm; table: ElTable }
  message = {
    standardId: '请选择指标标准'
  }

  loading = {
    standardParam: false
  }

  rules = {
    standardId: [{ required: true, message: this.message.standardId, trigger: 'change' }]
  }

  cols: (Partial<ElTableColumn> & { _slot?: true })[] = [
    {
      prop: 'target',
      label: '指标名称',
      minWidth: '100px',
      _slot: true,
      ...alignLeft()
    },
    { prop: 'threshold', label: '阈值', width: '150px', _slot: true },
    { prop: 'timeRange', label: '时段', width: '130px', _slot: true },
    { prop: 'level', label: '预警级别', width: '140px', _slot: true },
    { prop: 'push', label: '推送', width: '80px', _slot: true },
    { prop: 'action', label: '操作', width: '80px', _slot: true }
  ]

  standardParams: IStandardParam[] = []

  get standardParamNames() {
    return this.standardParams.map((item) => item.targetName).join(', ')
  }

  get params() {
    return uniqBy(this.standardParams, 'targetId')
  }

  async onStandardChange(standardId) {
    this.loading.standardParam = true
    try {
      const {
        result: { records }
      } = await standardParamPage({ standardId, current: 1, size: 9999 })
      this.standardParams = records
      this.formData.items = records.map(({ id, ...rest }, index) => getDefaultThreshold(`${id}-${index}`, rest))
      // console.log(this.$refs.table)
    } catch (error) {
      console.log(error)
    }
    this.$nextTick(() => {
      this.loading.standardParam = false
    })
  }

  onLevelChange(row: IThreshold) {
    const { notes: warningName } = this.levels.find((item) => item.id === row.warningLevel) || {}
    row.warningName = warningName
    // console.log(row)
  }

  onParamChange(row: IThreshold) {
    const { targetName } = this.params.find((item) => item.targetId === row.targetId) || {}
    row.targetName = targetName
  }

  onTimeRangeChange(time, row: IThreshold) {
    console.log(time)
  }

  onAdd(row: IThreshold) {
    const {} = row
    this.formData.items = [...this.formData.items, getDefaultThreshold(`__new__${+new Date()}`)]
  }

  onDel(row: IThreshold) {
    this.formData.items = this.formData.items.filter((item) => item.id !== row.id)
  }

  async validate() {
    return new Promise<IFormData>((resolve, reject) => {
      this.$refs.form.validate((valid) => {
        valid ? resolve(this.formData) : reject()
      })
    })
  }
  @Watch('typeId')
  onStandardsChange() {
    this.standardParams = []
    this.formData.standardId = undefined
    this.formData.items = []
  }
}
</script>
<style lang="scss" scoped>
.form {
  >>> .el-input-number {
    .el-input__inner {
      padding-left: 3px;
      padding-right: 3px;
      text-align: center;
    }
  }
  >>> .el-date-editor--timerange {
    .el-input__icon {
      display: none;
    }
  }
  >>> .el-table {
    .el-table__cell.is-left .cell {
      padding-left: 1.5em;
    }
  }
}
</style>
