<template>
  <a-page-header
    :title="title"
    :style="{ padding: screenWidth > 480 ? '16px 24px' : '0' }"
    @back="() => $router.go(-1)"
  >
    <a-spin :spinning="spinning">
      <a-card
        :bordered="false"
        :body-style="{ paddingTop: '5px' }"
        v-if="isShow"
      >
        <a-tabs v-model:active-key="active" @change="onChange">
          <a-tab-pane tab="基本信息" key="base">
            <CompanyInfo
              :data="form"
              :logo="logo"
              :company-qrcode="companyQrcode"
              @done="reload"
            />
          </a-tab-pane>
          <a-tab-pane
            tab="成员管理"
            key="users"
            v-if="hasRole('superAdmin') || hasRole('admin')"
          >
            <CompanyUsers :company-id="companyId" :data="form" @done="reload" />
          </a-tab-pane>
          <a-tab-pane tab="客户资料" key="param">
            <CompanyFieldForm
              :company-id="companyId"
              :data="form"
              @done="reload"
            />
          </a-tab-pane>
          <a-tab-pane tab="企业附件" key="annex">
            <CompanyAnnex :company-id="companyId" :data="form" @done="reload" />
          </a-tab-pane>
        </a-tabs>
      </a-card>
      <a-card v-else :bordered="false">
        <div style="max-width: 960px; margin: 0 auto">
          <a-result
            status="error"
            title="无查看权限"
            sub-title="请先添加为企业成员"
          >
            <template #extra>
              <a-space size="middle">
                <a-button type="primary" @click="openUrl('/oa/company/index')"
                  >返回</a-button
                >
              </a-space>
            </template>
          </a-result>
        </div>
      </a-card>
    </a-spin>
  </a-page-header>
</template>

<script lang="ts" setup>
  import { ref, unref, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import CompanyInfo from './components/company-info.vue';
  import CompanyUsers from './components/company-users.vue';
  import CompanyAnnex from './components/company-annex.vue';
  import CompanyFieldForm from './components/company-field.vue';
  import { pageCompany } from '@/api/oa/company';
  import useFormData from '@/utils/use-form-data';
  import { Company } from '@/api/oa/company/model';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { hasRole } from '@/utils/permission';
  import { setPageTabTitle } from '@/utils/page-tab-util';
  import { openUrl } from '@/utils/common';
  import { pageCompanyUser } from '@/api/oa/company/user';
  import { pageCompanyField } from '@/api/oa/company/field';
  import { CompanyField } from '@/api/oa/company/field/model';

  const { currentRoute } = useRouter();
  // 当前选项卡
  const active = ref('base');
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { screenWidth } = storeToRefs(themeStore);
  const title = ref('企业名称');
  const spinning = ref(true);
  const isShow = ref(true);
  const logo = ref<any[]>([]);
  const companyId = ref<number>(0);
  const companyQrcode = ref<any[]>([]);
  const images = ref<ItemType[]>([]);
  const companyField = ref<CompanyField[]>();

  // 应用信息
  const { form, assignFields, resetFields } = useFormData<Company>({
    companyId: undefined,
    companyName: '',
    shortName: '',
    companyCode: '',
    companyLogo: '',
    companyType: undefined,
    industryParent: '',
    industryChild: '',
    businessEntity: '',
    province: '',
    city: '',
    region: '',
    address: '',
    phone: '',
    tel: '',
    email: '',
    domain: '',
    serverUrl: undefined,
    clicks: undefined,
    version: undefined,
    sortNumber: undefined,
    comments: '',
    tenantName: '',
    tenantCode: '',
    tenantId: undefined,
    createTime: '',
    status: undefined,
    nickname: '',
    fields: [],
    userList: []
  });

  const onChange = () => {
    reload();
  };

  /**
   * 加载数据
   */
  const reload = () => {
    resetFields();
    logo.value = [];
    companyQrcode.value = [];
    images.value = [];
    // companyField.value = [];
    // 加载企业详情
    pageCompany({ companyId: companyId.value })
      .then((data) => {
        if (data?.list) {
          const company = data.list[0];
          assignFields(company);
          if (company.companyName) {
            title.value = company.companyName;
            // 修改页签标题
            setPageTabTitle(company.companyName);
          }
          if (company.companyLogo) {
            logo.value.push({
              uid: company.companyId,
              url: company.companyLogo,
              status: 'done'
            });
          }
        }
        isShow.value = true;
        spinning.value = false;
        // 加载企业资料
        pageCompanyField({ companyId: companyId.value, limit: 50 }).then(
          (res) => {
            companyField.value = res?.list;
            form.fields = res?.list;
          }
        );
        // 加载项目成员
        pageCompanyUser({ companyId: companyId.value }).then((res) => {
          if (res?.list) {
            form.userList = res.list;
          }
        });
      })
      .catch((err) => {
        isShow.value = false;
        spinning.value = false;
      });
  };

  watch(
    currentRoute,
    (route) => {
      const { params } = unref(route);
      const { id } = params;
      if (id) {
        companyId.value = Number(id);
      }
      reload();
    },
    { immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'CompanyDetail'
  };
</script>
