<template>
  <div id="unit-1">
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="24" class="one">
          <el-col :span="24" class="one_1">一、账户信息</el-col>
          <el-col :span="24" class="one_2">
            <component :is="CForm" :fields="fields" :rules="{}" :form="form" labelWidth="auto" @save="toSave">
              <template #is_studio>
                <el-option v-for="item in studioList" :key="item.dict_label" :label="item.dict_label" :value="item.dict_value"></el-option>
              </template>
              <template #prove>
                <component style="width: 100%" :is="CFile" model="prove" :limit="limit" :url="url" :list="form.prove" @change="onChange"></component>
              </template>
            </component>
          </el-col>
        </el-col>
        <el-col :span="24" class="two" v-show="form.is_studio == 'Y'">
          <el-col :span="24" class="two_1">二、基础信息</el-col>
          <el-col :span="24" class="two_2">
            <component :is="CForm" :fields="ufields" :rules="rules" :form="uform" labelWidth="auto" @save="utoSave" @dataChange="dataChange">
              <template #card>
                <component
                  style="width: 100%"
                  :is="CFile"
                  model="card"
                  limit="2"
                  url="/files/studioadmin/register/upload"
                  :list="uform.card"
                  @change="uonChange"
                ></component>
              </template>
              <template #unit_phone>
                <el-col :span="12">
                  <el-form-item label="内容" label-width="100px" prop="unit_phone.phone">
                    <el-input v-model="uform.unit_phone.phone" :disabled="true" placeholder="请输入联系电话"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否公开" label-width="80px">
                    <el-select v-model="uform.unit_phone.is_show" placeholder="请选择" style="width: 100%">
                      <el-option v-for="i in isshowList" :key="i.model" :label="i.dict_label" :value="i.dict_value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </template>
              <template #unit_email>
                <el-col :span="12">
                  <el-form-item label="内容" label-width="100px" prop="unit_email.email">
                    <el-input v-model="uform.unit_email.email" :disabled="true" placeholder="请输入单位联系电话"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否公开" label-width="80px">
                    <el-select v-model="uform.unit_email.is_show" placeholder="请选择" style="width: 100%">
                      <el-option v-for="i in isshowList" :key="i.model" :label="i.dict_label" :value="i.dict_value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </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>
                <el-button style="margin-bottom: 0.5vw" type="primary" size="small" @click="addDriection()">添加</el-button>
                <el-col :span="24">
                  <el-table :data="uform.direction" 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="请输入技术需求方向名称,名称长度不可超过八个字" maxlength="8"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="100">
                      <template v-slot="scope">
                        <el-button size="small" type="danger" @click="delDriection(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
              </template>
              <template #audit_report>
                <component
                  style="width: 100%"
                  :is="CFile"
                  model="audit_report"
                  :limit="limit"
                  :url="url"
                  :list="uform.audit_report"
                  @change="uonChange"
                ></component>
              </template>
              <template #special_report>
                <component
                  style="width: 100%"
                  :is="CFile"
                  model="special_report"
                  :limit="limit"
                  :url="url"
                  :list="uform.special_report"
                  @change="uonChange"
                ></component>
              </template>
              <template #prove_file>
                <component
                  style="width: 100%"
                  :is="CFile"
                  model="prove_file"
                  :limit="limit"
                  :url="url"
                  :list="uform.prove_file"
                  @change="uonChange"
                ></component>
              </template>
            </component>
          </el-col>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import store from '@/stores/counter';
import moment from 'moment';
// #region 组件
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, watch } from 'vue';
import type { FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
// #region 接口
import { UnitStore } from '@common/src/stores/users/unit'; //依托单位
import { UnitStudioApplyStore } from '@common/src/stores/studio/role/unitStudioApply'; // 依托单位申请科学家工作室权限表
import { DictDataStore } from '@common/src/stores/users/sysdictdata'; // 字典表
import type { IQueryResult } from '@/util/types.util';
const unitStudioApply = UnitStudioApplyStore();
const unit = UnitStore();
const sysdictdata = DictDataStore();
// 必填项
const rules = reactive<FormRules>({
  company: [{ required: true, message: '请输入单位全称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入单位地址', trigger: 'blur' }],
  name: [{ required: true, message: '请输入单位法人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '单位法人手机号码', trigger: 'change' },
    { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'change' },
  ],
  card: [{ required: true, message: '请上传法人身份证', trigger: 'change' }],
  unit_contact: [{ required: true, message: '请输入单位联系人', trigger: 'blur' }],
  'unit_phone.phone': [
    { required: true, message: '单位联系电话', trigger: 'change' },
    { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'change' },
  ],
  'unit_email.email': [{ required: true, message: '请输入单位电子邮箱', trigger: 'blur' }],
  fields: [{ required: true, message: '请选择行业领域', trigger: 'change' }],
  direction: [{ required: true, message: '请添加技术需求方向', trigger: 'change' }],
  audit_report: [{ required: true, message: '请上传上一年度财务审计报告', trigger: 'change' }],
  special_report: [{ required: true, message: '请上传上一年度R&D投入专项', trigger: 'change' }],
  prove_file: [{ required: false, message: '请上传其他证明资料', trigger: 'change' }],
});
// 系统表单
let fields: Ref<any[]> = ref([
  { label: '登录账号', model: 'account', options: { readonly: true } },
  { label: '管理员姓名', model: 'name' },
  { label: '管理员手机号', model: 'phone' },
  { label: '管理员电子邮箱', model: 'email' },
  { label: '单位全称', model: 'unit_name' },
  { label: '单位地址', model: 'unit_address' },
  { label: '营业执照', model: 'prove', custom: true },
  { label: '是否入住科学家工作室', model: 'is_studio', type: 'select' },
]);
// 依托单位信息表单
let ufields: Ref<any[]> = ref([
  { label: '单位全称', model: 'company', options: { readonly: true } },
  { label: '单位地址', model: 'address', options: { readonly: true } },
  { label: '单位法人姓名', model: 'name' },
  { label: '单位法人手机号码', model: 'phone' },
  { label: '法人身份证', model: 'card', custom: true },
  { label: '单位联系人', model: 'unit_contact', options: { readonly: true } },
  { label: '单位手机号', model: 'unit_phone', custom: true },
  { label: '单位电子邮箱', model: 'unit_email', custom: true },
  { label: '行业领域(2)', model: 'fields', type: 'selectMany', options: { placeholder: '请选择(多选，不超过2个)' } },
  { label: '技术需求方向', model: 'direction', custom: true },
  { label: '上一年度财务审计报告', model: 'audit_report', custom: true },
  { label: '上一年度R&D投入专项', model: 'special_report', custom: true },
  { label: '其他证明资料', model: 'prove_file', custom: true },
]);
let limit: Ref<number> = ref(1);
let url: Ref<string> = ref('/files/jcyjdt/unit/upload');
// 用户信息
let user: Ref<{ _id: string; name: string; unit_name: string; account: string; unit_address: string; email: string }> = ref({
  _id: '',
  name: '',
  unit_name: '',
  account: '',
  unit_address: '',
  email: '',
});
// 表单
let form: Ref<{ is_studio: string; prove: Array<[]>; direction: Array<[]> }> = ref({ is_studio: '', prove: [], direction: [] });
let uform: Ref<{
  _id: string;
  card: Array<any>;
  unit_phone: { phone: string; is_show: string };
  unit_email: { email: string; is_show: string };
  fields: Array<any>;
  direction: Array<any>;
  audit_report: Array<any>;
  special_report: Array<any>;
  prove_file: Array<any>;
  company: string;
  unit_id: string;
  unit_contact: string;
  address: string;
}> = ref({
  _id: '',
  card: [],
  unit_phone: { phone: '', is_show: '' },
  unit_email: { email: '', is_show: '' },
  company: '',
  unit_id: '',
  unit_contact: '',
  address: '',
  fields: [],
  direction: [],
  audit_report: [],
  special_report: [],
  prove_file: [],
});
// 行业领域
let fieldList: Ref<any[]> = ref([]);
// 是否显示
let isshowList: Ref<any[]> = ref([]);
// 工作室
let studioList: Ref<any[]> = ref([]);
// 状态
let statusList: Ref<any[]> = ref([]);
onMounted(async () => {
  user.value = store.state.user as { _id: string; name: string; unit_name: string; account: string; unit_address: string; email: string };
  await searchOther();
  await searchBasic();
  await search();
});
// 基本信息查询
const searchBasic = async () => {
  let res: IQueryResult = await unit.fetch(user.value._id);
  if (res.errcode == 0) {
    if (res.data) {
      form.value = res.data as { is_studio: ''; prove: []; direction: [] };
    }
  }
};
// 查询
const search = async () => {
  // 查询已申请数据状态
  let res: IQueryResult = await unitStudioApply.query({ unit_id: user.value._id });
  if (res.errcode == 0) {
    if (res.total > 0) {
      uform.value = res.data[0] as {
        _id: '';
        card: [];
        unit_phone: { phone: ''; is_show: '' };
        unit_email: { email: ''; is_show: '' };
        company: '';
        unit_id: '';
        unit_contact: '';
        address: '';
        fields: [];
        direction: [];
        audit_report: [];
        special_report: [];
        prove_file: [];
      };
    } else {
      if (user && user.value._id) {
        uform.value.unit_id = user.value._id;
        uform.value.company = user.value.unit_name || '';
        uform.value.address = user.value.unit_address || '';
        uform.value.unit_contact = user.value.name || '';
        uform.value.unit_email = { email: user.value.email || '', is_show: '' };
      }
    }
  }
};
// 改变基础信息关联
const changeForm = (val: { name: string; phone: string; email: string; unit_name: string; unit_address: string }) => {
  uform.value.unit_contact = val.name;
  uform.value.unit_phone.phone = val.phone;
  uform.value.unit_email.email = val.email;
  uform.value.company = val.unit_name;
  uform.value.address = val.unit_address;
};
// 研究方向添加
const addDriection = () => {
  let direction: any = form.value.direction;
  if (direction.length >= 5) {
    ElMessage({ message: `研究方向最多添加五个`, type: 'error' });
  } else {
    direction.push({ id: moment().valueOf(), name: '' });
  }
  form.value.direction = direction;
};
// 研究方向删除
const delDriection = (e: { id: '' }) => {
  let direction = form.value.direction.filter((i: any) => i.id != e.id);
  form.value.direction = direction;
};
// 依托单位添加
const utoSave = async (data: any) => {
  let res: IQueryResult;
  if (data.status == '2') data.status = '0';
  if (data._id) res = await unitStudioApply.update(data);
  else {
    res = await unitStudioApply.update(data);
    // 入住科学工作室 修改unit表中的is_studio
    updateBasic();
  }
  if (res.errcode == 0) {
    ElMessage({ message: `维护信息成功`, type: 'success' });
    search();
  }
};
// 修改基础信息
const updateBasic = async () => {
  let res: IQueryResult = await unit.update({ _id: user.value._id, is_studio: 'Y', account: user.value.account });
  console.log(res);
};
// 监听数据
const dataChange = (model: string, value: Array<[]>) => {
  if (model == 'fields') {
    if (value.length > 2) {
      ElMessage({ message: `数据过多，请重新选择`, type: 'error' });
    }
  }
};
// 基础信息上传
const onChange = (e: { model: string; value: Array<[]> }) => {
  const { model, value } = e;
  form.value[model] = value;
};
// 依托单位上传
const uonChange = (e: { model: string; value: Array<[]> }) => {
  const { model, value } = e;
  uform.value[model] = value;
};
// 添加
const toSave = async (data: any) => {
  let res: IQueryResult = await unit.update(data);
  if (res.errcode == 0) {
    // ElMessage({ type: 'success', message: '维护信息成功' });
    // 同步修改依托单位信息
    let form = {
      _id: uform.value._id,
      unit_contact: data.name,
      unit_phone: { phone: data.phone },
      unit_email: { email: data.email },
      company: data.unit_name,
      address: data.unit_address,
    };
    await utoSave(form);
    await search();
  } else ElMessage({ type: 'warning', message: `${res.errmsg}` });
};
// 查询其他信息
const searchOther = async () => {
  let res: IQueryResult;
  //是否公开
  res = await sysdictdata.query({ dict_type: 's_is_show' });
  if (res.errcode == '0') isshowList.value = res.data as [];
  // 领域
  res = await sysdictdata.query({ dict_type: 'studio_field' });
  if (res.errcode == '0') fieldList.value = res.data as [];
  // 是否入住科学家工作室
  res = await sysdictdata.query({ dict_type: 'sys_yes_no' });
  if (res.errcode == '0') studioList.value = res.data as [];
  // 审核状态
  res = await sysdictdata.query({ dict_type: 'studio_status' });
  if (res.errcode == '0') statusList.value = res.data as [];
};
watch(
  form,
  (newVal: any) => {
    if (newVal && newVal._id) {
      changeForm(newVal);
    }
  },
  {
    deep: true,
  }
);
</script>
<style lang="scss" scoped>
.main {
  .one {
    .one_1 {
      font-size: 22px;
      margin: 10px 0;
    }
  }
  .two {
    .two_1 {
      font-size: 22px;
      margin: 10px 0;
    }
  }
}
</style>
