<script lang="ts" setup>
// @ts-ignore

import { computed, onMounted, ref } from 'vue';

import {
  ElCard,
  ElDescriptions,
  ElDescriptionsItem,
  ElTag,
} from 'element-plus';

// @ts-ignore
import { useVbenVxeGrid } from '#/adapter/vxe-table';

// @ts-ignore

// 定义组件的Props接口
interface GroupLogProps {
  taskDetail: any;
}

// 接收父组件传递的任务详情数据
const props = defineProps<GroupLogProps>();

// 计算属性，获取班组日志数据
const groupLogData = computed(() => {
  return props.taskDetail || {};
});

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

// 格式化百分比
const formatPercentage = (value: number | string) => {
  if (value === undefined || value === null || value === '') return '-';
  return `${value}%`;
};

// 获取班次名称
const getShiftName = (shiftId: number | string, taskDetail: any) => {
  if (!shiftId || !taskDetail?.taskList?.length) return '-';
  const task = taskDetail.taskList[0];
  return task?.shiftName || '-';
};

const getMembers = (value: any) => {
  if (value === undefined || value === null || value === '') return [];
  return JSON.parse(value || '[]');
};

// 解析其它分工 JSON 字符串
const getOtherDivision = (value: any) => {
  if (value === undefined || value === null || value === '') return [];
  return JSON.parse(value || '[]');
};

// 解析评价 JSON 字符串
const getEvaluationComments = (value: any) => {
  if (value === undefined || value === null || value === '') return [];
  try {
    return JSON.parse(value || '[]');
  } catch {
    return [];
  }
};

// 表格列配置
const tableColumns: any = [
  {
    field: 'employeeName',
    title: '员工姓名',
    width: 100,
    fixed: 'left',
  },
];

// 初始化表格配置
const gridOptions: any = {
  size: 'medium',
  toolbarConfig: {
    custom: false,
    refresh: false,
    zoom: false,
  },
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async () => {
        return {
          items: tableDatas.value,
        };
      },
    },
  },
  columns: tableColumns,
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
};

const tableDatas = ref<any>([]);
// 使用BasicTable组件
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  gridOptions,
});

const init = () => {
  const res: any = props.taskDetail.evaluations;
  gridOptions.columns = [];
  gridOptions.columns = tableColumns;
  if (res?.length) {
    res.forEach((item: any) => {
      // evaluationItems.value.push(item.dictCode);
      // @ts-ignore
      gridOptions.columns.push({
        field: `id_${item.id}`,
        title: `${item.itemName}（${item.standardScore}）`,
        // cellType: 'number',
        width: 150,
      });
    });
  }

  // @ts-ignore
  gridOptions.columns.push({
    field: 'evaluationWords',
    title: `评语`,
    // cellType: 'number',
    width: 200,
  });
  basicTableApi.setGridOptions(gridOptions);

  const tableData: any = [];
  props.taskDetail?.evaluationRecords.forEach((item: any) => {
    const index = tableData.findIndex(
      (item2: any) => item2.employeeId === item.employeeId,
    );

    if (index === -1) {
      tableData.push({
        employeeId: item.employeeId,
        employeeName: item.employeeIdName,
        evaluationWords: item.evaluationWords,
        [`id_${item.itemId}`]: item.totalScore,
      });
    } else {
      tableData[index] = {
        ...tableData[index],
        [`id_${item.itemId}`]: item.totalScore,
      };
    }
  });
  tableDatas.value = tableData;
  basicTableApi.query();
};

// 组件挂载时，设置表格数据
onMounted(() => {
  init();
});
</script>

<template>
  <ElCard>
    <template #header>
      <div class="flex items-center gap-4">
        <div style="width: 4px; height: 12px; background-color: #215acd"></div>
        <span
          class="text-lg font-bold text-gray-800"
          style="font-size: 14px; font-weight: 600"
        >
          班组日志
        </span>
      </div>
    </template>

    <div class="task-info">
      <!-- 基本信息 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">基本信息</span>
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem label="上班日期:">
          {{ formatDateTime(groupLogData.shiftDate) }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="上班班次:">
          {{ getShiftName(groupLogData.shiftId, props.taskDetail) }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="当班负责人:">
          {{ groupLogData.shiftLeaderName || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="天气:">
          {{ groupLogData.weatherName || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="促品完成率:" :span="4">
          {{ formatPercentage(groupLogData.promotionCompletionRate) }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="班员:" :span="4">
          <div v-if="getMembers(groupLogData.shiftMembers).length > 0">
            <ElTag
              v-for="(item, index) in getMembers(groupLogData.shiftMembers)"
              :key="index"
              size="small"
              class="mb-1 mr-1"
            >
              {{ item.name }}
            </ElTag>
          </div>
          <span v-else>-</span>
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 班前会 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">班前会</span>
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem label="列队检查:" :span="4">
          {{ groupLogData.lineupCheck || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="前期工作回顾:" :span="4">
          {{ groupLogData.previousWorkReview || '-' }}
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 工作分工 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">工作分工</span>
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem label="贵重物品盘点:" :span="4">
          {{ groupLogData.valuableInventory || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="设备物料盘点:" :span="4">
          {{ groupLogData.equipmentInventory || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="赠品盘点:" :span="4">
          {{ groupLogData.giftInventory || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="车辆指引:" :span="4">
          {{ groupLogData.vehicleGuidance || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="油机清洁:" :span="4">
          {{ groupLogData.fuelMachineCleaning || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="前庭清洁:" :span="4">
          {{ groupLogData.forecourtCleaning || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="卫生间清洁:" :span="4">
          {{ groupLogData.toiletCleaning || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="便利店清洁:" :span="4">
          {{ groupLogData.storeCleaning || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="垃圾处理:" :span="4">
          {{ groupLogData.garbageDisposal || '-' }}
        </ElDescriptionsItem>
        <ElDescriptionsItem label="其它分工:" :span="4">
          <div v-if="getOtherDivision(groupLogData.otherDivision).length > 0">
            <ElTag
              v-for="(item, index) in getOtherDivision(
                groupLogData.otherDivision,
              )"
              :key="index"
              size="small"
              class="mb-1 mr-1"
            >
              {{ item.content }} ({{ item.name }})
            </ElTag>
          </div>
          <span v-else>-</span>
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 重点强化 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">重点强化</span>
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem label="重点强化:" :span="4">
          {{ groupLogData.keyEnhancement || '-' }}
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 营造氛围 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">营造氛围</span>
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem label="营造氛围:" :span="4">
          {{ groupLogData.atmosphereBuilding || '-' }}
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 班组总结 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">班组总结</span>
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem label="班组总结:" :span="4">
          {{ groupLogData.teamSummary || '-' }}
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 班前会拍照 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">班前会拍照</span>
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem
          v-if="
            groupLogData.meetingPhotosUrl &&
            groupLogData.meetingPhotosUrl.length > 0
          "
          label="班前会拍照现场:"
          :span="4"
        >
          <div class="task-images">
            <ElImage
              v-for="(image, index) in groupLogData.meetingPhotosUrl"
              :key="index"
              :src="image"
              :preview-src-list="groupLogData.meetingPhotosUrl"
              :initial-index="index"
              fit="cover"
              alt="班前会照片"
              class="task-image"
            />
          </div>
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 班后待跟进事项 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">班后待跟进事项</span>
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem label="班后待跟进事项:" :span="4">
          {{ groupLogData.followUpItems || '-' }}
        </ElDescriptionsItem>
      </ElDescriptions>

      <!-- 评价 -->
      <div class="section-title">
        <div class="section-bar"></div>
        <span class="section-text">评价</span>
      </div>
      <div class="mb-6">
        <BasicTable table-title="" class="w-full" />
      </div>
      <ElDescriptions :column="4" class="mb-6">
        <ElDescriptionsItem label="其它信息:" :span="4">
          {{ groupLogData.otherInfo || '-' }}
        </ElDescriptionsItem>
      </ElDescriptions>
    </div>
  </ElCard>
</template>

<style scoped lang="scss">
.task-info {
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 20px 0 12px 0;

    .section-bar {
      width: 4px;
      height: 12px;
      background-color: #215acd;
    }

    .section-text {
      font-size: 14px;
      font-weight: 600;
      color: var(--text-color-primary);
    }
  }

  :deep(.el-descriptions) {
    margin-bottom: 0 !important;
  }

  :deep(.el-descriptions__label) {
    font-size: 14px;
    font-weight: 400;
    color: var(--text-color-secondary);
  }

  :deep(.el-descriptions__content) {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-color-primary);
  }

  :deep(.el-descriptions__table) {
    background: transparent !important;
  }
}

.task-images {
  display: flex;
  gap: 12px;
  margin-top: 4px;
  flex-wrap: wrap;

  .task-image {
    width: 80px;
    height: 80px;
    cursor: pointer;
    object-fit: cover;
    border-radius: 4px;
    transition: transform 0.2s;
  }
}
</style>
