<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 #scientist_id>
              <el-option v-for="i in scientistList" :key="i.id" :label="i.name" :value="i._id"></el-option>
            </template>
            <template #fields>
              <el-option v-for="i in fieldList" :key="i.dict_value" :label="i.dict_label" :value="i.dict_value"></el-option>
            </template>
            <template #direction>
              <span v-for="(i, index) in form.direction" :key="index" class="direction">
                <span>{{ index + 1 }}.</span>{{ i.name }}
              </span>
            </template>
            <template #studio_id>
              <el-option v-for="i in studioList" :key="i._id" :label="i.apply_name || i.name" :value="i._id"></el-option>
            </template>
            <template #settle_file>
              <component :is="CFile" model="settle_file" :limit="limit" :url="url" :list="form.settle_file" @change="onChange"></component>
            </template>
            <template #team>
              <el-col :span="24" class="team_1">
                <el-button type="primary" size="small" @click="addTeam()">添加团队成员</el-button>
                <el-col :span="24" class="team_txt">团队成员人数不可超过15人！</el-col>
              </el-col>
              <el-col :span="24" class="team_2">
                <el-table :data="form.team" border size="small">
                  <el-table-column type="index" label="序号" width="50" align="center"> </el-table-column>
                  <el-table-column prop="name" label="姓名" align="center">
                    <template v-slot="scope">
                      <el-input v-model="scope.row.name" placeholder="请输入姓名"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="company" label="工作单位" align="center">
                    <template v-slot="scope">
                      <el-input v-model="scope.row.company" placeholder="请输入工作单位"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="zc" label="职称" align="center">
                    <template v-slot="scope">
                      <el-input v-model="scope.row.zc" placeholder="请输入职称"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="phone" label="手机号码" align="center">
                    <template v-slot="scope">
                      <el-input v-model="scope.row.phone" placeholder="请输入手机号码"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="100" v-if="form.status == null">
                    <template v-slot="scope">
                      <el-button size="small" type="danger" @click="delTeam(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </template>
          </component>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import store from '@/stores/counter';
import moment from 'moment';
// #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 { ScientistsettleStore } from '@common/src/stores/studio/studios/scientistsettle'; // 入驻科学家工作室
import { StudioStore } from '@common/src/stores/studio/studios/studio'; // 工作室
import { UnitStudioApplyStore } from '@common/src/stores/studio/role/unitStudioApply'; // 依托单位申请科学家工作室权限表
import { UserStudioApplyStore } from '@common/src/stores/studio/role/userStudioApply'; //个人账号申请科学家工作室权限表
import { DictDataStore } from '@common/src/stores/users/sysdictdata'; // 字典表
import type { IQueryResult } from '@/util/types.util';
const studio = StudioStore();
const unitStudioApply = UnitStudioApplyStore();
const scientistsettle = ScientistsettleStore();
const sysdictdata = DictDataStore();
const userStudioApply = UserStudioApplyStore();
let route = useRoute();
// 必填项
const rules = reactive<FormRules>({});
// 表单
let fields: Ref<any[]> = ref([
  { label: '依托单位名称', model: 'company_name', options: { disabled: true } },
  {
    label: '科学家工作室',
    model: 'studio_id',
    type: 'select',
    format: (i) => {
      let data = studioList.value.find((r) => r._id == i);
      if (data) return data.name;
    },
    options: { disabled: true },
  },
  {
    label: '科学家姓名',
    model: 'scientist_id',
    type: 'select',
    format: (i) => {
      let data = scientistList.value.find((r) => r._id == i);
      if (data) return data.name;
    },
    options: { disabled: true },
  },
  { label: '工作单位', model: 'company', options: { disabled: true } },
  { label: '职称', model: 'zc', options: { disabled: true } },
  { label: '专业领域', model: 'fields', type: 'selectMany', options: { disabled: true } },
  { label: '研究方向', model: 'direction', custom: true },
  { label: '文件', model: 'settle_file', custom: true },
  { label: '团队成员', model: 'team', custom: true },
]);
let limit: Ref<number> = ref(1);
let url: Ref<string> = ref('/files/studioadmin/support/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 }> = ref({ _id: '', status: '', company: '' });
// 表单
let form: Ref<{
  scientist_name: string;
  user_id: string;
  company: string;
  zc: string;
  fields: Array<any>;
  direction: Array<any>;
  settle_file: Array<any>;
  team: Array<any>;
  status: string;
}> = ref({
  scientist_name: '',
  user_id: '',
  company: '',
  zc: '',
  fields: [],
  direction: [],
  settle_file: [],
  status: '',
  team: [],
});
// 行业领域
let fieldList: Ref<any[]> = ref([]);
// 科学家信息
let scientistList: Ref<any[]> = ref([]);
// 工作室
let studioList: Ref<any[]> = ref([]);
onMounted(async () => {
  user.value = store.state.user as { _id: string; name: string; unit_name: string; nick_name: string };
  await searchOther();
  await searchUnit();
  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 = {
    company_id: unitInfo.value._id,
    company_name: unitInfo.value.company,
    scientist_name: '',
    user_id: '',
    company: '',
    zc: '',
    fields: [],
    direction: [],
    settle_file: [],
    status: '',
    team: [],
  };
  if (route.query && route.query.id) {
    let id = route.query.id;
    const res: IQueryResult = await scientistsettle.fetch(id);
    if (res.errcode == 0) {
      if (res.data) {
        form.value = res.data as { scientist_name: ''; user_id: ''; company: ''; zc: ''; fields: []; direction: []; settle_file: []; status: ''; team: [] };
      }
    }
  } else {
    form.value = { ...data };
  }
};
// 添加成员信息
const addTeam = () => {
  let team = form.value.team;
  if (team.length >= 15) {
    ElMessage({ message: `团队成员人数不可超过15人!`, type: 'error' });
  } else {
    team.push({ id: moment().valueOf(), name: '' });
  }
  form.value.team = team;
};
// 团队成员信息删除
const delTeam = (e) => {
  let team = form.value.team.filter((i: any) => i.id != e.id);
  form.value.team = team;
};
const dataChange = (model, value) => {
  if (model == 'scientist_id') {
    let data = scientistList.value.find((i) => i._id == value);
    if (data) {
      form.value.scientist_name = data.name;
      form.value.user_id = data.user_id;
      form.value.company = data.company;
      form.value.zc = data.zc;
      form.value.fields = data.fields;
      form.value.direction = data.direction;
    }
  }
};
// 返回
const toBack = () => {
  window.history.go(-1);
};
// 上传
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 scientistsettle.update(data);
  else res = await scientistsettle.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 userStudioApply.query({ status: '1' });
  scientistList.value = p1.data as [];
  // 领域
  const p2: IQueryResult = await sysdictdata.query({ dict_type: 'studio_field' });
  fieldList.value = p2.data as [];
  // 工作室
  const p3: IQueryResult = await studio.query({ user_id: user.value._id });
  studioList.value = p3.data as [];
};
</script>

<style scoped></style>
