<template>
  <div id="index">
    <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"> </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">
            <template #leader="{ item, row }">
              <template v-if="item.model === 'leader'">
                <span size="small" type="primary">{{ getProps(row, item.model) }}</span>
              </template>
            </template>
            <template #accounting="{ item, row }">
              <template v-if="item.model === 'accounting'">
                <span size="small" type="primary">{{ getProps(row, item.model) }}</span>
              </template>
            </template>
          </cTable>
        </el-col>
      </el-col>
    </el-row>
    <cDialog :dialog="dialog" @toClose="toClose">
      <template v-slot:info>
        <el-col :span="24" class="dialog_one" v-if="dialog.type == '1'">
          <cForm :span="24" :fields="formFields" :form="form" :rules="rules" @save="toSave">
            <template #office>
              <el-option @click="toChange(i)" v-for="i in officeList" :key="i._id" :label="i.name"
                :value="i._id"></el-option>
            </template>
            <template #is_use>
              <el-radio v-for="(i, index) in is_useList" :key="index" :label="i.value">{{ i.label }}</el-radio>
            </template>
            <template #leader>
              <el-select v-model="form.leader" multiple placeholder="请选择审批领导" style="width: 100%">
                <el-option v-for="item in ldList" :key="item._id" :label="item.name" :value="item._id" />
              </el-select>
            </template>
            <template #accounting>
              <el-select v-model="form.accounting" multiple placeholder="请选择审批会计" style="width: 100%">
                <el-option v-for="item in kjList" :key="item._id" :label="item.name" :value="item._id" />
              </el-select>
            </template>
          </cForm>
        </el-col>
      </template>
    </cDialog>
  </div>
</template>

<script setup lang="ts">
// 基础
import _ from 'lodash';
import type { FormRules } from 'element-plus';
import type { Ref } from 'vue';
import { ref, onMounted, getCurrentInstance, reactive } from 'vue';
import { ElMessage } from 'element-plus';
// 接口
import { CollectionStore } from '@/stores/collection/collection';
import { DictDataStore } from '@/stores/dict/dictData';
import { OfficeStore } from '@/stores/office/office';
import { UserStore } from '@/stores/users/user';
import type { IQueryResult } from '@/util/types.util';
const dictData = DictDataStore();
const collectionAxios = CollectionStore();
const officeAxios = OfficeStore();
const userAxios = UserStore();
const { proxy } = getCurrentInstance() as any;
// 加载中
const loading: Ref<any> = ref(false);
// 列表数据
let list: Ref<any> = ref([]);
let total: Ref<number> = ref(0);
let skip = 0;
let limit: number = proxy.$limit;
let fields: Ref<any[]> = ref([
  { label: '街道', model: 'office', format: (i: any) => getDict(i, 'office') },
  { label: '领导', model: 'leader', custom: true },
  { label: '会计', model: 'accounting', custom: true },
  { label: '是否使用', model: 'is_use', format: (i: any) => getDict(i, 'is_use') }
]);
// 操作
let opera: Ref<any[]> = ref([
  { label: '修改', method: 'edit' },
  { label: '删除', method: 'del', confirm: true, type: 'danger' }
]);
// 弹框
const dialog: Ref<{ type: string; show: boolean; title: string }> = ref({ type: '1', show: false, title: '信息管理' });
let form: Ref<{ leader: Array<any>; accounting: Array<any> }> = ref({ leader: [], accounting: [] });
// 表单
let formFields: Ref<any[]> = ref([
  { label: '街道', model: 'office', type: 'select' },
  { label: '领导', model: 'leader', custom: true },
  { label: '会计', model: 'accounting', custom: true },
  { label: '是否使用', model: 'is_use', type: 'radio' }
]);
const rules = reactive<FormRules>({
  office: [{ required: true, message: '街道', trigger: 'blur' }],
  leader: [{ required: true, message: '领导', trigger: 'blur' }],
  accounting: [{ required: true, message: '会计', trigger: 'blur' }]
});
// 查询数据
let searchForm: Ref<any> = ref({});
// 字典表
let is_useList: Ref<any> = ref([]);
let officeList: Ref<any> = ref([]);
let ldList: Ref<any> = ref([]);
let kjList: Ref<any> = ref([]);

// 请求
onMounted(async () => {
  loading.value = true;
  await searchOther();
  await search({ skip, limit });
  loading.value = false;
});
const search = async (e: { skip: number; limit: number }) => {
  const { skip, limit } = e;
  const condition = _.cloneDeep(searchForm.value);
  let info = { limit: limit, skip: skip, ...condition };
  let res: IQueryResult = await collectionAxios.query(info);
  if (res.errcode == 0) {
    list.value = res.data;
    total.value = res.total;
  }
};
const toSearch = (query: any) => {
  searchForm.value = query;
  search({ skip, limit });
};
const toChange = async (val: any) => {
  let res: IQueryResult;
  let info: any = { status: '1', street: val._id };
  form.value.leader = [];
  form.value.accounting = [];
  // 领导
  res = await userAxios.query({ role: 'ld', ...info });
  if (res.errcode == '0') ldList.value = res.data;
  // 会计
  res = await userAxios.query({ role: 'kj', ...info });
  if (res.errcode == '0') kjList.value = res.data;
};
const getDict = (value: any, model: any) => {
  if (model == 'is_use') {
    if (value) {
      let data = is_useList.value.find((i: any) => i.value == value);
      if (data) return data.label;
      else return '暂无';
    }
  } else if (model == 'office') {
    if (value) {
      let data = officeList.value.find((i: any) => i._id == value);
      if (data) return data.name;
      else return '暂无';
    }
  }
};
const getProps = (data: any, prop: any) => {
  let list = [];
  let res;
  if (prop == 'leader') {
    for (const val of data[prop]) {
      res = ldList.value.find((i) => i._id == val._id);
      if (res) list.push(res.name);
    }
  } else {
    for (const val of data[prop]) {
      res = kjList.value.find((i) => i._id == val._id);
      if (res) list.push(res.name);
    }
  }
  return list.toString();
};
// 新增
const toAdd = () => {
  dialog.value = { title: '信息管理', show: true, type: '1' };
};
// 修改
const toEdit = async (data: any) => {
  form.value = data;
  dialog.value = { title: '信息管理', show: true, type: '1' };
};
// 提交保存
const toSave = async (data: any) => {
  if (data.accounting) {
    if (!data.accounting[0]._id) {
      data.accounting = data.accounting.map((i) => {
        let arrObj = { _id: '' };
        arrObj._id = i;
        return arrObj;
      });
    }
  }
  if (data.leader) {
    if (!data.leader[0]._id) {
      data.leader = data.leader.map((i) => {
        let arrObj = { _id: '' };
        arrObj._id = i;
        return arrObj;
      });
    }
  }
  let res: IQueryResult;
  if (data._id) res = await collectionAxios.update(data);
  else res = await collectionAxios.create(data);
  if (res.errcode == 0) {
    ElMessage({ type: `success`, message: `维护信息成功` });
    toClose();
  } else ElMessage({ type: `warning`, message: `${res.errmsg}` });
};
// 删除
const toDel = async (data: any) => {
  let res: IQueryResult = await collectionAxios.del(data._id);
  if (res.errcode == 0) {
    ElMessage({ type: `success`, message: `刪除信息成功` });
    search({ skip, limit });
  }
};
// 弹框关闭
const toClose = () => {
  form.value = { leader: [], accounting: [] };
  dialog.value = { title: '信息管理', show: false, type: '1' };
  search({ skip, limit });
  searchOther();
};
// 查询其他信息
const searchOther = async () => {
  let res: IQueryResult;
  // 是否使用
  res = await dictData.query({ type: 'is_use' });
  if (res.errcode == '0') is_useList.value = res.data;
  // 街道
  res = await officeAxios.query({ is_use: '0', type: '0' });
  if (res.errcode == '0') officeList.value = res.data;
  // 领导
  res = await userAxios.query({ role: 'ld', status: '1' });
  if (res.errcode == '0') ldList.value = res.data;
  // 会计
  res = await userAxios.query({ role: 'kj', status: '1' });
  if (res.errcode == '0') kjList.value = res.data;
};
</script>
<style scoped lang="scss">
.main {
  .two {
    margin: 0 0 10px 0;
  }
}
</style>
