<template>
  <div id="add">
    <el-row>
      <el-col :span="24" class="main animate__animated animate__backInRight">
        <el-col :span="24" class="one">
          <component :is="partsSearch" :is_back="true" @toBack="toBack"></component>
        </el-col>
        <el-col :span="24" class="two">
          <component :is="CForm" :fields="fields" :rules="rules" :form="form" @dataChange="dataChange" labelWidth="auto" @save="toSave">
            <template #studio_id>
              <el-option v-for="i in studioList" :key="i._id" :label="i.name" :value="i._id"></el-option>
            </template>
            <template #file>
              <component :is="CFile" model="file" :limit="limit" :url="url" :list="form.file" @change="onChange"></component>
            </template>
          </component>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import store from '@/stores/counter';
// #region 组件
import partsSearch from '@common/src/components/frame/c-search.vue';
import CForm from '@common/src/components/frame/c-form.vue';
import CFile from '@common/src/components/frame/c-upload.vue';
// #endregion
import type { Ref } from 'vue';
import { ref, onMounted, reactive } from 'vue';
import type { FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
// #region 接口
import { ApplyflairStore } from '@common/src/stores/studio/studios/applyflair'; //申请保留资质
import { StudioStore } from '@common/src/stores/studio/studios/studio'; // 工作室
import { UnitStudioApplyStore } from '@common/src/stores/studio/role/unitStudioApply'; //个人账号申请科学家工作室权限表
import type { IQueryResult } from '@/util/types.util';
const applyflair = ApplyflairStore();
const studio = StudioStore();
const unitStudioApply = UnitStudioApplyStore();
let route = useRoute();
// 必填项
const rules = reactive<FormRules>({
  studio_id: [{ required: true, message: '请选择工作室名称', trigger: 'change' }],
  file: [{ required: true, message: '请上传评估文件', trigger: 'change' }],
  apply_time: [{ required: true, message: '请选择申请时间', trigger: 'change' }],
});
// 表单
let fields: Ref<any[]> = ref([
  { label: '依托单位名称', model: 'company_name', options: { readonly: true } },
  { label: '工作室名称', model: 'studio_id', type: 'select' },
  { label: '评估文件', model: 'file', custom: true },
  { label: '申请时间', model: 'apply_time', type: 'date' },
]);
let limit: Ref<number> = ref(1);
let url: Ref<string> = ref('/files/studioadmin/applyflair/upload');
// 用户信息
let user: Ref<{ _id: string; name: string; unit_name: string; nick_name: string }> = ref({ _id: '', name: '', unit_name: '', nick_name: '' });
// 依托单位信息
let unitInfo: Ref<{ _id: String; status: String; company: string; phone: string }> = ref({ _id: '', status: '', company: '', phone: '' });
// 表单
let form: Ref<{ file: Array<[]>; studio_name: string }> = ref({ file: [], studio_name: '' });
// 工作室列表
let studioList: Ref<any[]> = ref([]);
onMounted(async () => {
  user.value = store.state.user as { _id: string; name: string; unit_name: string; nick_name: string };
  await searchUnit();
  await searchOther();
  await search();
});
// 依托单位信息
const searchUnit = async () => {
  const res: IQueryResult = await unitStudioApply.query({ unit_id: user.value._id });
  let list = res.data as any[];
  if (res.total > 0) unitInfo.value = list[0];
};
// 查询
const search = async () => {
  let data = {
    user_id: unitInfo.value._id,
    company_name: unitInfo.value.company,
    file: [],
    studio_name: '',
  };
  if (route.query && route.query.id) {
    let id = route.query.id;
    const res: IQueryResult = await applyflair.fetch(id);
    if (res.errcode == 0) {
      if (res.data) form.value = res.data as { content: string; file: Array<[]>; studio_name: string };
    }
  } else {
    form.value = { ...data };
  }
};
// 返回
const toBack = () => {
  window.history.go(-1);
};
// 数据选择
const dataChange = ({ model, value }) => {
  if (model == 'studio_id') {
    let data = studioList.value.find((i) => i._id == value);
    if (data) form.value.studio_name = data.name;
  }
};
// 上传
const onChange = (e: { model: string; value: Array<[]> }) => {
  const { model, value } = e;
  form.value[model] = value;
};
// 添加
const toSave = async (data: { _id: string }) => {
  let res: IQueryResult;
  if (data._id) res = await applyflair.update(data);
  else res = await applyflair.create(data);
  if (res.errcode == 0) {
    ElMessage({ type: 'success', message: '维护信息成功' });
    toBack();
  } else ElMessage({ type: 'warning', message: `${res.errmsg}` });
};
// 查询其他信息
const searchOther = async () => {
  // 工作室
  const p1: IQueryResult = await studio.query({ status: '1', user_id: user.value._id });
  studioList.value = p1.data as [];
};
</script>

<style scoped></style>
