<template>
  <div class="">
    <a-table
      :columns="tableColumns"
      :data="workList"
      :scroll="{
        x: 1400
      }"
      stripe
      :pagination="false"
      :bordered="{
        cell: false,
        headerCell: true,
        wrapper: false
      }"
      :hoverable="false"
    >
      <template #date="{ record }">
        <a-tooltip content="工作流程时间线">
          <a-link
            style="color: rgb(var(--gray-10))"
            @click="showWorkTimelineDrawer(record.id)"
          >
            <template #icon>
              <icon-history
                :size="20"
                style="color: rgb(var(--primary-6)); margin-top: 4px"
              />
            </template>
            {{ record.started_at }}</a-link
          >
        </a-tooltip>
      </template>

      <template #status="{ record }">
        <a-tag :color="curStatus(record.status)?.color">{{
          record.process_type === 1
            ? curStatus(record.status)?.label
            : curStatus(record.status)?.subLable ||
              curStatus(record.status)?.label
        }}</a-tag>
      </template>

      <template #prj_name="{ record }">
        <a-link icon @click="redirectProjectDetailPage(record.prj_id)">
          {{ record.prj_name }}</a-link
        >
      </template>

      <template #type="{ record }">
        <icon-font :type="curType(record.process_type)?.font" :size="40" />
      </template>

      <template #operate="{ record }">
        <div class="operate-text-button">
          <a-button
            type="text"
            :disabled="record.status === 2 && record.process_type === 1"
            @click="processWorkInfo(record)"
            >{{ record.process_type === 1 ? '办理' : '阅读' }}</a-button
          >
          <!-- <a-divider direction="vertical" />
          <a-button type="text" @click="processWorkInfo(record)"
            >时间线</a-button
          > -->
        </div>
      </template>
    </a-table>
    <Page :page="page" @change="pageChangehandle" />

    <WorkModal ref="workModalRef"></WorkModal>

    <a-drawer
      title="工作流程时间线"
      :width="850"
      class="chain-drawer"
      :header="true"
      :hide-cancel="true"
      :visible="drawerVisible"
      popup-container="body"
      placement="left"
      unmount-on-close
      @ok="drawerVisible = false"
      @cancel="drawerVisible = false"
    >
      <div style="margin: 0 auto">
        <a-timeline mode="alternate">
          <a-timeline-item
            v-for="(item, index) in workChainList"
            :key="item.id"
            :class="
              item.id === selelctedId
                ? index % 2 == 0
                  ? 'selectedItemLeft'
                  : 'selectedItemRight'
                : ''
            "
          >
            {{ item.name }}
            <br />
            <div v-if="item.desc" style="font-size: 12px; margin: 10px 0">
              <div v-html="item.desc"></div>
            </div>
            <template #label>
              <div v-if="item.process_type === 1">
                <div style="margin: 5px 0">
                  {{ item.handler_name
                  }}<a-tag
                    :color="curStatus(item.status)?.color"
                    style="margin-left: 5px"
                    >{{
                      item.process_type === 1
                        ? curStatus(item.status)?.label
                        : curStatus(item.status)?.subLable ||
                          curStatus(item.status)?.label
                    }}</a-tag
                  >
                </div>
                {{ item.started_at }} ~ {{ item.completed_at }}
              </div>
            </template>
            <template #dot>
              <a-badge v-if="item.status === 0" status="normal" />
              <a-badge v-if="item.status === 1" status="warning" />
              <a-badge v-if="item.status === 2" status="success" />
            </template>
          </a-timeline-item>
        </a-timeline>
      </div>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { PropType, ref, watch } from 'vue'
import { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import Page from '@/components/page/index.vue'
import usePage, { IPage } from '@/components/page/index'
import { useEmitt } from '@/logics/mitt/useEmitt'
import { getWorkChain, getWorkList } from '@/api/project/work'
import { Work, WorkChain } from '@/types/work'
import { Icon } from '@arco-design/web-vue'
import { IconFontUrl, ProjectDetailTabTitleList } from '@/enums/api'
import { useRouter } from 'vue-router'
import { useWindows } from '@/hooks/useWindow'
import { useUndoneCount } from '@/hooks/useUndoneCount'
import WorkModal from '../../project-center/components/work-modal.vue'

const IconFont = Icon.addFromIconFontCn({
  src: IconFontUrl.URL
})

const { page } = usePage()
const props = defineProps({
  filterForm: {
    type: Object,
    default() {
      return {}
    }
  },
  statusList: {
    type: Array as PropType<
      { subLable?: string; label: string; value: number; color: string }[]
    >
  },
  typeList: {
    type: Array as PropType<{ label: string; value: number; font: string }[]>
  },
  tableColumns: {
    type: Array as PropType<TableColumnData[]>
  },
  status: {
    type: Number
  }
})
const router = useRouter()
const workList = ref<Work[]>([])
const workModalRef = ref<any>(null) // Modal 增删改子组件ref
const drawerVisible = ref(false)
const workChainList = ref<WorkChain[]>([])
const selelctedId = ref()
const { addWindow } = useWindows([])
// 跳转到详情页面
const redirectProjectDetailPage = (id: string) => {
  const routeData = router.resolve({
    name: 'ProjectDetail',
    params: { prjId: id }
  })
  const myWindow = window.open(routeData.href, id)
  const windowSubset = {
    close: window.close.bind(myWindow)
  }
  // 将这个新对象转换为字符串
  const windowSubsetString = JSON.stringify(windowSubset, (key, value) => {
    // 如果值是函数，转换为字符串表示的函数（例如："function() {...}"）
    if (typeof value === 'function') {
      return value.toString()
    }
    return value
  })
  addWindow({ id, value: JSON.stringify(windowSubsetString)! })
}

// 跳转到详情页面
const processWorkInfo = (work: Work) => {
  if (!work.target_type) {
    workModalRef.value?.showWorkModal(work.id)
    return
  }
  const routeData = router.resolve({
    name: ProjectDetailTabTitleList.find(item =>
      item.redirectId?.includes(work.target_type)
    )?.routerName,
    params: { prjId: work.prj_id },
    query: { ...work.params }
  })
  // // 在新窗口中打开 URL
  const myWindow = window.open(routeData.href, work.prj_id)

  const windowSubset = {
    close: window.close.bind(myWindow)
  }
  // 将这个新对象转换为字符串
  const windowSubsetString = JSON.stringify(windowSubset, (key, value) => {
    // 如果值是函数，转换为字符串表示的函数（例如："function() {...}"）
    if (typeof value === 'function') {
      return value.toString()
    }
    return value
  })
  addWindow({ id: work.prj_id, value: JSON.stringify(windowSubsetString)! })
}

const curStatus = (status: number) => {
  return props.statusList?.find(item => item.value === status)
}

const curType = (type: number) => {
  return props.typeList?.find(item => item.value === type)
}

/**
 * 获取筛选框列表
 */
const getFilterForm = () => {
  const { name, type, prjId, status, date } = props.filterForm
  const beginFrom = date ? date[0] : date
  const endTo = date ? date[1] : date
  return {
    name: name === '' ? undefined : name,
    prjId: prjId === '' ? undefined : prjId,
    status: status === '' ? props.status : status,
    type: type === '' ? undefined : type,
    endTo,
    beginFrom
  }
}

// 获取合同列表
const getList = async () => {
  try {
    const { pageIndex, pageSize } = page
    const { type, name, endTo, status, beginFrom, prjId } = getFilterForm()
    const params = {
      page_no: pageIndex,
      page_size: pageSize,
      begin_from: beginFrom,
      end_to: endTo,
      name,
      prj_id: prjId,
      status,
      process_type: type
    }
    const { list, total } = await getWorkList(params)
    page.total = total
    workList.value = list
  } catch (e) {
    console.error(e)
  }
}

/**
 * 分页变化事件
 * @param argPage
 */
const pageChangehandle = (argPage: IPage): void => {
  page.pageIndex = argPage.pageIndex
  page.pageSize = argPage.pageSize
  getList().then(() => console.log('获取列表'))
}

/**
 * 根据表单按条件筛选分类项
 */
const filterWork = (): void => {
  getList().then(() => console.log('获取列表'))
}

const { undoneCount } = useUndoneCount()

watch(
  () => undoneCount.value,
  () => {
    console.log(`undoneCount变化：${undoneCount.value}`)
    getList().then(() => console.log('获取列表'))
    // console.log(undoneCount.value)
  }
)

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
  name: 'get_work_list',
  callback: () => {
    getList().then(() => console.log('获取列表'))
  }
})

// 显示工作流程时间线
const showWorkTimelineDrawer = async (id: string) => {
  const data: any = await getWorkChain({ work_id: id })
  workChainList.value = data.list ? data.list : data
  selelctedId.value = id
  drawerVisible.value = true
}

defineExpose({ filterWork }) // 暴露子组件的方法或者数据
</script>

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

<style lang="less">
// .chain-drawer {
//   .arco-drawer {
//     .arco-drawer-body {
//       padding: 12px 0 !important;
//     }
//   }
// }
</style>

<style lang="less" scoped>
:deep(.arco-timeline-item-content) {
  font-size: 15px;
}

.selectedItemLeft {
  :deep(.arco-timeline-item-content-wrapper) {
    margin-top: -6px;
  }
  :deep(.arco-timeline-item-content-wrapper) {
    background: var(--color-primary-light-1);
    padding: 15px;
    border-radius: 5px;
  }
  :deep(.arco-timeline-item-content-wrapper::before) {
    position: absolute;
    display: inline-block;
    border-top: 10px solid transparent;
    border-right: 10px solid var(--color-primary-light-1);
    border-bottom: 10px solid transparent;
    // border-right-color: rgba(0, 0, 0, 0.2);
    left: -10px;
    top: 10px;
    content: '';
  }
  // :deep(.arco-timeline-item-content-wrapper::after) {
  //   position: absolute;
  //   display: inline-block;
  //   border-top: 10px solid transparent;
  //   border-right: 10px solid var(--color-primary-light-1);
  //   border-bottom: 10px solid transparent;
  //   left: -10px;
  //   top: 10px;
  //   content: '';
  // }
}

.selectedItemRight {
  :deep(.arco-timeline-item-content-wrapper) {
    margin-top: -6px;
  }
  :deep(.arco-timeline-item-content-wrapper) {
    background: var(--color-primary-light-1);
    padding: 15px;
    border-radius: 5px;
  }
  :deep(.arco-timeline-item-content-wrapper::before) {
    position: absolute;
    display: inline-block;
    border-top: 10px solid transparent;
    border-left: 10px solid var(--color-primary-light-1);
    border-bottom: 10px solid transparent;
    right: -10px;
    top: 10px;
    content: '';
  }
  // :deep(.arco-timeline-item-content-wrapper::after) {
  //   position: absolute;
  //   display: inline-block;
  //   border-top: 10px solid transparent;
  //   border-left: 10px solid var(--color-primary-light-1);
  //   border-bottom: 10px solid transparent;
  //   // border-left-color: rgba(0, 0, 0, 0.2);
  //   right: -10px;
  //   top: 10px;
  //   content: '';
  // }
}

:deep(
    .arco-timeline-alternate
      .arco-timeline-item-vertical-right
      > .arco-timeline-item-content-wrapper
  ) {
  padding-left: 30px;
}

:deep(
    .arco-timeline-alternate
      .arco-timeline-item-vertical-left
      > .arco-timeline-item-content-wrapper
  ) {
  padding-right: 30px;
}
// :deep(
//     .arco-timeline-alternate
//       .arco-timeline-item-vertical-right
//       > .arco-timeline-item-content-wrapper
//   ) {
// margin-left: -6px;
// }
</style>
