<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="right" label-width="90px" class="form-container">
      <div class="createPost-main-container">
        <el-form-item label="自定义ID：" style="margin-bottom: 40px;width: 60%" prop="id">
          <el-input v-model="postForm.id2" placeholder="请输入ID" />
        </el-form-item>
        <el-form-item label="名称：" prop="name" style="margin-bottom: 40px;width: 60%" required>
          <el-input v-model="postForm.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述：" prop="description" style="margin-bottom: 30px;width: 40%">
          <el-input v-model="postForm.description" type="textarea" :rows="4" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="食物类型：" prop="foodType" style="margin-bottom: 30px;width: 40%">
          <el-radio :label="0" v-model="postForm.foodType">主材</el-radio>
          <el-radio :label="1" v-model="postForm.foodType">辅材</el-radio>
        </el-form-item>
        <el-form-item label="ep：" prop="ep" style="margin-bottom: 40px;width: 60%">
          <el-input v-model="postForm.ep" placeholder="请输入ep" style="width: 40%" />
        </el-form-item>
        <el-form-item label="NV_spec：" prop="nvSpec" style="margin-bottom: 40px;width: 60%">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-input v-model="postForm.nvSpec" placeholder="请输入nvSpec" />
            </el-col>
            <el-col :span="6">
              <el-autocomplete
                v-model="postForm.nvSpecUnitName"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
              ></el-autocomplete>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="最小刻度：" prop="minScale" style="margin-bottom: 40px;width: 60%">
          <el-input v-model="postForm.minScale" placeholder="请输入最小刻度" />
        </el-form-item>
        <el-form-item label="最大刻度：" prop="maxScale" style="margin-bottom: 40px;width: 60%">
          <el-input v-model="postForm.maxScale" placeholder="请输入最大刻度" />
        </el-form-item>
        <el-form-item label="卡尺每格刻度：" prop="stepScale" style="margin-bottom: 40px;width: 60%">
          <el-input v-model="postForm.stepScale" placeholder="请输入卡尺每格刻度" />
        </el-form-item>
        <el-form-item label="图片列表：" prop="images" style="margin-bottom: 30px;width: 60%">
          <dropzone
            :id="mainImgDropzone"
            :default-img="postForm.images"
            @dropzone-removedFile="removeFile"
            @dropzone-success="addFile"
          />
        </el-form-item>
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          保存
        </el-button>
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" v-if="!isEdit" @click="handleDialog">
          保存并从模板导入营养素
        </el-button>
      </div>
    </el-form>

    <el-dialog title="从模板导入营养素" :visible.sync="dialogFormVisible">
      <el-form ref="dialogForm" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="模板：" prop="templateId">
          <el-select
            v-model="templateId"
            class="filter-item"
            filterable
            remote
            reserve-keyword
            placeholder="请输入模板关键词"
            :loading="templateLoading"
            :remote-method="queryTemplates"
          >
            <el-option v-for="item in templates" :key="`template${item.id}`" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitFromTemplate">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { create, getDetail, update } from '@/api/food'
import Dropzone from '@/components/Dropzone'
import { getList as getUnits } from '@/api/unit'
import { getNutrientTemplates } from '@/api/nutrientTemplate'

export default {
  name: "FoodDetail",
  components: { Dropzone },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      mainImgDropzone: 'mainImgDropzone',
      nutrientImgDropzone: 'nutrientImgDropzone',
      postForm: { id2: '', name: '', img: '', description: ''},
      loading: false,
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      },
      foodId: '',
      unitLoading: false,
      dialogFormVisible: false,
      templateLoading:false,
      templates: [],
      templateId: ''
    }
  },
  created() {
    if (this.isEdit) {
      this.foodId = this.$route.params && this.$route.params.id
      this.fetchData(this.foodId)
    }
  },
  methods: {
    fetchData(id) {
      getDetail(id).then(res => {
        this.postForm = res.data
      })
    },
    submitForm() {
      this.loading = true
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.updateData()
          } else {
            this.createData()
          }
        } else {
          this.$notify({ title: '失败', message: '必填字段为空', type: 'error', duration: 2000 })
          this.loading = false
        }
      })
    },
    createData() {
      create(this.postForm).then(res => {
        this.$message.success('创建成功')
        this.loading = false
        this.$router.push({ path: '/food' })
      }).catch(error => {
        this.$message.error(res.data.message)
        this.loading = false
      })
    },
    updateData() {
      update(this.foodId, this.postForm).then(res => {
        this.$message.success('更新成功')
        this.loading = false
        this.$router.push({ path: '/food' })
      }).catch(error => {
        this.$message.error(res.data.message)
        this.loading = false
      })
    },
    removeFile(file) {
      let imgs = this.postForm.images
      let imgIndex = -1
      for (let i = 0; i < imgs.length; i++) {
        if (imgs[i] === file.fileUrl) {
          imgIndex = i
          break
        }
      }
      imgs.splice(imgIndex, 1)
    },
    addFile(file) {
      if (file.dropzoneId === this.mainImgDropzone) {
        if (this.postForm.images) {
          this.postForm.images.push(file.fileUrl)
        } else {
          this.postForm.images = [file.fileUrl]
        }
      }
    },
    queryTemplates(query) {
      getNutrientTemplates({ query }).then(res => {
        this.templates = res.data.list
      }).catch(() => {
        this.templates = []
      })
    },
    handleDialog() {
      this.templateId = ''
      this.dialogFormVisible = true
    },
    submitFromTemplate() {
      this.postForm.templateId = this.templateId
      this.submitForm()
    },
    querySearchAsync(query, cb) {
      getUnits({ query }).then(res => {
        cb(res.data.list.map(item => { return { value: item.name } }))
      }).catch(() => {
        cb([])
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .createPost-container {
    position: relative;

    .createPost-main-container {

      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }
</style>
