<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="食品标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入食品标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="分类" prop="cid">
        <el-select v-model="queryParams.cid">
          <el-option v-for="c in categoryList" :key="c.id" :value="c.id" :label="c.title"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优惠" prop="coupon">
        <el-input v-model="queryParams.coupon" placeholder="请输入优惠" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="queryParams.price" placeholder="请输入价格" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="售卖区域" prop="area">
        <el-input v-model="queryParams.area" placeholder="请选择售卖区域" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.data_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['admin:food:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['admin:food:edit']">修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="foodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="食品编号" align="center" prop="id" />
      <el-table-column label="分类编号" align="center" prop="cid">
        <template slot-scope="scope">
          {{ getCategoryName(scope.row.cid) }}
        </template>
      </el-table-column>
      <el-table-column label="食品标题" align="center" prop="title" />
      <el-table-column label="商品主图" align="center" prop="cover" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.cover" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="优惠" align="center" prop="coupon" />
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="排序" align="center" prop="sort" />
<!--      (匹配收货地址,null表示不限制)-->
      <el-table-column label="售卖区域" align="center" prop="area" />
      <el-table-column label="是否推荐" align="center" prop="recommend" />
      <el-table-column label="已售出数量" align="center" prop="saleCount" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.data_state" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:food:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['admin:food:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改食品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-row :gutter="20">
          <el-col :span="18">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="食品标题" prop="title">
                  <el-input v-model="form.title" placeholder="请输入食品标题" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="价格" prop="price">
                  <el-input-number style="width: 100%;" :min="0" controls-position="right" v-model="form.price"
                    placeholder="请输入价格" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="分类" prop="cid">
                  <el-select v-model="form.cid">
                    <el-option v-for="c in categoryList" :key="c.id" :value="c.id" :label="c.title"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="食品简介" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品主图" prop="cover">
              <image-upload :limit="1" v-model="form.cover" :isShowTip="false" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-form-item label="食品详情">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="优惠" prop="coupon">
              <el-input v-model="form.coupon" placeholder="请输入优惠" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠开始时间" prop="couponStartTime">
              <el-date-picker clearable v-model="form.couponStartTime" type="datetime" placeholder="请选择优惠开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠结束时间" prop="couponEndTime">
              <el-date-picker clearable v-model="form.couponEndTime" type="datetime" placeholder="请选择优惠结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已售出数量" prop="saleCount">
              <el-input v-model="form.saleCount" placeholder="请输入已售出数量" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="售卖区域" prop="area">
              <el-select v-model="form.area" multiple placeholder="请输入售卖区域(匹配收货地址,null表示不限制)">
                <el-option
                  v-for="item in areaData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
<!--              <el-cascader-->
<!--                placeholder="请输入售卖区域(匹配收货地址,null表示不限制)"-->
<!--                :options="areaData"-->
<!--                :show-all-levels="false"-->
<!--                v-model="form.area"-->
<!--                :props="{-->
<!--                  multiple:true,-->
<!--                  label:'name',-->
<!--                  value:'code'-->
<!--                }"-->
<!--                collapse-tags-->
<!--                clearable></el-cascader>-->
<!--              <el-input v-model="form.area" placeholder="请输入售卖区域(匹配收货地址,null表示不限制)" />-->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否推荐" prop="recommend">
              <el-select v-model="form.recommend" placeholder="请选择是否推荐">
                <el-option value="1">推荐</el-option>
                <el-option value="0">不推荐</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="推荐开始时间" prop="recommendStartTime">
              <el-date-picker clearable v-model="form.recommendStartTime" type="datetime" placeholder="请选择推荐开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="推荐结束时间" prop="recommendEndTime">
              <el-date-picker clearable v-model="form.recommendEndTime" type="datetime" placeholder="请选择推荐结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFood, getFood, delFood, addFood, updateFood } from "@/api/admin/food";
import { listCategory } from '@/api/admin/category'
import { AreaData } from '@/utils/pca-code'

export default {
  name: "Food",
  dicts: ['data_state'],
  data() {
    return {
      areaData:AreaData,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 食品表格数据
      foodList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cid: null,
        title: null,
        coupon: null,
        price: null,
        area: null,
        recommend: null,
        createTime: null,
        state: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
        recommend: [
          { required: true, message: "是否推荐不能为空", trigger: "change" }
        ],
        saleCount: [
          { required: true, message: "已售出数量不能为空", trigger: "blur" }
        ],
      },
      categoryList: []
    };
  },
  created() {
    this.getList();
    listCategory({}).then(resp => {
      this.categoryList = resp.rows
    })
  },
  methods: {
    getCategoryName(cid){
      if(!cid || !this.categoryList) return '';
      const c = this.categoryList.find(c=>c.id == cid)
      return c ? c.title : '';
    },
    /** 查询食品列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listFood(this.queryParams).then(response => {
        this.foodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cid: null,
        title: null,
        cover: null,
        description: null,
        content: null,
        coupon: null,
        couponStartTime: null,
        couponEndTime: null,
        price: null,
        sort: null,
        area: null,
        recommend: null,
        recommendStartTime: null,
        recommendEndTime: null,
        saleCount: null,
        createTime: null,
        updateTime: null,
        state: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加食品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFood(id).then(response => {
        if(response.data.area){
          response.data.area = response.data.area.split(',')
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改食品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if(this.form.area){
          this.form.area = this.form.area.join(',')
        }
        if (valid) {
          if (this.form.id != null) {
            updateFood(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFood(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除食品编号为"' + ids + '"的数据项？').then(function () {
        return delFood(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('admin/food/export', {
        ...this.queryParams
      }, `food_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
