<template>
  <div class="app-container">
    <div class="filter-container">
      营养素:
      <el-select
        ref="nutrientSelect"
        v-model="params.nutrientId"
        filterable
        remote
        reserve-keyword
        :default-first-option="true"
        style="width: 200px;margin-left: 10px;"
        placeholder="请输入营养素关键词"
        :remote-method="queryNutrients"
        :loading="loading"
        @change="nutrientChanged"
      >
        <el-option v-for="item in nutrients" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      计量:
      <el-radio v-model="params.radio" :label="0" @change="radioChange(params)">值</el-radio>
      <el-radio v-model="params.radio" :label="1" @change="radioChange(params)">范围</el-radio>
      <el-radio v-model="params.radio" :label="2" @change="radioChange(params)">误差</el-radio>
      <div v-if="params.radio === 1" style="display: inline-block">
        大于等于:
        <el-input v-model="params.quantityMin" style="width: 80px;" class="filter-item" />
        小于等于:
        <el-input v-model="params.quantityMax" style="width: 80px;" class="filter-item" />
      </div>
      <div v-else-if="params.radio === 2" style="display: inline-block">
        基准：
        <el-input v-model="params.quantity" style="width: 80px;" class="filter-item" />
        ±：
        <el-input v-model="params.stdError" style="width: 80px;" class="filter-item" />
      </div>
      <el-input
        v-else
        v-model="params.quantity"
        style="width: 80px;"
        class="filter-item"
      />
      <el-autocomplete
        class="inline-input"
        v-model="params.unit"
        :fetch-suggestions="queryNutrientUnits"
        placeholder="单位关键词"
      />
      NRV%:
      <el-input
        v-model="params.nrvPercent"
        style="width: 80px;"
        class="filter-item"
      />
      Nv_Spec计量:
      <el-input
        v-model="params.nvSpec"
        style="width: 80px;"
        class="filter-item"
      />
      <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>
    </div>

    <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="150">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-radio v-model="row.radio" :label="0" @change="radioChange(row)">值</el-radio>
            <el-radio v-model="row.radio" :label="1" @change="radioChange(row)">范围</el-radio>
            <el-radio v-model="row.radio" :label="2" @change="radioChange(row)">误差</el-radio>
            <div v-if="row.radio === 1" style="display: inline-block">
              大于等于:
              <el-input v-model="row.quantityMin" />
              小于等于:
              <el-input v-model="row.quantityMax" />
            </div>
            <div v-else-if="row.radio === 2" style="display: inline-block">
              基准：
              <el-input v-model="row.quantity" />
              ±：
              <el-input v-model="row.stdError" />
            </div>
            <el-input
              v-else
              v-model="row.quantity"
              style="width: 80px;"
              class="filter-item"
            />
          </template>
          <span v-else>{{ row | nutrientQuantityFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计量单位" align="center" width="150">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-autocomplete v-model="row.unit" :fetch-suggestions="queryUnits" placeholder="单位关键词" />
          </template>
          <span v-else>{{ row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="NRV%" align="center" width="80">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.nrvPercent"/>
          </template>
          <span v-else>{{ row.nrvPercent }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Nv_Spec" align="center" width="80">
        <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="计量单位" align="center" width="150">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-autocomplete 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" width="200">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-autocomplete
              v-model="row.source"
              :fetch-suggestions="querySources"
              placeholder="请输入信息来源"
            />
          </template>
          <span v-else>{{ row.source }}</span>
        </template>
      </el-table-column>
      <el-table-column label="信息来源备注" align="center" width="200">
        <template slot-scope="{row}">
          <template v-if="row.edit">
            <el-input type="text" :rows="2" v-model="row.sourceNote" />
          </template>
          <span v-else>{{ row.sourceNote }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="320" fixed="right">
        <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="fetchData"
            >
              取消
            </el-button>
          </template>
          <template v-else>
            <el-button size="mini" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="primary" @click="updateSort(row, 0)">上移</el-button>
            <el-button size="mini" type="primary" @click="updateSort(row, 1)">下移</el-button>
            <el-button size="mini" type="danger" @click="confirmRemoveNutrient(row)">
              删除
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getNutrientList, addFoodNutrient, updateFoodNutrient, removeFoodNutrient,
  updateFoodNutrientSort, confirmDeleteFoodNutrient } from '@/api/food'
import { getList, getNutrientUnits } from '@/api/nutrient'
import { getList as getUnits } from '@/api/unit'

export default {
  name: 'AddNutrient',
  created() {
    this.foodId = this.$route.params && this.$route.params.id
    this.fetchData()
    this.queryNutrients()
  },
  filters: {
    nutrientQuantityFilter(row) {
      if (row.stdError) {
        return `${row.quantity} ± ${row.stdError}`
      }else if (row.quantityMin && row.quantityMax) {
        return `${row.quantityMin} ~ ${row.quantityMax}`
      } else if (row.quantityMin) {
        return `≥${row.quantityMin}`
      } else if (row.quantityMax) {
        return `≤${row.quantityMax}`
      } else {
        return row.quantity
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.nutrientSelect.focus()
    })
  },
  data() {
    return {
      tableKey: 0,
      listLoading: false,
      units: [],
      foodId: '',
      list: [],
      nutrients: [],
      params: { source: '营养标签', radio: 0, nvSpec: 100, nvSpecUnit: '克' },
      loading: false,
      unitLoading: false,
      sources: [{ value: "营养标签" }, { value: "食品官方资料" }, { value: "计算值" }]
    }
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getNutrientList(this.foodId).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', 100)
          this.$set(this.params, 'nvSpecUnit', '克')
        }
      })
    },
    addNutrient() {
      this.params.foodId = this.foodId
      addFoodNutrient(this.foodId, this.params).then(res => {
        this.params = { source: '营养标签', radio: 0 }
        this.fetchData()
        this.$notify.success('添加营养素成功')
        this.$refs.nutrientSelect.focus()
      }).catch(res => {
        this.$message.error(res.data.message)
      })
    },
    confirmEdit(row) {
      updateFoodNutrient(this.foodId, row.nutrientId, row).then(res => {
        this.fetchData()
        this.$notify.success('提交成功')
      }).catch(res => {
        this.$message.error(res.data.message)
      })
    },
    confirmRemoveNutrient(row) {
      confirmDeleteFoodNutrient(row.foodId, row.nutrientId).then(res => {
        if (!res.data) {
          this.$confirm('由于单位转换的原因，删除此条营养素关联数据，将会导致该食物被删除，是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.removeNutrient(row)
          })
        } else {
          this.removeNutrient(row)
        }
      }).catch(res => {
        this.$message.error(res.data.message)
      })
    },
    removeNutrient(row) {
      removeFoodNutrient(row.foodId, row.nutrientId).then(res => {
        this.fetchData()
        this.$notify.success('删除营养素成功')
        this.$refs.nutrientSelect.focus()
      }).catch(res => {
        this.$message.error(res.data.message)
      })
    },
    queryNutrients(query) {
      getList({ query }).then(res => {
        this.nutrients = res.data.list
      }).catch(() => {
        this.nutrients = []
      })
    },
    queryNutrientUnits(query, cb) {
      let units = []
      getNutrientUnits(this.params.nutrientId).then(res => {
        res.data.forEach(item => units.push({ value: item }))
        cb(units)
      })
    },
    queryUnits(query, cb) {
      let units = []
      getUnits({ query }).then(res => {
        res.data.list.forEach(item => units.push({ value: item.name }))
        cb(units)
      })
    },
    updateSort(row, type) {
      updateFoodNutrientSort(this.foodId, row.nutrientId, { type }).then(res => {
        this.$notify.success('提交成功')
        this.fetchData()
      }).catch(res => {
        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);
      };
    },
    handleEdit(row) {
      this.$set(row, 'edit', true)
      if (row.quantityMax || row.quantityMin) {
        this.$set(row, 'radio', 1)
      } else if (row.stdError) {
        this.$set(row, 'radio', 2)
      } else {
        this.$set(row, 'radio', 0)
      }
    },
    radioChange(row) {
      this.$set(row, 'stdError', '')
      this.$set(row, 'quantityMin', '')
      this.$set(row, 'quantityMax', '')
      this.$set(row, 'quantity', '')
    },
    nutrientChanged(value) {
      for (let nutrient of this.nutrients) {
        if (nutrient.id === value) {
          this.$set(this.params, 'unit', nutrient.baseUnit)
          break
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
