<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="name">
              <el-select v-model="queryParams.baseDiet" placeholder="请选择" clearable>
                <el-option v-for="dict in dietary_types" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="食谱分类" prop="categoryId">
              <el-select v-model="queryParams.categoryId" placeholder="请选择" clearable>
                <el-option v-for="dict in recipeCategoryList" :key="dict.recipeCategoryId" :label="dict.name" :value="dict.recipeCategoryId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="智能推荐" prop="smartRecommend">
              <el-select v-model="queryParams.smartRecommend" placeholder="请选择" clearable>
                <el-option v-for="dict in intelligent_recommendation" :key="dict.value" :label="dict.label=='启用'?dict.label:'未启用'" :value="dict.value"></el-option>
              </el-select>
            </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:recipe:add']">新增食谱</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button  @click="handleNew()"  >食谱分类</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="primary"  :disabled="recommend" @click="handleRecommend()">批量智能推荐</el-button>
          </el-col>
          
          <el-col :span="1.5">
            <el-button type="primary"  :disabled="cancleRecommend" @click="handleCancleRecommend()">批量取消智能推荐</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:recipe:remove']">批量删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:recipe:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:recipe: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="recipeList" @selection-change="handleSelectionChange" ref="tableRef">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="食谱编码" align="center" prop="recipeId" width="200px"/>
        <el-table-column label="膳食类型" align="left" prop="baseDietName"  width="150px"/>
        <el-table-column label="食谱分类" align="left" prop="categoryName" width="150px"/>
        <el-table-column label="食谱名称" align="left" prop="name" />
        <el-table-column label="食谱价格" align="left" prop="price" width="150px"/>
        <el-table-column label="智能推荐" align="left" prop="smartRecommend" width="150px">
        <template #default="scope">
            <el-switch v-model="scope.row.smartRecommend" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="230px">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleUpdate(true,scope.row)" v-hasPermi="['system:recipe:edit']">详情</el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(false,scope.row)" v-hasPermi="['system:recipe:edit']">编辑</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete( scope.row)" v-hasPermi="['system:recipe: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="800px" append-to-body>
      <el-row :gutter="10" class="mb8">         
          <el-col :span="21"> 
            <el-form-item label="新增食谱分类" prop="name">
              <el-input v-model="recipeCategoryFormData.name" placeholder="请输入食谱分类名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="3" align="right">
            <el-button :loading="buttonLoading" type="primary" @click="submitRecipeCategoryForm">确 定</el-button>     
          </el-col> 
        </el-row> 

      <el-table border :data="recipeCategoryList">
        <el-table-column label="食谱分类名称" align="left" prop="name" />        
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope"> 
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleRecipeCategoryUpdate(scope.row)">编辑</el-button>
            </el-tooltip>          
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleRecipeCategoryDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div> 
   
</template>


<script setup name="Recipe" lang="ts">
import { listRecipeCategory, getRecipeCategory, delRecipeCategory, addRecipeCategory, updateRecipeCategory } from '@/api/system/recipeCategory';
import { RecipeCategoryVO, RecipeCategoryQuery, RecipeCategoryForm } from '@/api/system/recipeCategory/types';
import { listRecipe, getRecipe, delRecipe, addRecipe, updateRecipe,changeRecipeStatus } from '@/api/system/recipe';
import { RecipeVO, RecipeQuery, RecipeForm } from '@/api/system/recipe/types';
import { title } from 'process';


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {  intelligent_recommendation, dietary_types } = toRefs<any>(proxy?.useDict('intelligent_recommendation', 'dietary_types'));
 
const cancleRecommend = ref(true);
const recommend = ref(true);
const router = useRouter();
const recipeList = ref<RecipeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const idRows = ref<Array<RecipeVO>>([]);
const idForNames = ref<string>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const recipeCategoryList = ref<RecipeCategoryVO[]>([]);
const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<ElTableInstance>();

 

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


const recipeCategoryFormData  =ref<RecipeCategoryForm> ({
  recipeCategoryId: undefined,
  name: undefined,
  sort: undefined,   
  status: undefined,
});

const initFormData: RecipeForm = {
  recipeId: undefined,
  name: undefined,
  categoryId: undefined,
  baseDiet: undefined,
  mealTime: undefined,
  price: undefined,
  suitableDisease: undefined,
  avoidDisease: undefined,
  suitableDept: undefined,
  smartRecommend: undefined,
  cookingMethod: undefined,
  status: undefined,
}
const data = reactive<PageData<RecipeForm, RecipeQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    categoryId: undefined,
    baseDiet: undefined,
    mealTime: undefined,
    price: undefined,
    suitableDisease: undefined,
    avoidDisease: undefined,
    suitableDept: undefined,
    smartRecommend: undefined,
    cookingMethod: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    recipeId: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "食谱名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "食谱分类ID不能为空", trigger: "blur" }
    ],
  }
});

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: RecipeVO[]) => {
  ids.value = selection.map(item => item.recipeId);
  idRows.value=selection;
  idForNames.value= selection.map(item => item.name).join(',');
  // single.value = selection.length != 1;
  multiple.value = !selection.length;
  if(selection&&selection.length==0){
    recommend.value=true;
    cancleRecommend.value=true;
  }else{
    recommend.value=selection.filter((value: RecipeVO, index: number, array: RecipeVO[])=>{     
    return value.smartRecommend=='1';
  }).length!=selection.length;

  cancleRecommend.value=selection.filter((value: RecipeVO, index: number, array: RecipeVO[])=>{     
    return value.smartRecommend=='0';
  }).length!=selection.length;
  }  
}

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

/** 修改按钮操作 */
const handleNew = async ( ) => {
  dialog.visible = true;
  dialog.title = "食谱分类管理";
  await getRecipeCategoryList();
}

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

 

/** 查询食谱管理列表 */
const getRecipeCategoryList = async () => {
  const queryParams =ref<RecipeCategoryQuery>({
      pageNum: 1,
      pageSize: -1,
    }) 
  const res = await listRecipeCategory(queryParams.value);
  recipeCategoryList.value = res.rows;   
}

/** 提交按钮 */
const submitRecipeCategoryForm = async () => {
  if(!recipeCategoryFormData.value.name){
    proxy?.$modal.msgError("请输入食谱分类名称");
    return;
  }
  recipeCategoryFormData.value.name=recipeCategoryFormData.value.name.trim();
  if(recipeCategoryFormData.value.name.length<1){
    proxy?.$modal.msgError("请输入食谱分类名称");
    return;
  }

  buttonLoading.value = true;
  const res =await addRecipeCategory(recipeCategoryFormData.value).finally(() =>  buttonLoading.value = false);
  if(res.code==200){
      proxy?.$modal.msgSuccess("操作成功");       
      await getRecipeCategoryList();
    }else{
      proxy?.$modal.msgError(res.message);
    }  
}

const handleRecipeCategoryUpdate = async (row?: RecipeCategoryVO) => {  
  recipeCategoryFormData.value.name=row?.name.trim();
}

const handleRecipeCategoryDelete = async (row?: RecipeCategoryVO) => {
  await proxy?.$modal.confirm('是否确认删除食谱分类名称为"' + row?.name + '"的数据项？').finally(() => loading.value = false);
  await delRecipeCategory(row?.recipeCategoryId) ;
  proxy?.$modal.msgSuccess("删除成功");
  await getRecipeCategoryList();
}



/** 删除按钮操作 */
const handleDelete = async (row?: RecipeVO) => {
  const _recipeIds = row?.recipeId || ids.value;
  const _recipeNames = row?.name || idForNames.value;
  await proxy?.$modal.confirm('是否确认删除食谱名称为"' + _recipeNames + '"的数据项？').finally(() => loading.value = false);
  await delRecipe(_recipeIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}


const handleStatusChange = async (row: RecipeVO) => {
  const text = row.smartRecommend === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.name + '"食谱吗?');
    await changeRecipeStatus(row.recipeId, row.smartRecommend);
    proxy?.$modal.msgSuccess(text + '成功');  
  } catch {
    row.smartRecommend = row.smartRecommend === '0' ? '1' : '0';
  }
};

const handleRecommend = async ( ) => {
    const _recipeIds =  ids.value.join(",");
    const _recipeNames =  idForNames.value;
    const text =  '启用'  ;
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + _recipeNames + '"食谱吗?');
    await changeRecipeStatus(_recipeIds, '0');
    idRows.value.forEach(item=>{
      item.smartRecommend='0';
      tableRef.value?.clearSelection(); 
    })
    proxy?.$modal.msgSuccess(text + '成功');  
  } catch {     
  }
};


const handleCancleRecommend = async ( ) => {
    const _recipeIds =  ids.value.join(",");
    const _recipeNames =  idForNames.value;
    const text =  '停用'  ;
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + _recipeNames + '"食谱吗?');
    await changeRecipeStatus(_recipeIds, '1');
    idRows.value.forEach(item=>{
      item.smartRecommend='1';
      tableRef.value?.clearSelection(); 
    })
    proxy?.$modal.msgSuccess(text + '成功');  
  } catch {     
  }
};

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