<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.query"
        placeholder="请输入检索词"
        style="width: 60%;"
        class="filter-item"
        @keyup.enter.native="fetchData()"
      />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="fetchData">
        检索
      </el-button>
      <el-button
        class="filter-item"
        style="margin: 0 10px 20px 0; float: right;"
        type="success"
        icon="el-icon-circle-plus-outline"
        @click="handleCreateOrUpdate('create')"
      >
        新建
      </el-button>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
    >
      <el-table-column type="index" label="序号" align="center" width="60" />
      <el-table-column label="图片" align="center" width="180">
        <template slot-scope="{row}">
          <el-image v-if="row.coverPic" style="width: 150px; height: 180px" :src="row.coverPic" fit="contain" />
        </template>
      </el-table-column>
      <el-table-column label="自定义ID" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.id2 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="英文名称" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.enName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编码" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上级营养素名称" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.parentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="推荐用量类型" align="center" width="70">
        <template slot-scope="{row}">
          <span>{{ row.recommendType | recommendTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="每日推荐量值" align="center" width="70">
        <template slot-scope="{row}">
          <span>{{ row.recommend ? `${row.recommend} ${row.recommendUnit}` : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="每日推荐量范围起始值" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.recommendBegin ? `${row.recommendBegin} ${row.recommendUnit}` : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="每日推荐量范围截止值" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.recommendEnd ? `${row.recommendEnd} ${row.recommendUnit}` : '' }}</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" width="480">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleCreateOrUpdate('update', row)">
            更新
          </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 type="primary" size="mini" @click="updateSort(row, 2)">
            置顶
          </el-button>
          <el-button type="primary" size="mini" @click="updateSort(row, 3)">
            置底
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </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="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="params" label-position="left" label-width="200px" style="width: 400px; margin-left:50px;">
        <el-form-item label="自定义ID" prop="id2">
          <el-input v-model="params.id2" placeholder="请输入自定义ID" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="params.name" placeholder="请输入名称" :disabled="dialogStatus === 'edit'" />
        </el-form-item>
        <el-form-item label="英文名称" prop="enName">
          <el-input v-model="params.enName" placeholder="请输入英文名称" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="params.code" placeholder="编码" :disabled="dialogStatus === 'edit'" />
        </el-form-item>
        <el-form-item label="推荐用量类型" prop="recommendType">
          <el-radio v-model="params.recommendType" :label="0">值</el-radio>
          <el-radio v-model="params.recommendType" :label="1">范围</el-radio>
          <el-radio v-model="params.recommendType" :label="2">无</el-radio>
        </el-form-item>
        <el-form-item v-if="params.recommendType!==2" label="推荐量单位" prop="recommendUnit">
          <el-select
            v-model="params.recommendUnit"
            filterable
            remote
            reserve-keyword
            placeholder="请选择推荐量单位"
            :remote-method="queryUnits"
            :loading="loading"
          >
            <el-option v-for="item in units" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="params.recommendType===0" prop="recommend" label="每日推荐摄入量">
          <el-input v-model="params.recommend" placeholder="每日推荐摄入量" />
        </el-form-item>
        <el-form-item v-if="params.recommendType===1" prop="recommendBegin" label="每日推荐摄入量范围-开始值">
          <el-input v-model="params.recommendBegin" placeholder="每日推荐摄入量范围-开始值" />
        </el-form-item>
        <el-form-item v-if="params.recommendType===1" prop="recommendEnd" label="每日推荐摄入量范围-截止值">
          <el-input v-model="params.recommendEnd" placeholder="每日推荐摄入量范围-截止值" />
        </el-form-item>
        <el-form-item label="上级营养素" prop="parentId">
          <el-select
            v-model="params.parentId"
            filterable
            remote
            reserve-keyword
            placeholder="请选择上级营养素"
            :remote-method="queryNutrients"
            :loading="loading"
          >
            <el-option v-for="item in parentNutrients" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="营养素图片" prop="coverPic">
          <single-image :value="params.coverPic" :show-preview="true" style="width: 100%" @success="updateFile" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createOrUpdateData">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import SingleImage from '@/components/Upload/SingleImage'
import { getList, update, remove, create, updateSortOrder } from '@/api/nutrient'
import { getList as getUnits } from '@/api/unit'

const recommendTypes = { 0: '值', 1: '范围', 2: '无' }

export default {
  name: 'NutrientList',
  components: { Pagination, SingleImage },
  filters: {
    recommendTypeFilter(value) {
      return recommendTypes[value]
    }
  },
  data() {
    return {
      tableKey: 0,
      total: 0,
      dialogStatus: '',
      dialogFormVisible: false,
      list: [{}],
      listLoading: true,
      listQuery: {
        query: '',
        pageNum: 1,
        pageSize: 20
      },
      textMap: {
        update: '更新',
        create: '新建'
      },
      rules: {
        name: [{ required: true, message: '名称不允许为空', trigger: 'blur' }]
      },
      params: { recommendType: 2 },
      units: [],
      loading: false,
      parentNutrients: []
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.count
        this.listLoading = false
      }).catch(() => {
        this.$message.error('获取数据失败')
        this.listLoading = false
      })
    },
    handleCreateOrUpdate(dialogStatus, row) {
      this.queryUnits()
      this.queryNutrients()
      this.params = dialogStatus === 'create' ? { recommendType: 2 } : Object.assign({}, row) // copy obj
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      remove(row.id).then(res => {
        this.$notify.success('提交成功')
        this.fetchData()
      }).catch(res => {
        this.$message.error(res.data.message)
      })
    },
    createOrUpdateData() {
      const resultPromise = this.dialogStatus === 'create' ? create(this.params) : update(this.params.id, this.params)
      resultPromise.then(res => {
        this.$notify.success('提交成功')
        this.fetchData()
        this.dialogFormVisible = false
      }).catch(res => {
        this.$message.error(res.data.message)
        this.fetchData()
      })
    },
    queryUnits(query) {
      this.loading = true
      getUnits({ query }).then(res => {
        this.units = res.data.list
        this.loading = false
      }).catch(res => {
        this.units = []
        this.loading = false
      })
    },
    queryNutrients(query) {
      this.loading = true
      getList({ query }).then(res => {
        this.parentNutrients = res.data.list
        this.loading = false
      }).catch(res => {
        this.parentNutrients = []
        this.loading = false
      })
    },
    updateFile(value) {
      this.$set(this.params, 'coverPic', value)
    },
    updateSort(row, type) {
      updateSortOrder(row.id, { type }).then(res => {
        this.$notify.success('提交成功')
        this.fetchData()
      }).catch(res => {
        this.$message.error(res.data.message)
        this.fetchData()
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
