<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="食材分类" prop="foodCategoryId">                      
              <el-tree-select clearable
              v-model="queryParams.foodCategoryId"
              :data="foodCategoryList"
              :render-after-expand="false" 
              :props="{ value: 'foodCategoryId', label: 'name', children: 'children' } as any"
              check-strictly=true
            />
            </el-form-item>
            <el-form-item label="食材名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入食材名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>             
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary"  icon="Plus" @click="handleAdd" v-hasPermi="['system:foodIngredient:add']">新增食材</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:foodIngredient:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:foodIngredient:remove']">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Upload" @click="handleImport" v-hasPermi="['system:foodIngredient:export']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Download" @click="downLoadTemplate" v-hasPermi="['system:foodIngredient:export']">下载导入模板</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="foodIngredientList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="食材大类" align="center" prop="bigCategory" />
        <el-table-column label="食材亚类" align="center" prop="subCategory" />
        <el-table-column label="食材名称" align="center" prop="name" />         
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(false ,scope.row)" v-hasPermi="['system:foodIngredient:edit']">编辑</el-button>
            </el-tooltip>
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleUpdate(true,scope.row)" v-hasPermi="['system:foodIngredient:edit']">详情</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:foodIngredient:remove']">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改食材管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="foodIngredientFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="食材分类ID" prop="foodCategoryId">
          <el-input v-model="form.foodCategoryId" placeholder="请输入食材分类ID" />
        </el-form-item>
        <el-form-item label="食材名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入食材名称" />
        </el-form-item>
        <el-form-item label="食材编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入食材编码" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="入货价格" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" placeholder="请输入入货价格" />
        </el-form-item>
        <el-form-item label="食材可食比例构成" prop="edibleRatio">
          <el-input v-model="form.edibleRatio" placeholder="请输入食材可食比例构成" />
        </el-form-item>
        <el-form-item label="保质期" prop="shelfLife">
          <el-input v-model="form.shelfLife" placeholder="请输入保质期" />
        </el-form-item>
        <el-form-item label="库存预警值" prop="stockWarning">
          <el-input v-model="form.stockWarning" placeholder="请输入库存预警值" />
        </el-form-item>
        <el-form-item label="保质期预警" prop="expiryWarning">
          <el-input v-model="form.expiryWarning" placeholder="请输入保质期预警" />
        </el-form-item>
        <el-form-item label="食材描述" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="热量" prop="calories">
          <el-input v-model="form.calories" placeholder="请输入热量" />
        </el-form-item>
        <el-form-item label="蛋白质" prop="protein">
          <el-input v-model="form.protein" placeholder="请输入蛋白质" />
        </el-form-item>
        <el-form-item label="脂肪" prop="fat">
          <el-input v-model="form.fat" placeholder="请输入脂肪" />
        </el-form-item>
        <el-form-item label="碳水化合物" prop="carbohydrate">
          <el-input v-model="form.carbohydrate" placeholder="请输入碳水化合物" />
        </el-form-item>
        <el-form-item label="水分" prop="water">
          <el-input v-model="form.water" placeholder="请输入水分" />
        </el-form-item>
        <el-form-item label="维生素A" prop="vitaminA">
          <el-input v-model="form.vitaminA" placeholder="请输入维生素A" />
        </el-form-item>
        <el-form-item label="维生素B2" prop="vitaminB2">
          <el-input v-model="form.vitaminB2" placeholder="请输入维生素B2" />
        </el-form-item>
        <el-form-item label="维生素C" prop="vitaminC">
          <el-input v-model="form.vitaminC" placeholder="请输入维生素C" />
        </el-form-item>
        <el-form-item label="钠" prop="sodium">
          <el-input v-model="form.sodium" placeholder="请输入钠" />
        </el-form-item>
        <el-form-item label="铁" prop="iron">
          <el-input v-model="form.iron" placeholder="请输入铁" />
        </el-form-item>
        <el-form-item label="磷" prop="phosphorus">
          <el-input v-model="form.phosphorus" placeholder="请输入磷" />
        </el-form-item>
        <el-form-item label="膳食纤维" prop="dietaryFiber">
          <el-input v-model="form.dietaryFiber" placeholder="请输入膳食纤维" />
        </el-form-item>
        <el-form-item label="维生素B1" prop="vitaminB1">
          <el-input v-model="form.vitaminB1" placeholder="请输入维生素B1" />
        </el-form-item>
        <el-form-item label="烟酸" prop="niacin">
          <el-input v-model="form.niacin" placeholder="请输入烟酸" />
        </el-form-item>
        <el-form-item label="维生素E" prop="vitaminE">
          <el-input v-model="form.vitaminE" placeholder="请输入维生素E" />
        </el-form-item>
        <el-form-item label="钙" prop="calcium">
          <el-input v-model="form.calcium" placeholder="请输入钙" />
        </el-form-item>
        <el-form-item label="钾" prop="potassium">
          <el-input v-model="form.potassium" placeholder="请输入钾" />
        </el-form-item>
        <el-form-item label="胆固醇" prop="cholesterol">
          <el-input v-model="form.cholesterol" placeholder="请输入胆固醇" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

        <!-- 上传excel -->
    <el-dialog :title="dialogFile.title" v-model="dialogFile.visible" width="700px" append-to-body>
      <el-upload  drag :action="uploadFileUrl" :headers="headers" :file-list="fileList"
        accept=".xlsx,.xls"        
        :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"      
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或 <em>点击上传</em>
          </div>          
        </el-upload>
        <div class="el-upload__tip">
            请上传 .xls , .xlsx 标准格式文件
            </div>
    </el-dialog>
  </div>
</template>

<script setup name="FoodIngredient" lang="ts">
import { listFoodIngredient, getFoodIngredient, delFoodIngredient, addFoodIngredient, updateFoodIngredient } from '@/api/system/foodIngredient';
import { FoodIngredientVO, FoodIngredientQuery, FoodIngredientForm } from '@/api/system/foodIngredient/types';
import { listTree } from '@/api/system/foodCategory';
import { FoodCategoryVO } from '@/api/system/foodCategory/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

import { UploadFilled } from '@element-plus/icons-vue'
import { globalHeaders } from '@/utils/request';

const router = useRouter();
const foodIngredientList = ref<FoodIngredientVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const foodCategoryList = ref<FoodCategoryVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const foodIngredientFormRef = ref<ElFormInstance>();

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + '/system/foodIngredient/importExcel'); 
const headers = ref(globalHeaders());
const fileList = ref<any[]>([]);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogFile = reactive<DialogOption>({
  visible: false,
  title: '请上传'
});

const initFormData: FoodIngredientForm = {
  foodIngredientId: undefined,
  foodCategoryId: undefined,
  name: undefined,
  code: undefined,
  unit: undefined,
  purchasePrice: undefined,
  edibleRatio: undefined,
  shelfLife: undefined,
  stockWarning: undefined,
  expiryWarning: undefined,
  description: undefined,
  calories: undefined,
  protein: undefined,
  fat: undefined,
  carbohydrate: undefined,
  water: undefined,
  vitaminA: undefined,
  vitaminB2: undefined,
  vitaminC: undefined,
  sodium: undefined,
  iron: undefined,
  phosphorus: undefined,
  dietaryFiber: undefined,
  vitaminB1: undefined,
  niacin: undefined,
  vitaminE: undefined,
  calcium: undefined,
  potassium: undefined,
  cholesterol: undefined,
  status: undefined,
}
const data = reactive<PageData<FoodIngredientForm, FoodIngredientQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    foodCategoryId: undefined,
    name: undefined,
    code: undefined,
    unit: undefined,
    purchasePrice: undefined,
    edibleRatio: undefined,
    shelfLife: undefined,
    stockWarning: undefined,
    expiryWarning: undefined,
    description: undefined,
    calories: undefined,
    protein: undefined,
    fat: undefined,
    carbohydrate: undefined,
    water: undefined,
    vitaminA: undefined,
    vitaminB2: undefined,
    vitaminC: undefined,
    sodium: undefined,
    iron: undefined,
    phosphorus: undefined,
    dietaryFiber: undefined,
    vitaminB1: undefined,
    niacin: undefined,
    vitaminE: undefined,
    calcium: undefined,
    potassium: undefined,
    cholesterol: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    foodIngredientId: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    foodCategoryId: [
      { required: true, message: "食材分类ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "食材名称不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "食材编码不能为空", trigger: "blur" }
    ],
    unit: [
      { required: true, message: "单位不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询食材管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listFoodIngredient(queryParams.value);
  foodIngredientList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  foodIngredientFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: FoodIngredientVO[]) => {
  ids.value = selection.map(item => item.foodIngredientId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  router.push('/food/food-ingredient-page/0');
}

/** 修改按钮操作 */
const handleUpdate = async (disabled:boolean,row?: FoodIngredientVO) => {
  // reset();
  const _foodIngredientId = row?.foodIngredientId || ids.value[0] 
  if(disabled){
    router.push('/food/food-ingredient-view/'+_foodIngredientId);
  }else{
    router.push('/food/food-ingredient-page/'+_foodIngredientId);
  }  
}

/** 提交按钮 */
const submitForm = () => {
  foodIngredientFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.foodIngredientId) {
        await updateFoodIngredient(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addFoodIngredient(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: FoodIngredientVO) => {
  const _foodIngredientIds = row?.foodIngredientId || ids.value;
  await proxy?.$modal.confirm('是否确认删除食材管理编号为"' + _foodIngredientIds + '"的数据项？').finally(() => loading.value = false);
  await delFoodIngredient(_foodIngredientIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/foodIngredient/export', {
    ...queryParams.value
  }, `foodIngredient_${new Date().getTime()}.xlsx`)
}

/** 导出按钮操作 */
const handleImport = () => {
  dialogFile.visible = true;
  fileList.value = [];
}

/** 导出按钮操作 */
const downLoadTemplate = () => {
  proxy?.getDownload('system/foodIngredient/downLoadTemplate', {
  }, `食材模版.xlsx`)
}


// 上传失败
const handleUploadError = () => {
  proxy?.$modal.msgError('上传Excel失败');
  proxy?.$modal.closeLoading();
};

// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
  if (res.code === 200) {
    dialogFile.visible = false;
    fileList.value = [];
    proxy?.$modal.closeLoading();
    getList();
  } else {
    proxy?.$modal.msgError(res.msg);
    proxy?.$modal.closeLoading();   
  }
  fileList.value = [];
};


/** 上传前loading加载 */
const handleBeforeUpload = (file: any) => {
   const isLt = file.size / 1024 / 1024 < 10;
    if (!isLt) {
      proxy?.$modal.msgError(`上传文件大小不能超过10MB!`);
      return false;
    }       
  proxy?.$modal.loading('正在上传文件，请稍候...');
  return true;
};

/** 查询食材分类列表 */
const getList2 = async () => {   
  const res = await listTree();  
  foodCategoryList.value = res.rows;   
}

onMounted(() => {
  getList();
  getList2();
});
</script>
