<template>
  <full-page v-if="!visible" :customScroll="empty">
    <view v-if="formItems.length === 0" class="flex items-center justify-center h-full">
      <empty-data />
    </view>
    <view v-else class="p-15">
      <view class="bg-white rounded shadow-lg">
        <form-template ref="tempRef" :disableTitles="disableTitles" :items="formItems" :form="formData"
          @change="change($event)" />
      </view>
    </view>
    <template #footer>
      <button-footer :showCancel="customerId ? true : false" cancelText="删除" :confirmText="healthTypes.length?'下一步':'保存'" @cancel="unBindArchive()"
        @confirm="confirm()" />
    </template>
  </full-page>
  <bind-popup :customers="customers" :corpName="corpName" :visible="visible" @close="visible = false"
    @confirm="bindArchive($event)" />
  <verify-popup :visible="verifyVisible" @close="verifyVisible = false" />
</template>
<script setup>
import { computed, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { onLoad } from "@dcloudio/uni-app";
import dayjs from 'dayjs';
import useGuard from '@/hooks/useGuard';
import useAccount from '@/store/account';
import api from '@/utils/api';
import { toast, confirm as uniConfirm } from '@/utils/widget';
import validate from '@/utils/validate';
import { set } from "@/utils/cache";

import ButtonFooter from '@/components/button-footer.vue';
import EmptyData from '@/components/empty-data.vue';
import FullPage from '@/components/full-page.vue';
import bindPopup from './bind-popup.vue';
import verifyPopup from './verify-popup.vue';
import formTemplate from '@/components/form-template/index.vue';

const empty = ref(false)
const { useLoad } = useGuard();
const { account, externalUserId } = storeToRefs(useAccount());
const { getExternalUserId } = useAccount()
const corpId = ref('');
const corpName = ref('');
const corpUserId = ref('');
const referenceCustomerId = ref('');
const customer = ref({});
const customerId = ref('');
const customers = ref([]);
const disableTitles = ref(['mobile']);
const form = ref({});
const formItems = ref([]);
const loading = ref(false);
const teamId = ref('');
const tempRef = ref(null);
const verifyVisible = ref(false);
const visible = ref(false);
const referenceCustomer = ref(null)
const healthTypes = ref([]);

const formData = computed(() => {
  return { ...customer.value, ...form.value, mobile: account.value?.mobile }
});

function change({ title, value }) {
  if (title) {
    form.value[title] = value;
  }
  if (title == 'idCard') {
    const [isIdCard, birthday, gender] = validate.isChinaId(value);
    if (isIdCard) {
      form.value.birthday = birthday;
      form.value.sex = gender == 'MALE' ? '男' : '女';
      const age = dayjs().diff(birthday, 'year');
      form.value.age = Math.max(1, age);
    }
  } else if (title === 'birthday' && formItems.value.some(i => i.title === 'age') && value && dayjs(value).valueOf()) {
    const age = dayjs().diff(value, 'year');
    form.value.age = Math.max(1, age);
  }

}

function confirm() {
  if (!tempRef.value.verify()) return;
  if (customerId.value) {
    updateArchive();
  } else {
    addArchive();
  }
}

/**
 * 产品要求, 建档页面：与联系人关系：默认选中“本人”，证件类型：默认选中“身份证”
 */
function preProcessFrom() {
  const relationItem = formItems.value.find(item => item.title === 'relationship');
  const range = relationItem && Array.isArray(relationItem.range) ? relationItem.range : [];
  if (range.includes('本人')) {
    form.value.relationship = '本人';
  }
  const cardTypeItem = formItems.value.find(item => item.title === 'cardType');
  const cardTypeRange = cardTypeItem && Array.isArray(cardTypeItem.range) ? relationItem.range : [];
  if (cardTypeRange.includes('身份证')) {
    form.value.cardType = '身份证';
  }
}

/**
 * 产品要求, 编辑的情况下 姓名、身份证号、性别、年龄、出生年月
 * 建档成功或者绑定档案成功后，姓名、身份证号、性别、年龄、出生年月。如果有内容的都不允许修改。没有内容的则允许编辑。
 */
function setDisabledTitles(data) {
  const list = ['mobile'];
  if (data.name) {
    list.push('name');
  }
  if (data.idCard) {
    list.push('idCard');
  }
  if (data.sex) {
    list.push('sex');
  }
  if (data.age) {
    list.push('age');
  }
  if (data.birthday) {
    list.push('birthday');
  }
  disableTitles.value = list;
}

async function addArchive() {
  if (loading.value) return;
  loading.value = true;
  const params = {
    ...form.value,
    addMethod: 'customerManual',
    teamId: teamId.value,
    corpId: corpId.value,
    mobile: account.value.mobile,
    miniAppId: account.value.openid,
    externalUserId: externalUserId.value,
    realUnionid: account.value.unionid || '',
  }
  if (externalUserId.value) {
    const corpUserId = await getResponsiblePerson();
    if (corpUserId) {
      params.personResponsibles = [{ corpUserId, teamId: teamId.value }]
    }
  }
  if (referenceCustomerId.value && !referenceCustomer.value) {
    await getReferenceCustomer();
  }
  if (referenceCustomer.value) {
    params.referenceCustomerId = referenceCustomer.value._id;
    params.referenceUserId = '';
    params.reference = referenceCustomer.value.name;
    params.referenceType = '客户';
    params.customerSource = ['客户推荐']
  }
  loading.value = false;
  const res = await api('addCustomer', { params });
  set('home-invite-team-info', { teamId: teamId.value })
  if (res && res.success) {
    uni.$emit('reloadTeamCustomers')
    // getTeam(corpId.value, teamId.value, res.data.id);
    if (healthTypes.value.length) {
      const nextType = healthTypes.value[0];
      const nextTypes = healthTypes.value.slice(1);
      const url = `/pages/health/record?type=${nextType}&teamId=${teamId.value}&corpId=${corpId.value}&customerId=${res.data.id}&nextTypes=${nextTypes.join(',')}&source=afterArchive`
      uni.redirectTo({ url });
    } else {
      uni.redirectTo({
        url: `/pages/archive/archive-result?corpId=${corpId.value}&teamId=${teamId.value}&customerId=${res.data.id}`
      })
    }
  } else {
    toast(res?.message || '新增档案失败');
  }
}

async function getResponsiblePerson() {
  const res = await api('getResponsiblePerson', { corpId: corpId.value, teamId: teamId.value, externalUserId: externalUserId.value, corpUserId: corpUserId.value });
  return res && res.data ? res.data : ''
}

async function bindArchive(customerId) {
  let responsiblePerson = '';
  if (externalUserId.value) {
    const corpUserId = await getResponsiblePerson();
    responsiblePerson = corpUserId || '';
  }
  const res = await api('bindMiniAppArchive', { id: customerId, corpId: corpId.value, teamId: teamId.value, miniAppId: account.value.openid, externalUserId: externalUserId.value, responsiblePerson });
  if (res && res.success) {
    await toast('绑定成功');
    uni.$emit('reloadTeamCustomers')
    uni.switchTab({
      url: '/pages/home/home'
    })
    // uni.reLaunch({ url: `/pages/home/home?corpId=${corpId.value}&teamId=${teamId.value}` })
  } else {
    toast(res?.message || '绑定失败');
  }
  // customerArchive.value = customers.value.find(item => item.customerId === customerId);
  // verifyVisible.value = true;
}

async function init() {
  if (customerId.value) {
    await getCustomer();
  } else {
    const res = await getArchives();
    if (res.length > 0) {
      visible.value = true;
    }
    getExternalUserId(corpId.value);
    getTeam(corpId.value, teamId.value)
  }
  await getBaseForm();
  if (!customerId.value) {
    preProcessFrom()
  }

}

async function getArchives() {
  const res = await api('getUnbindMiniAppCustomers', { corpId: corpId.value, mobile: account.value?.mobile || '' });
  customers.value = res && Array.isArray(res.data) ? res.data : [];
  corpName.value = res && res.corpName ? res.corpName : '';
  return customers.value
}

async function getBaseForm() {
  const res = await api('getTeamBaseInfo', { corpId: corpId.value, teamId: teamId.value });
  if (res && res.success) {
    formItems.value = Array.isArray(res.data) ? res.data : [];
    const mobileIndex = formItems.value.findIndex(item => item.title === 'mobile');
    if (mobileIndex > -1) {
      formItems.value[mobileIndex].appendText = `(授权手机号)`;
    }

  } else {
    toast(res?.message || '查询失败');
    return Promise.reject()
  }
}

async function getCustomer() {
  const res = await api('getCustomerByCustomerId', { customerId: customerId.value });
  if (res && res.success && res.data) {
    customer.value = res.data;
    setDisabledTitles(res.data)
  } else {
    await toast(res?.message || '查询档案信息失败');
    uni.navigateBack();
    return Promise.reject()
  }
}

async function updateArchive() {
  if (Object.keys(form.value).length > 0) {
    const res = await api('updateCustomer', { id: customerId.value, params: { ...form.value } });
    if (res && res.success) {
      await toast('修改成功');
      uni.$emit('reloadTeamCustomers')
      uni.navigateBack();
    } else {
      toast(res?.message || '修改失败');
    }
  } else {
    uni.navigateBack();
  }
}

async function unBindArchive() {
  await uniConfirm('确定删除档案吗？')
  const res = await api('unbindMiniAppArchive', { id: customer.value._id, corpId: corpId.value, teamId: teamId.value, miniAppId: account.value.openid });
  if (res && res.success) {
    await toast('删除成功');
    uni.$emit('reloadTeamCustomers')
    uni.navigateBack();
  } else {
    toast(res?.message || '删除失败')
  }
}

async function getReferenceCustomer() {
  const res = await api('getRefrencePeople', { corpId: corpId.value, id: referenceCustomerId.value });
  referenceCustomer.value = res && res.data ? res.data : null;
}

async function getTeam(corpId, teamId, customerId) {
  const res = await api('getTeamData', { teamId, corpId });
  if (res && res.data) {
    const team = res.data;
    const qrcode = team && Array.isArray(team.qrcodes) ? team.qrcodes[0] : null;
    const healthTempList = qrcode && Array.isArray(qrcode.healthTempList) ? qrcode.healthTempList : [];
    healthTypes.value = healthTempList.filter(i => typeof i.templateType === 'string' && i.templateType.trim() && i.archiveRecommend === true).map(i => i.templateType);
    // if (types.length && customerId) {
    //   const nextType = types[0];
    //   const nextTypes = types.slice(1);
    //   const url = `/pages/health/record?type=${nextType}&teamId=${teamId}&corpId=${corpId}&customerId=${customerId}&nextTypes=${nextTypes.join(',')}&source=afterArchive`
    //   uni.redirectTo({ url });
    //   return
    // }
  }
  // uni.redirectTo({
  //   url: `/pages/archive/archive-result?corpId=${corpId}&teamId=${teamId}&customerId=${customerId}`
  // })
}


onLoad(options => {
  teamId.value = options.teamId;
  corpId.value = options.corpId;
  customerId.value = options.id || '';
  corpUserId.value = options.corpUserId || '';
  referenceCustomerId.value = options.referenceCustomerId || '';
  if (referenceCustomerId.value) {
    getReferenceCustomer();
  }
  uni.setNavigationBarTitle({ title: customerId.value ? '编辑档案' : '新增档案' })
})

useLoad(options => {
  init();
})

</script>
<style scoped></style>