<template>
  <el-row>
    <el-col :span="24" class="main animate__animated animate__backInRight" v-loading="loading">
      <el-col :span="24" class="one">
        <cSearch :is_title="false" :is_search="true" :fields="fields" @search="toSearch">
          <template #is_use>
            <el-option v-for="i in statusList" :key="i._id" :label="i.label" :value="i.value"></el-option>
          </template>
        </cSearch>
      </el-col>
      <el-col :span="24" class="two">
        <cButton @toAdd="toAdd"> </cButton>
      </el-col>
      <el-col :span="24" class="thr">
        <cTable :fields="fields" :opera="opera" :list="list" @query="search" :total="total" @rate="toRate" @edit="toEdit" @del="toDel" @changeUse="toChangeUse"> </cTable>
      </el-col>
    </el-col>
  </el-row>
  <cDialog :dialog="dialog" @toClose="toClose">
    <el-col :span="24" class="dialog_one" v-if="dialog.type == '1'">
      <cForm :span="24" :fields="formFields" :form="form" :rules="{}" @save="toSave" label-width="auto">
        <template #params>
          <el-button class="button" type="primary" size="mini" @click="paramsAdd()">添加</el-button>
          <el-table :data="form.params" border size="mini">
            <el-table-column label="参数名" prop="label" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.label" placeholder="请输入参数名"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="参数值" prop="value" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.value" placeholder="请输入参数值"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button type="danger" size="mini" @click="paramsDel(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template #img>
          <cUpload model="img" :list="form.img" :limit="1" url="/files/notarization/apply/upload" listType="picture-card" @change="onUpload"></cUpload>
        </template>
      </cForm>
    </el-col>
  </cDialog>
</template>

<script setup lang="ts">
import { ref, Ref, onMounted, inject } from 'vue';
import { useRouter } from 'vue-router';
// NeedChange
import { ApplyStore } from '@/stores/core/apply';
import { DictDataStore } from '@/stores/system/dictData';
import type { IQueryResult } from '@/util/types.util';
import { cloneDeep, get } from 'lodash';
import baseStore from '@/stores/counter';
const user = ref(baseStore.state.user);
onMounted(async () => {
  loading.value = true;
  await searchOther();
  await search({ skip, limit });
  loading.value = false;
});
// 路由
const router = useRouter();
const loading: Ref<any> = ref(false);
// NeedChange
const store = ApplyStore();
const dictDataStore = DictDataStore();
const $checkRes = inject('$checkRes') as Function;

// #region 字典
// NeedChange
const statusList: Ref<any> = ref([]);

const searchOther = async () => {
  let res: IQueryResult;
  // 是否使用
  res = await dictDataStore.query({ code: 'isUse', is_use: '0' });
  if ($checkRes(res)) statusList.value = res.data;
};
// #endregion

// #region 查询相关
let list: Ref<any> = ref([]);
let total: Ref<number> = ref(0);
let skip = 0;
let limit = inject('$limit') as number;
let searchForm: Ref<any> = ref({});

const search = async (e: { skip: number; limit: number }) => {
  const info = { skip: e.skip, limit: e.limit, ...searchForm.value };
  const res: IQueryResult = await store.query(info);
  if (res.errcode == '0') {
    list.value = res.data;
    total.value = res.total;
  }
};
const toSearch = (query) => {
  searchForm.value = query;
  search({ skip, limit });
};
const toChangeUse = async (data) => {
  let status = '0';
  switch (data.is_use) {
    case '0':
      status = '1';
      break;
    case '1':
      status = '0';
      break;
    default:
      break;
  }
  const udata = { _id: data._id, is_use: status };
  const res = await store.update(udata);
  if ($checkRes(res, true)) {
    search({ skip: 0, limit });
  }
};
// #endregion

// #region 表格及操作
// NeedChange
let fields: Ref<any[]> = ref([
  { label: '菜品名称', model: 'name', isSearch: true },
  { label: '卡路里(大卡)', model: 'reserve' },
  { label: '是否使用', model: 'is_use', format: (i) => getDict(i, 'is_use'), isSearch: true, type: 'select' }
]);
// 操作
let opera: Ref<any[]> = ref([
  { label: '修改', method: 'edit' },
  { label: '评价', method: 'rate' },
  { label: '禁用', method: 'changeUse', type: 'warning', confirm: true, display: (i) => i.is_use === '0' },
  { label: '使用', method: 'changeUse', type: 'success', confirm: true, display: (i) => i.is_use === '1' },
  { label: '删除', method: 'del', confirm: true, type: 'danger' }
]);

const getDict = (data, model) => {
  let list;
  switch (model) {
    case 'is_use':
      list = statusList.value;
      break;
    default:
      break;
  }
  if (!list) return;
  const res = list.find((f) => f.value == data);
  return get(res, 'label');
};
const toAdd = () => {
  formFields.value = formFieldsForCreate;
  // 所属人是自己,需要把自己的id放进去
  form.value = { ...cloneDeep(defaultForm) };
  dialog.value.show = true;
};
const toEdit = async (data) => {
  formFields.value = formFieldsForUpdate;
  form.value = { ...data };
  dialog.value.show = true;
};
// 菜品评价
const toRate = async (data) => {
  router.push({ path: '/rate', query: { id: data._id } });
};
// #endregion

// #region 常规接口
const toSave = async () => {
  const data = cloneDeep(form.value);
  let res: IQueryResult;
  if (get(data, '_id')) res = await store.update(data);
  else res = await store.create(data);
  if ($checkRes(res, true)) {
    search({ skip: 0, limit });
    toClose();
  }
};
const toDel = async (data) => {
  const res = await store.del(data._id);
  if ($checkRes(res, true)) {
    search({ skip: 0, limit });
  }
};

// #endregion

// #region 表单及操作
// NeedChange
const defaultForm = { is_use: '0', img: [] };
const formFields: Ref<any> = ref();
const dialog: Ref<any> = ref({ title: '数据信息', show: false, type: '1' });
const form: Ref<any> = ref({ img: [], params: [] });
const formFieldsForCreate = [
  { label: '菜品名称', model: 'name' },
  { label: '卡路里(大卡)', model: 'reserve', type: 'number' },
  { label: '参数列表', model: 'params', custom: true },
  { label: '图片', model: 'img', custom: true },
  { label: '菜品介绍', model: 'content', type: 'textarea' },
  { label: '备注', model: 'remark', type: 'textarea' }
];
const formFieldsForUpdate = [
  { label: '菜品名称', model: 'name' },
  { label: '卡路里(大卡)', model: 'reserve', type: 'number' },
  { label: '参数列表', model: 'params', custom: true },
  { label: '图片', model: 'img', custom: true },
  { label: '菜品介绍', model: 'content', type: 'textarea' },
  { label: '备注', model: 'remark', type: 'textarea' }
];
// 添加参数
const paramsAdd = () => {
  let list = form.value.params || [];
  list.push({});
  form.value.params = list;
};
// 删除参数
const paramsDel = (index: number) => {
  let list = form.value.params;
  list.splice(index, 1);
  form.value.params = list;
};
// 关闭弹框
const toClose = () => {
  form.value = {};
  dialog.value.show = false;
};
const onUpload = (e: { model: string; value: Array<[]> }) => {
  console.log(e);
  const { model, value } = e;
  form.value[model] = value;
};
// #endregion
</script>

<style scoped lang="scss">
.dialog_one {
  .button {
    margin: 0 0 5px 0;
  }
}
</style>
