<template>
  <div class="app-container">
    <div class="filter-container">
      营养素：
      <el-select
        ref="nutrientSelect"
        v-model="params.nutrientId"
        filterable
        remote
        reserve-keyword
        style="width: 200px;margin-left: 10px;"
        placeholder="请输入营养素关键词"
        :remote-method="queryNutrients"
        :loading="loading"
      >
        <el-option v-for="item in nutrients" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      营养素计量单位：
      <el-autocomplete
        class="inline-input"
        v-model="params.unit"
        :fetch-suggestions="queryUnits"
        placeholder="单位关键词"
      />
      Nv_Spec计量:
      <el-input
        v-model="params.nvSpec"
        style="width: 80px;"
        class="filter-item"
      />
      Nv_Spec计量单位：
      <el-autocomplete
        class="inline-input"
        v-model="params.nvSpecUnit"
        :fetch-suggestions="queryUnits"
        placeholder="单位关键词"
      />
      信息来源：
      <el-autocomplete
        v-model="params.source"
        :fetch-suggestions="querySources"
        placeholder="请输入信息来源"
      />
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        @click="addNutrient"
      >
        添加
      </el-button>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-top: 10px"
      >
        <el-table-column type="index" label="序号" align="center" width="60px" />
        <el-table-column label="营养素名称" align="center">
          <template slot-scope="{row}">
            <span>{{ row.nutrientName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="营养素计量单位" align="center" width="150px">
          <template slot-scope="{row}">
            <template v-if="row.edit">
              <el-autocomplete
                class="inline-input"
                v-model="row.unit"
                :fetch-suggestions="queryUnits"
                placeholder="单位关键词"
              />
            </template>
            <span v-else>{{ row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Nv_Spec" align="center" width="100px">
          <template slot-scope="{row}">
            <template v-if="row.edit">
              <el-input
                v-model="row.nvSpec"
                class="filter-item"
              />
            </template>
            <span v-else>{{ row.nvSpec }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Nv_Spec单位" align="center" width="150px">
          <template slot-scope="{row}">
            <template v-if="row.edit">
              <el-autocomplete
                class="inline-input"
                v-model="row.nvSpecUnit"
                :fetch-suggestions="queryUnits"
                placeholder="单位关键词"
              />
            </template>
            <span v-else>{{ row.nvSpecUnit }}</span>
          </template>
        </el-table-column>


        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="320px">
          <template slot-scope="{row}">
            <template v-if="row.edit">
              <el-button
                type="success"
                size="mini"
                @click="confirmEdit(row)"
              >
                提交
              </el-button>
              <el-button
                type="danger"
                size="mini"
                @click="fetchNutrients"
              >
                取消
              </el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="primary" @click="row.edit=true">编辑</el-button>
              <el-button type="primary" size="mini" @click="updateSort(row, 0)">
                上移
              </el-button>
              <el-button type="primary" size="mini" @click="updateSort(row, 1)">
                下移
              </el-button>
              <el-button size="mini" type="danger" @click="removeNutrient(row)">
                删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getList } from '@/api/nutrient'
import { getList as getUnits } from '@/api/unit'
import { getNutrients, addTemplateNutrient, updateTemplateNutrient, removeNutrient,
  updateTemplateNutrientSort } from '@/api/nutrientTemplate'

export default {
  name: 'Detail',
  components: {},
  data() {
    return {
      templateId: '',
      tableKey: 0,
      listLoading: false,
      list: [],
      units: [],
      nutrients: [],
      params: {},
      loading: false,
      unitLoading: false,
      sources: [{ value: "营养标签" }, { value: "食品官方资料" }, { value: "计算值" }]
    }
  },
  created() {
    this.templateId = this.$route.params.id
    if (!this.templateId) {
      this.$message.error('获取数据失败')
      this.$router.push({ path: '/nutrient-template' })
    }
    this.fetchNutrients()
    this.queryNutrients()
    this.$nextTick(() => {
      this.$refs['nutrientSelect'].focus()
    })
  },
  methods: {
    addNutrient() {
      if (this.params.nutrientId) {
        addTemplateNutrient(this.templateId, this.params).then(res => {
          this.fetchNutrients()
          this.$notify.success('添加成功')
          this.params = {}
          this.$nextTick(() => {
            this.$refs['nutrientSelect'].focus()
          })
        }).catch(res => {
          this.$message.error(res.data.message)
        })
      } else {
        this.$message.error('未选择营养素')
      }
    },
    confirmEdit(row) {
      updateTemplateNutrient(this.templateId, row.nutrientId, row).then(res => {
        this.fetchNutrients()
        this.$notify.success('提交成功')
      }).catch(res => {
        this.$message.error(res.data.message)
      })
    },
    updateSort(row, type) {
      updateTemplateNutrientSort(this.templateId, row.nutrientId, { type }).then(res => {
        this.fetchNutrients()
        this.$notify.success('提交成功')
      }).catch(res => {
        this.fetchNutrients()
        this.$message.error(res.data.message)
      })
    },
    queryNutrients(query) {
      getList({ query }).then(res => {
        this.nutrients = res.data.list
      }).catch(() => {
        this.nutrients = []
      })
    },
    queryUnits(query, cb) {
      let units = []
      getUnits({ query }).then(res => {
        res.data.list.forEach(item => units.push({ value: item.name }))
        cb(units)
      })
    },
    fetchNutrients() {
      this.listLoading = true
      getNutrients(this.templateId).then(res => {
        this.list = res.data
        this.listLoading = false
        if (this.list.length > 0) {
          this.$set(this.params, "nvSpec", this.list[0].nvSpec)
          this.$set(this.params, "nvSpecUnit", this.list[0].nvSpecUnit)
        } else {
          this.$set(this.params, 'nvSpec', null)
          this.$set(this.params, 'nvSpecUnit', null)
        }
      }).catch(() => {
        this.$message.error('获取数据失败')
        this.listLoading = false
        this.$router.push({ path: '/nutrient-template' })
      })
    },
    removeNutrient(row) {
      removeNutrient(this.templateId, row.nutrientId).then(res => {
        this.fetchNutrients()
        this.$notify.success('提交成功')
      }).catch(res => {
        this.fetchNutrients()
        this.$message.error(res.data.message)
      })
    },
    querySources(query, cb) {
      let sources = this.sources
      let results = query ? sources.filter(this.sourcesFilter(query)) : sources;
      cb(results)
    },
    sourcesFilter(query) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(query.toLowerCase()) === 0);
      };
    }
  }
}
</script>

<style scoped>

</style>
