<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 #type>
            <el-option v-for="i in serviceTypeList" :key="i._id" :label="i.label" :value="i.value"></el-option>
          </template>
          <template #way>
            <el-option v-for="i in wayList" :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" @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 #status>
          <el-radio v-for="i in statusList" :key="i._id" :label="i.value">{{ i.label }}</el-radio>
        </template>
        <template #type>
          <el-option v-for="i in serviceTypeList" :key="i._id" :label="i.label" :value="i.value"></el-option>
        </template>
        <template #way>
          <el-option v-for="i in wayList" :key="i._id" :label="i.label" :value="i.value"></el-option>
        </template>
        <template #area>
          <el-option v-for="i in areaList" :key="i._id" :label="i.label" :value="i.value"></el-option>
        </template>
        <template #tags>
          <el-row>
            <el-col :span="24">
              <el-button size="small" @click="addTags" type="primary">添加标签</el-button>
            </el-col>
            <el-col :span="24">
              <el-table border stripe :data="form.tags" height="20vh">
                <el-table-column align="center" label="标签文案">
                  <template v-slot="{ row }">
                    <el-input v-model="row.label" />
                  </template>
                </el-table-column>
                <el-table-column align="center" label="标签级别">
                  <template v-slot="{ row }">
                    <el-select v-model="row.type">
                      <el-option label="低" value="primary">
                        <el-link type="primary">低</el-link>
                      </el-option>
                      <el-option label="中" value="warning">
                        <el-link type="warning">中</el-link>
                      </el-option>
                      <el-option label="高" value="danger">
                        <el-link type="danger">高</el-link>
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="删除">
                  <template v-slot="{ $index }">
                    <el-link type="danger" @click="toDelTag($index)">删除</el-link>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </template>
      </cForm>
    </el-col>
  </cDialog>
</template>

<script setup lang="ts">
import { ref, Ref, onMounted, inject } from 'vue';
// NeedChange
import { ServiceStore } from '@/stores/core/service';
import { DictDataStore } from '@/stores/system/dictData';
import type { IQueryResult } from '@/util/types.util';
import { cloneDeep, get, isArray, isString } 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 loading: Ref<any> = ref(false);
// NeedChange
const store = ServiceStore();
const dictDataStore = DictDataStore();
const $checkRes = inject('$checkRes') as Function;

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

const searchOther = async () => {
  const statusResult: IQueryResult = await dictDataStore.query({ code: 'serviceStatus' });
  if ($checkRes(statusResult)) {
    statusList.value = statusResult.data;
  }
  const serviceTypeResult: IQueryResult = await dictDataStore.query({ code: 'serviceType' });
  if ($checkRes(serviceTypeResult)) {
    serviceTypeList.value = serviceTypeResult.data;
  }
  const serviceWayResult: IQueryResult = await dictDataStore.query({ code: 'serviceWay' });
  if ($checkRes(serviceWayResult)) {
    wayList.value = serviceWayResult.data;
  }
  const areaResult: IQueryResult = await dictDataStore.query({ code: 'serviceArea' });
  if ($checkRes(areaResult)) {
    areaList.value = areaResult.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, owner: user.value._id };
  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.status) {
    case '0':
      status = '1';
      break;
    case '1':
      status = '0';
      break;
    default:
      break;
  }
  const udata = { _id: data._id, 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: 'title', isSearch: true },
  { label: '服务类型', model: 'type', isSearch: true, type: 'selectMult', format: (i) => getDict(i, 'type') },
  { label: '服务方式', model: 'way', isSearch: true, type: 'selectMult', format: (i) => getDict(i, 'way') },
  { label: '服务地区', model: 'area', format: (i) => getDict(i, 'area') },
  { label: '价格', model: 'money' },
  { label: '服务状态', model: 'status', format: (i) => getDict(i, 'status') }
]);
// 操作
let opera: Ref<any[]> = ref([
  { label: '修改', method: 'edit' },
  { label: '禁用', method: 'changeUse', type: 'warning', confirm: true, confirmWord: '您确定禁用该服务?', display: (i) => i.status === '0' },
  { label: '启用', method: 'changeUse', type: 'success', confirm: true, confirmWord: '您确定启用该服务?', display: (i) => i.status === '1' },
  { label: '删除', method: 'del', confirm: true, type: 'danger' }
]);

const getDict = (data, model) => {
  let list;
  switch (model) {
    case 'status':
      list = statusList.value;
      break;
    case 'type':
      list = serviceTypeList.value;
      break;
    case 'way':
      list = wayList.value;
      break;
    case 'area':
      list = areaList.value;
      break;
    default:
      break;
  }
  if (!list) return;
  if (isString(data)) {
    const res = list.find((f) => f.value == data);
    return get(res, 'label');
  } else if (isArray(data)) {
    const arr = [];
    for (const i of data) {
      const res = list.find((f) => f.value == data);
      if (res) arr.push(get(res, 'label'));
    }
  }
};
const toAdd = () => {
  formFields.value = formFieldsForCreate;
  // 所属人是自己,需要把自己的id放进去
  form.value = { ...cloneDeep(defaultForm), owner: user.value._id };
  dialog.value.show = true;
};
const toEdit = (data) => {
  formFields.value = formFieldsForUpdate;
  form.value = { ...data };
  dialog.value.show = true;
};
// #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 = { status: '0', tags: [] };
const formFields: Ref<any> = ref();
const dialog: Ref<any> = ref({ title: '数据信息', show: false, type: '1' });
const form: Ref<any> = ref({ file: [] });
const formFieldsForCreate = [
  { label: '服务标题', model: 'title' },
  { label: '服务类型', model: 'type', type: 'select' },
  { label: '标签', model: 'tags', custom: true },
  { label: '服务方式', model: 'way', type: 'select' },
  { label: '服务地区', model: 'area', type: 'select' },
  { label: '价格', model: 'money' },
  { label: '服务描述', model: 'desc', type: 'textarea' }
];
const formFieldsForUpdate = [
  { label: '服务标题', model: 'title' },
  { label: '服务类型', model: 'type', type: 'select' },
  { label: '标签', model: 'tags', custom: true },
  { label: '服务方式', model: 'way', type: 'select' },
  { label: '服务地区', model: 'area', type: 'select' },
  { label: '价格', model: 'money' },
  { label: '服务描述', model: 'desc', type: 'textarea' }
];
const addTags = () => {
  form.value.tags.push({ type: 'primary' });
};
const toDelTag = (index) => {
  form.value.tags.splice(index, 1);
};
// 关闭弹框
const toClose = () => {
  form.value = {};
  dialog.value.show = false;
};
// #endregion
</script>

<style scoped></style>
