<template>
  <div class="">
    <a-table
      :columns="tableColumns"
      :data="projectList"
      :scroll="{
        x: 1600
      }"
      stripe
      :pagination="false"
      :bordered="{
        cell: false,
        headerCell: true,
        wrapper: false
      }"
      :hoverable="false"
    >
      <template #progress="{ record }">
        <a-tooltip :content="`${record.progress}%`">
          <a-progress
            :percent="record.progress / 100"
            :style="{ width: '100%' }"
            :show-text="false"
            size="large"
          />
        </a-tooltip>
      </template>
      <template #phase="{ record }">
        <a-tag
          v-for="item in selectedPhase(record.phase_id, prjPhaseList)"
          :key="item.id"
          :color="item.color"
          >{{ item.name }}</a-tag
        >
      </template>
      <template #operate="{ record }">
        <div class="operate-text-button">
          <a-button type="text" @click="redirectProjectDetailPage(record.id)"
            >详情</a-button
          >
          <a-divider direction="vertical" />
          <a-button
            type="text"
            status="danger"
            @click="handleRemoveProject(record)"
            >删除</a-button
          >
          <a-divider direction="vertical" />
          <a-dropdown v-if="record.works?.length > 0">
            <a-button type="text">更多 <icon-down /></a-button>
            <template #content>
              <a-doption
                v-for="item in record.works"
                :key="item.id"
                @click="redirectTaskPage(item)"
                >{{ item.name }}</a-doption
              >
            </template>
          </a-dropdown>
        </div>
      </template>
    </a-table>
    <Page :page="page" @change="pageChangehandle" />
    <CURDModal
      ref="curdModalRef"
      :region-tree-data="regionTreeData"
      :account-list="accountList"
      :prj-type-tree-data="prjTypeTreeData"
    ></CURDModal>
    <WorkModal ref="workModalRef"></WorkModal>
  </div>
</template>

<script lang="ts" setup>
import { PropType, ref } from 'vue'
import { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import Page from '@/components/page/index.vue'
import { useEmitt } from '@/logics/mitt/useEmitt'
import usePage, { IPage } from '@/components/page/index'
import { Project, ProjectListReqParams } from '@/types/project'
import { getProjectList } from '@/api/project/info'
import { selectedPhase } from '@/utils'
import { DomainTree } from '@/types/domain'
import { useRouter } from 'vue-router'
import { useWindows } from '@/hooks/useWindow'
import CURDModal from './Curd.vue'
import WorkModal from '../../components/work-modal.vue'

const router = useRouter()
const { page } = usePage()
const props = defineProps({
  filterForm: {
    type: Object,
    default() {
      return {}
    }
  },
  regionTreeData: {
    type: Array as PropType<DomainTree[]>
  },
  accountList: {
    type: Array as PropType<{ id: string; name: string }[]>
  },
  prjTypeTreeData: {
    type: Array as PropType<DomainTree[]>
  },
  prjPhaseList: {
    type: Array as PropType<{ id: string; name: string; color: string }[]>,
    required: true
  }
})
const projectList = ref<Project[]>([])
const tableColumns: TableColumnData[] = [
  {
    title: '项目名称',
    dataIndex: 'name',
    fixed: 'left',
    tooltip: true,
    ellipsis: true,
    width: 180
    // align: 'center'
  },
  {
    title: '项目进度',
    dataIndex: 'progress',
    slotName: 'progress',
    width: 170
  },
  {
    title: '客户名称',
    dataIndex: 'customer_name',
    width: 180,
    tooltip: true,
    ellipsis: true
    // align: 'center'
  },
  {
    title: '项目阶段',
    dataIndex: 'phase',
    slotName: 'phase',
    width: 150
    // align: 'center'
  },
  {
    title: '预计交付时间',
    dataIndex: 'deliver_at',
    tooltip: true,
    ellipsis: true,
    width: 130
    // align: 'center'
  },
  {
    title: '所在地区',
    dataIndex: 'region_name',
    tooltip: true,
    ellipsis: true,
    width: 120
    // align: 'center'
  },

  {
    title: '所属行业',
    dataIndex: 'industry_name',
    width: 150
    // align: 'center'
  },
  {
    title: '项目负责人',
    dataIndex: 'leader_name',
    tooltip: true,
    ellipsis: true,
    width: 150
    // align: 'center'
  },
  {
    title: '商务负责人',
    dataIndex: 'bizman_name',
    tooltip: true,
    ellipsis: true,
    width: 150
    // align: 'center'
  },
  {
    title: '创建日期',
    dataIndex: 'created_at',
    tooltip: true,
    ellipsis: true,
    width: 170
    // align: 'center'
  },
  {
    title: '操作',
    slotName: 'operate',
    width: 190,
    // align: 'left',
    fixed: 'right'
  }
]

const curdModalRef = ref<any>(null) // Modal 增删改子组件ref
const workModalRef = ref<any>(null) // Modal 增删改子组件ref

// 创建一个新对象，只包含 window 对象的 close 方法
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 redirectTaskPage = async (work: { id: string }) => {
  workModalRef.value?.showWorkModal(work.id)
}

/**
 * 获取筛选框列表
 */
const getFilterForm = () => {
  const {
    name,
    typeId,
    leaderId,
    regionId,
    customerName,
    phaseId,
    startAt,
    deliverAt
  } = props.filterForm
  const startAtFrom = startAt ? startAt[0] : startAt
  const startAtTo = startAt ? startAt[1] : startAt
  const deliverAtFrom = deliverAt ? deliverAt[0] : deliverAt
  const deliverAtTo = deliverAt ? deliverAt[1] : deliverAt
  return {
    name: name === '' ? undefined : name,
    typeId: typeId === '' ? undefined : typeId,
    leaderId: leaderId === '' ? undefined : leaderId,
    regionId: regionId === '' ? undefined : regionId,
    customerName: customerName === '' ? undefined : customerName,
    startAtFrom,
    startAtTo,
    deliverAtFrom,
    deliverAtTo,
    phaseId: phaseId === '' ? undefined : phaseId
  }
}

// 获取项目列表
const getList = async () => {
  try {
    const { pageIndex, pageSize } = page
    const {
      name,
      typeId,
      leaderId,
      regionId,
      customerName,
      phaseId,
      startAtFrom,
      startAtTo,
      deliverAtFrom,
      deliverAtTo
    } = getFilterForm()
    const params: ProjectListReqParams = {
      page_no: pageIndex,
      page_size: pageSize,
      name,
      type_id: typeId,
      leader_id: leaderId,
      region_id: regionId,
      customer_name: customerName,
      phase_id: phaseId,
      start_at_from: startAtFrom,
      start_at_to: startAtTo,
      deliver_at_from: deliverAtFrom,
      deliver_at_to: deliverAtTo
    }
    const { list, total } = await getProjectList(params)
    page.total = total
    projectList.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 filterProject = (): void => {
  getList().then(() => console.log('获取列表'))
}

/**
 * 显示增删改modal
 * @param type modal 类型
 * @param item
 */
const showProjectModal = async () => {
  curdModalRef.value?.showProjectModal()
}

const handleRemoveProject = async ({
  id,
  name
}: {
  id: string
  name: string
}) => {
  curdModalRef.value?.handleRemoveProject(id, name)
}

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

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

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