<template>
  <div class="app-container" v-loading="uploadLoading">
    <div class="filter-container">
      <el-row style="margin-bottom: 5px">
        <el-input
          v-model="listQuery.query"
          placeholder="请输入检索词"
          style="width: 40%;"
          class="filter-item"
          @keyup.enter.native="fetchData()"
        />
        <el-select v-model="usdaType" v-if="isUsda" clearable style="width: 160px;margin-left: 10px;" class="filter-item">
          <el-option v-for="item in usdaTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="fetchData">
          检索
        </el-button>
        <el-select v-model="listQuery.orderBy" style="width: 160px;margin-left: 10px;" class="filter-item" @change="fetchData">
          <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
      </el-row>
      <el-row>
        <el-button
          class="filter-item"
          style="margin: 0 10px 20px 0; float: right;"
          type="success"
          icon="el-icon-circle-plus-outline"
          @click="handleCreate"
        >
          新建
        </el-button>
        <el-button
          class="filter-item"
          style="margin: 0 10px 20px 0; float: right;"
          type="primary"
          @click="handleImport"
        >
          食物导入
        </el-button>
      </el-row>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @row-click="handleFoodClick"
    >
      <el-table-column type="index" label="序号" align="center" fixed width="60px" />
      <el-table-column label="名称" align="center" fixed width="200px">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" width="180">
        <template slot-scope="{row}">
          <el-image
            v-if="row.mainImage"
            style="width: 150px; height: 100px"
            :src="row.mainImage"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column label="自定义ID" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.id2 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" width="200">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="食物类型" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.foodType | foodTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="ep(%)" align="center" width="70px">
        <template slot-scope="{row}">
          <span>{{ row.ep }}</span>
        </template>
      </el-table-column>
      <el-table-column label="GI" align="center" width="70px">
        <template slot-scope="{row}">
          <span>{{ row.gi }}</span>
        </template>
      </el-table-column>
      <el-table-column label="GL" align="center" width="70px">
        <template slot-scope="{row}">
          <span>{{ row.gl ? row.gl : row.glCalcd }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据来源" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.dataSource }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding" fixed="right" width="90">
        <template slot-scope="{row,$index}">
          <el-dropdown @command="handleCommand">
            <el-button size="small" @click.stop="{}" type="primary">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{row: row, command: 'update'}">更新/查看</el-dropdown-item>
              <el-dropdown-item :command="{row: row, command: 'copy'}">复制</el-dropdown-item>
              <el-dropdown-item :command="{row: row, command: 'manageNutrients'}">营养素关联</el-dropdown-item>
              <el-dropdown-item :command="{row: row, command: 'manageUnits'}">单位管理</el-dropdown-item>
              <el-dropdown-item :command="{row: row, command: 'manageModifiers'}">规格管理</el-dropdown-item>
              <el-dropdown-item :disabled="!canDelete(row)" :command="{row: row, command: 'delete'}">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="fetchData"
    />

    <el-dialog title="食物导入" width="40%" :visible.sync="dialogFormVisible">
      <el-upload
        ref="upload"
        action=""
        :auto-upload="false"
        :multiple="false"
        drag
        :limit="1"
        :show-file-list="true"
        :on-change="fileChanged"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" >
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="importFoods">
          开始导入
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="复制食物" width="40%" :visible.sync="copyDialogVisible">
      <el-form ref="dialogForm" label-position="left" label-width="90px" style="width: 80%; margin-left:50px;">
        <el-form-item label="新食物名称: " prop="foodName">
          <el-input v-model="params.foodName" placeholder="请输入新食物名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" >
        <el-button @click="copyDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="copyFood">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="食物二维码" width="250" :visible.sync="foodQRDialogVisible">
      <vue-qr
        :text="foodQRParams.url"
        :bgSrc="foodQRParams.bgImg"
        :logoSrc="foodQRParams.logoImg"
        :size="200"
        :correctLevel="3"
        colorDark="#000"
        colorLight="#fff"
        :dotScale="1"
      ></vue-qr>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { getList, remove, copyFromSimilarFood } from '@/api/food'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { getFoodSourceByUrl, isUsda } from '@/utils/food-utils'
import store from '@/store'
import VueQr from 'vue-qr'

const foodTypes = { 0: '主材', 1: '辅材' }

export default {
  name: 'FoodList',
  components: { Pagination, VueQr },
  filters: {
    foodTypeFilter(value) {
      return foodTypes[value]
    }
  },
  data() {
    return {
      tableKey: 0,
      total: 0,
      dialogStatus: '',
      dialogFormVisible: false,
      sortOptions: [{ key: 0, label: '按创建时间倒序排列' }, { key: 1, label: '按ID顺序排列' }],
      list: [],
      listLoading: true,
      listQuery: {
        query: '',
        orderBy: 0,
        pageNum: 1,
        pageSize: 20
      },
      uploadFile: null,
      uploadLoading: false,
      copyDialogVisible: false,
      params: {},
      foodSource: '',
      foodQRDialogVisible: false,
      foodQRParams: {},
      isUsda: false,
      usdaTypes: [{ 'label': '全部', 'value': 'ALL' }, { 'label': 'Foundation', 'value': 'USDA_FOUNDATION' },
                  { 'label': 'Legacy', 'value': 'USDA_SR_LEGACY' }, { 'label': 'Branded', 'value': 'USDA_BRANDED' },
                  { 'label': 'FNDDS', 'value': 'USDA_FNDDS' }],
      usdaType: ''
    }
  },
  created() {
    this.foodSource = getFoodSourceByUrl(this.$route.path)
    if (this.foodSource === 'ENTRY' || this.foodSource === '') {
      this.listQuery.orderBy = 0
    } else {
      this.listQuery.orderBy = 1
    }
    this.isUsda = isUsda(this.foodSource)
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      this.listQuery.foodSource = this.foodSource
      if (this.foodSource === 'USDA') {
        if (!this.usdaType || this.usdaType === 'ALL'){
          this.listQuery.foodSource = 'USDA'
        } else {
          this.listQuery.foodSource = this.usdaType
        }
      }
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.count
        this.listLoading = false
      })
    },
    handleCreate() {
      this.$router.push({ path: '/food/create' })
    },
    handleUpdate(row) {
      this.$router.push({ path: '/food/edit/' + row.id })
    },
    manageNutrients(row) {
      this.$router.push({ path: `/food/${row.id}/nutrient` })
    },
    manageUnits(row) {
      this.$router.push({ path: `/food/${row.id}/unit` })
    },
    manageModifiers(row) {
      this.$router.push({ path: `/food/${row.id}/modifier` })
    },
    handleDelete(row, index) {
      remove(row.id).then(res => {
        this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
        this.list.splice(index, 1)
        this.fetchData()
      }).catch(res => {
        this.$message.error(res.data.message)
      })
    },
    handleImport() {
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
      this.uploadFile = null
      this.dialogFormVisible = true
    },
    importFoods() {
      const reqConfig = { headers: { 'Authorization': getToken(), 'Content-Type':'multipart/form-data' },
        timeout: 1000 * 60 * 3 }
      const importUrl = process.env.VUE_APP_BASE_API + '/api/foods/import'
      this.uploadLoading = true
      this.dialogFormVisible = false
      axios.post(importUrl, this.uploadFile, reqConfig).then(res => {
        this.$notify.success('导入成功')
        this.uploadLoading = false
      }).catch(res => {
        this.$message.error(res.response.data.message)
        this.uploadLoading = false
      })
    },
    fileChanged(file, fileList) {
      let fromData = new FormData()
      fromData.append('file', file.raw)
      this.uploadFile = fromData
    },
    handleCopy(data) {
      this.params = { foodId: data.id }
      this.copyDialogVisible = true
    },
    copyFood() {
      copyFromSimilarFood(this.params).then(res => {
        this.$notify.success('提交成功')
        this.$router.push({ path: `/food/edit/${res.data}`})
      }).catch(res => {
        this.$message.error(res.data.message)
      })
    },
    handleCommand(data) {
      switch (data.command) {
        case 'update':
          this.handleUpdate(data.row)
          break
        case 'copy':
          this.handleCopy(data.row)
          break
        case 'manageNutrients':
          this.manageNutrients(data.row)
          break
        case 'manageUnits':
          this.manageUnits(data.row)
          break
        case 'manageModifiers':
          this.manageModifiers(data.row)
          break
        case 'delete':
          this.handleDelete(data.row)
          break
      }
    },
    canDelete(data) {
      return store.getters.isAdmin || data && data.userId === store.getters.userId
    },
    handleFoodClick(row) {
      this.foodQRParams = { url: process.env.VUE_APP_H5_URL + `/food/index.html?id=${row.id}`,
        bgImg: row.mainImage ? row.mainImage : '',
        logoImg: row.mainImage ? row.mainImage : ''
      }
      this.foodQRDialogVisible = true
    }
  }
}
</script>

<style scoped>

</style>
