<template>
  <div id="index">
    <el-col class="main animate__animated animate__backInRight">
      <el-col :span="24" class="one">
        <component :is="partsSearch" :is_search="true" :fields="fields" @search="partSearch">
          <template #status>
            <el-option v-for="i in statusList" :key="i.model" :label="i.dict_label" :value="i.dict_value"></el-option>
          </template> 
          <!-- <template #unit_phone>
            <el-input v-model="searchForm.unit_phone" placeholder="请输入单位联系电话" clearable size="small"></el-input>
          </template> -->
        </component>
      </el-col>
      <el-col :span="24" class="two">
        <component
          :is="CTable"
          :fields="fields"
          :opera="opera"
          :select="false"
          :selected="selected"
          @handleSelect="handleSelect"
          @query="search"
          :data="tableData"
          :total="total"
          @view="toView"
          @exam="toExam"
          @del="toDel"
        >
          <!-- <template #unit_phone="{ row, item }">
            {{ row[item.model].phone }}
          </template> -->
        </component>
      </el-col>
    </el-col>
  </div>
  <el-dialog v-model="dialog.show" title="文件夹" :before-close="handleClose">
    <component :is="CForm" :fields="infoFields" :rules="rules" :form="form" labelWidth="auto" @save="toSave">
      <template #status>
        <el-option v-for="(item, index) in statusList" :key="index" :label="item.dict_label" :value="item.dict_value"></el-option>
      </template>
    </component>
  </el-dialog>
</template>
<script setup lang="ts">
import store from '@/stores/counter';
import moment from 'moment';
// #region 组件
import partsSearch from '@/components/c-search.vue';
import CTable from '@/components/c-table.vue';
import CForm from '@/components/c-form.vue';
// #endregion
import type { Ref } from 'vue';
import { ref, onMounted, getCurrentInstance, reactive } from 'vue';
import type { FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
// #region 接口
import { UserStudioApplyStore } from '@common/src/stores/studio/role/userStudioApply'; // 列表
import { DictDataStore } from '@common/src/stores/users/sysdictdata'; // 字典表
import { MessageStore } from '@common/src/stores/studio/other/message'; // 系统消息
import { UsersStore } from '@common/src/stores/users/users';
import { RoleStore } from '@common/src/stores/admin/role';
import type { IQueryResult } from '@/util/types.util';
const userStudioApply = UserStudioApplyStore();
const dictData = DictDataStore();
const message = MessageStore();
const role = RoleStore();
const users = UsersStore();
const { proxy } = getCurrentInstance() as any;
const router = useRouter();
interface operaItem {
  label: string;
  method: string;
  confirm?: boolean;
  type?: string;
  display?: any;
}
// #endregion
// 列表数据
let tableData: Ref<any[]> = ref([]);
// 列表
let fields: Ref<any[]> = ref([
  { label: '序号', options: { type: 'index' } },
  { label: '姓名', model: 'name', isSearch: true },
  { label: '出生年月', model: 'brith' },
  { label: '居住地', model: 'live_place' },
  { label: '手机号', model: 'phone.phone' },
  { label: '电子邮箱', model: 'email.email' },
  { label: '团队联系人', model: 'team_name' },
  { label: '团队联系电话', model: 'team_phone.phone' },
  { label: '所在单位全称', model: 'company', isSearch: true },
  {
    label: '审核状态',
    model: 'status',
    type: 'select',
    format: (i) => {
      let data = statusList.value.find((r) => r.dict_value == i);
      if (data) return data.dict_label;
    },
    isSearch: true,
  },
]);
// 操作
let opera: Ref<any[]> = ref([
  { label: '详情', method: 'view' },
  { label: '审核', method: 'exam', type: 'warning', display: (i) => i.status == '0' },
  { label: '删除', method: 'del', type: 'danger', confirm: true },
]);
// 多选
let selected: Ref<any[]> = ref([]);
// 总数
let total: Ref<number> = ref(0);
let skip = 0;
let limit: number = proxy.$limit;
// 查询数据
let searchForm: Ref<{}> = ref({});
// 弹框
const dialog: Ref<{ type: string; show: boolean; title: string }> = ref({ type: '1', show: false, title: '信息管理' });
// 审核表单
let form: Ref<{}> = ref({});
// 必填项
const rules = reactive<FormRules>({
  status: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
  remark: [{ required: true, message: '请输入审核意见', trigger: 'blur' }],
});
// 表单
let infoFields: Ref<any[]> = ref([
  { label: '审核状态', model: 'status', type: 'select' },
  { label: '审核意见', model: 'remark', type: 'textarea' },
]);
// 角色
let roleInfo: Ref<{ _id: string }> = ref({ _id: '' });
// 状态
let statusList: Ref<any[]> = ref([]);

onMounted(async () => {
  await searchOther();
  await search({ skip, limit });
});
// 查询
const search = async (e: { skip: number; limit: number }) => {
  const { skip, limit } = e;
  let info = { limit: limit, skip: skip, ...searchForm.value };
  const res: IQueryResult = await userStudioApply.query(info);
  tableData.value = res.data as any[];
  total.value = res.total;
};
// 查询
const partSearch = (form: { [x: string]: any }) => {
  searchForm.value = form;
  search({ skip, limit });
};

// 修改
const toView = async (data: { _id: string }) => {
  router.push({ path: '/center/users/scientist/info', query: { id: data._id } });
};
// 审核
const toExam = (data: object) => {
  console.log(data);

  form.value = data;
  dialog.value = { title: '信息管理', show: true, type: '1' };
};
// 审核保存
const toSave = async (data: { _id: string; status: string }) => {
  let obj = { _id: data._id, status: data.status };
  let res: IQueryResult = await userStudioApply.create(obj);
  if (obj.status == '1') updateRole(data);
  if (res.errcode == 0) {
    ElMessage({ type: 'success', message: '维护信息成功' });
    createMess(data);
  } else ElMessage({ type: 'warning', message: `${res.errmsg}` });
};
// // 分配角色
const updateRole = async (e) => {
  let userInfo = await users.fetch(e.unit_id);
  if (userInfo.errcode == 0) {
    let object = {
      _id: userInfo.data._id,
      role: [...userInfo.data.role, roleInfo.value._id],
      account: userInfo.data.account,
      unit_name: userInfo.data.unit_name,
    };
    let res = await users.update(object);
  }
};
// // 发送系统消息
const createMess = async (data) => {
  let user = store.state.user;
  let res = await users.fetch(data.unit_id);
  if (res.errcode == 0) {
    let obj = {
      user_id: user._id,
      title: '审核通知',
      send_time: moment().format('YYYY-MM-DD HH:mm:ss'),
      type: '3',
      user: [{ id: data.unit_id, company: data.company, phone: data.phone }],
      content: '您好，权限申请，' + `${data.status == '1' ? '已通过审核' : '未通过审核'}` + ',原因：' + data.remark,
    };
    let arr = await message.create(obj);
    if (arr.errcode == 0) {
      ElMessage({ type: 'success', message: '系统信息发送成功' });
      handleClose();
    }
  }
};
// 删除
const toDel = async (data: { _id: string }) => {
  const res: IQueryResult = await userStudioApply.del(data._id);
  if (res.errcode == 0) {
    ElMessage({ type: 'success', message: '删除成功' });
    search({ skip, limit });
  }
};

// 关闭弹窗
const handleClose = () => {
  form.value = {};
  search({ skip, limit });
  dialog.value = { title: '信息管理', show: false, type: '' };
};
// 选择
const handleSelect = () => {};
// 查询其他信息
const searchOther = async () => {
  // 字典表---审核状态
  const p1: IQueryResult = await dictData.query({ dict_type: 'studio_status' });
  statusList.value = p1.data as [];
  // 角色
  const p2 = await role.query({ code: 'studio-users', account_type: '3', status: 'Y' });
  roleInfo.value = p2.data[0];
};
</script>
<style scoped>
.main .one {
  margin: 0 0 10px 0;
}
</style>
