<template>
  <div v-if="customer && customer._id" v-loading="loading" class="bg-white">
    <div class="bg-[#ecf4ff] bg-opacity-30 px-15px py-5px">
      <div class="flex justify-between flex-wrap w-full">
        <div class="mr-10px">
          <div class="flex items-center">
            <div class="text-16px font-semibold leading-30px">{{ customer.name }}</div>
            <div class="ml-10px text-14px leading-30px">{{ customer.sex }} {{ customer.sex && age ? " | " : "" }} {{ age }}</div>
            <div v-if="birthdayStr" :title="birthdayStr">
              <svg-icon class="ml-10px flex-shrink-0" title="" name="cake" size="24"></svg-icon>
            </div>
          </div>
          <div v-if="customer.tagIds && customer.tagIds.length" class="flex flex-nowrap items-center mt-4px">
            <customer-tag v-for="tagId in customer.tagIds.slice(0, 6)" :key="tagId" :tag-id="tagId" class="mb-0" />
            <el-popover :disabled="customer.tagIds.length <= 6" placement="top-start" :width="300" trigger="click">
              <template #reference>
                <span v-if="customer.tagIds.length > 6" class="ml-10px text-gray-400 cursor-pointer">...</span>
              </template>
              <div class="flex flex-wrap">
                <customer-tag v-for="tagId in customer.tagIds" :key="`${tagId}_popover`" :tag-id="tagId" class="flex-shrink-0" />
              </div>
            </el-popover>
          </div>
        </div>
        <div class="flex-shrink-0 flex items-center text-blue-500 text-14px">
          <span class="mr-5px cursor-pointer" @click="handleDetail">详情</span>
          <el-icon class="cursor-pointer" @click="handleDetail">
            <DArrowRight />
          </el-icon>
        </div>
      </div>
      <el-row class="mt-5px text-14px">
        <el-col :lg="6" :md="8" :span="12">
          <div class="flex items-center pr-10px">
            <div class="flex-shrink-0 leading-26px text-gray-500">备注：</div>
            <div class="truncate text-[#FC8352]" :title="customer.notes || ''">{{ customer.notes || "--" }}</div>
          </div>
        </el-col>
        <el-col :lg="6" :md="8" :span="12">
          <div class="flex items-center pr-10px">
            <div class="flex-shrink-0 leading-26px text-gray-500">当前团队责任人：</div>
            <div class="truncate">
              <ww-user v-if="person && person.corpUserId" :openid="person.corpUserId"></ww-user>
              <span v-else>--</span>
            </div>
          </div>
        </el-col>
        <el-col :lg="6" :md="8" :span="12">
          <div class="flex items-center pr-10px">
            <div class="flex-shrink-0 leading-26px text-gray-500">建档时间：</div>
            <div class="truncate flex-shrink-0 min-w-0">
              {{ customer.createTime ? dayjs(customer.createTime).format("YYYY-MM-DD HH:mm") : "--" }}
            </div>
          </div>
        </el-col>
        <el-col :lg="6" :md="8" :span="12">
          <div class="flex items-center pr-10px">
            <div class="flex-shrink-0 leading-26px text-gray-500">最近服务：</div>
            <div class="truncate flex-shrink-0 min-w-0">
              {{ customer.serviceTime ? dayjs(customer.serviceTime).format("YYYY-MM-DD HH:mm") : "--" }}
            </div>
          </div>
        </el-col>
        <el-col :lg="6" :md="8" :span="12">
          <div class="flex items-center pr-10px">
            <div class="flex-shrink-0 leading-26px text-gray-500">共享团队：</div>
            <div v-if="serviceTeams.length" class="flex items-center">
              <el-popover placement="bottom-end" :width="350" trigger="click">
                <template #reference>
                  <div class="truncate mr-4px cursor-pointer hover:text-blue-500">{{ serviceTeams.length }}个团队服务中</div>
                </template>
                <el-scrollbar wrap-style="max-height:40vh">
                  <div v-for="i in serviceTeams" :key="i.teamId" class="py-10px flex border-b border-gray-100">
                    <div class="w-160px flex-shrink-0 truncate" :title="i.name || ''">{{ i.name }}</div>
                    <div class="w-160px flex-shrink-0 truncate">
                      <span class="mx-5px">|</span>
                      责任人：
                      <ww-user v-if="i.corpUserId" :openid="i.corpUserId"></ww-user>
                    </div>
                  </div>
                </el-scrollbar>
              </el-popover>
            </div>
          </div>
        </el-col>
        <el-col :lg="6" :md="8" :span="12">
          <div class="flex items-center pr-10px">
            <div class="flex-shrink-0 leading-26px text-gray-500">添加人：</div>
            <div>
              <el-popover placement="bottom-end" :width="420" trigger="click">
                <template #reference>
                  <el-text type="primary cursor-pointer">{{ serviceTimes.length }}人</el-text>
                </template>
                <el-scrollbar wrap-style="max-height:40vh">
                  <div v-for="i in serviceTimes" :key="i.id" class="py-8px flex items-center border-b border-gray-100">
                    <svg-icon class="mr-4px flex-shrink-0" name="wx-work" size="24"></svg-icon>
                    <div class="flex-shrink-0">
                      <ww-user v-if="i.id" :openid="i.id"></ww-user>
                    </div>
                    <div class="flex-shrink-0" v-if="i.executionTime">
                      <span class="mx-10px">|</span>
                      最近服务时间：{{ i.executionTime }}
                    </div>
                  </div>
                </el-scrollbar>
              </el-popover>
            </div>
          </div>
        </el-col>
        <el-col :lg="6" :md="8" :span="12">
          <div class="flex items-center pr-10px">
            <div class="flex-shrink-0 leading-26px text-gray-500">最近到院：</div>
            <div class="truncate">{{ lastVisitTime || "--" }}</div>
          </div>
        </el-col>
        <el-col :lg="6" :md="8" :span="12">
          <div class="flex items-center pr-10px">
            <div class="flex-shrink-0 leading-26px text-gray-500">累计消费：</div>
            <div class="truncate">--</div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script setup>
import { computed, ref, toRefs, watch } from "vue";
import { storeToRefs } from "pinia";
import dayjs from "dayjs";
import { getCustomerInfoById } from "@/api/member";
import { getLastServiceTime } from "@/api/todo";
import { teamStore } from "@/store/team";
import wxContact from "@/store/wxContact";

import customerTag from "@/components/customer-tag/customer-tag";
import WwUser from "@/components/ww-user/index.vue";

const emits = defineEmits(["showCustomerDetail"]);
const props = defineProps({
  customer: { type: Object, default: () => ({}) },
  customerId: { type: String, default: "" },
  request: { type: Boolean, default: false },
});
const customerInfo = ref({});
const customer = computed(() => (props.request ? customerInfo.value : props.customer));

const loading = ref(false);
const serviceTimes = ref([]);
const contactStore = wxContact();
const { contactFollowUsers } = storeToRefs(contactStore);
const { allTeams } = storeToRefs(teamStore());

const birthdayStr = computed(() => {
  if (customer.value.birthdayStamp && dayjs(customer.value.birthdayStamp).isValid()) {
    return dayjs(customer.value.birthdayStamp).format("YYYY年MM月DD日");
  }
  if (customer.value.birthday && dayjs(customer.value.birthday).isValid()) {
    return dayjs(customer.value.birthday).format("YYYY年MM月DD日");
  }
  return "";
});
const followUser = computed(() => contactFollowUsers.value[customer.value.externalUserId] || []);

const lastVisitTime = computed(() => (customer.value && customer.value.lastVisitTime ? dayjs(customer.value.lastVisitTime).format("YYYY-MM-DD") : "--"));
const personResponsibles = computed(() => (customer.value && Array.isArray(customer.value.personResponsibles) ? customer.value.personResponsibles : []));
const serviceTeams = computed(() => {
  const teamIds = customer.value.teamId ? (typeof customer.value.teamId === "string" ? [customer.value.teamId] : customer.value.teamId) : [];
  return teamIds.map((i) => {
    const item = personResponsibles.value.find((j) => j.teamId === i);
    const team = allTeams.value.find((j) => j.teamId === i);
    return { name: team ? team.name : "", teamId: i, corpUserId: item ? item.corpUserId : "" };
  });
});
const serviceTimePayload = computed(() => [customer.value._id, [...followUser.value]]);

function handleDetail() {
  emits("showCustomerDetail", customer.value);
}

async function getCustomerInfo() {
  loading.value = true;
  const { success, data, message } = await getCustomerInfoById(sessionStorage.getItem("userId"), { _id: props.customerId });
  customerInfo.value = data.data && data.data[0] ? data.data[0] : {};
  loading.value = false;
}

async function getServiceTimes() {
  const res = await getLastServiceTime(customer.value._id, followUser.value);
  const list = res && Array.isArray(res.data.data) ? res.data.data : [];
  serviceTimes.value = followUser.value
    ? followUser.value.map((i) => {
        const item = list.find((item) => item.id === i);
        const executionTime = item && item.executionTime ? dayjs(item.executionTime).format("YYYY-MM-DD") : "";
        return { id: i, executionTime };
      })
    : [];
}

watch(
  () => props.customerId,
  (n) => {
    if (n && props.request) {
      if (customerInfo.value._id !== n) {
        getCustomerInfo(n);
      }
    } else {
      customerInfo.value = {};
    }
  },
  { immediate: true }
);

watch(
  serviceTimePayload,
  (n) => {
    if (n[0] && n[1].length) {
      getServiceTimes();
    } else {
      serviceTimes.value = [];
    }
  },
  { immediate: true }
);
</script>
<style lang="scss" scoped></style>
