<template>
  <div>
    <Breadcrumb :items="['项目中心', '项目管理']" :title="'项目管理'">
    </Breadcrumb>
    <div class="container">
      <a-space direction="vertical" :size="16" fill>
        <div class="space-unit">
          <DataOverview />
        </div>
        <a-row :gutter="20" align="stretch">
          <a-col :span="24">
            <a-card class="general-card" style="min-height: 70vh">
              <template #title>
                <a-form
                  ref="filterFormRef"
                  :model="filterForm"
                  :label-col-props="{ span: 6 }"
                  :wrapper-col-props="{ span: 18 }"
                  label-align="right"
                  auto-label-width
                >
                  <a-row :gutter="[16, 16]">
                    <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24">
                      <a-form-item field="name" label="项目名称" row-class="mb0"
                        ><a-input-search
                          v-model="filterForm.name"
                          placeholder="根据项目名称模糊匹配"
                          allow-clear
                          @search="filterProject()"
                          @clear="filterProject()"
                          @keyup.enter="filterProject()"
                        />
                      </a-form-item>
                    </a-col>

                    <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24">
                      <a-form-item
                        field="typeId"
                        label="项目类型"
                        row-class="mb0"
                      >
                        <a-cascader
                          v-model="filterForm.typeId"
                          style="width: 100%"
                          :options="prjTypeTreeData"
                          :field-names="{
                            value: 'id',
                            label: 'name'
                          }"
                          :allow-search="false"
                          :allow-clear="true"
                          placeholder="全部"
                          check-strictly
                          @change="filterProject()"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24">
                      <a-form-item
                        field="leaderId"
                        label="项目负责人"
                        row-class="mb0"
                      >
                        <a-select
                          v-model="filterForm.leaderId"
                          placeholder="全部"
                          :allow-search="true"
                          :allow-clear="true"
                          @change="filterProject()"
                        >
                          <a-option
                            v-for="{ id, name } in accountList"
                            :key="id"
                            :value="id"
                            :label="name"
                          ></a-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24">
                      <a-form-item
                        field="regionId"
                        label="所在地区"
                        row-class="mb0"
                      >
                        <a-cascader
                          v-model="filterForm.regionId"
                          style="width: 100%"
                          :options="regionTreeData"
                          :field-names="{
                            value: 'id',
                            label: 'name'
                          }"
                          :allow-search="false"
                          :allow-clear="true"
                          placeholder="全部"
                          check-strictly
                          @change="filterProject()"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24">
                      <a-form-item
                        field="customerName"
                        label="客户名称"
                        row-class="mb0"
                      >
                        <a-input-search
                          v-model="filterForm.customerName"
                          placeholder="根据客户名称模糊匹配"
                          allow-clear
                          @search="filterProject()"
                          @clear="filterProject()"
                          @keyup.enter="filterProject()"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24">
                      <a-form-item
                        field="phaseId"
                        label="项目阶段"
                        row-class="mb0"
                      >
                        <a-select
                          v-model="filterForm.phaseId"
                          placeholder="全部"
                          :allow-search="true"
                          :allow-clear="true"
                          @change="filterProject()"
                        >
                          <a-option
                            v-for="{ id, name } in prjPhaseList"
                            :key="id"
                            :value="id"
                            :label="name"
                          ></a-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                    <a-col :xxl="12" :xl="24" :lg="12">
                      <a-form-item
                        hide-label
                        :row-class="expandForm ? 'mb0' : ''"
                      >
                        <a-space>
                          <a-button type="outline" @click="showProjectModal()">
                            <template #icon>
                              <icon-plus />
                            </template>
                            创建项目
                          </a-button>
                          <a-button type="primary" @click="resetFilter()">
                            重置
                          </a-button>
                          <a-typography-text
                            type="primary"
                            style="cursor: pointer; font-size: 14px"
                            @click="expandForm = !expandForm"
                          >
                            {{ expandForm ? '收起' : '更多' }}
                            <icon-up v-if="expandForm" />
                            <icon-down v-else />
                          </a-typography-text>
                        </a-space>
                      </a-form-item>
                    </a-col>
                    <a-col v-if="expandForm" :span="24">
                      <a-form-item
                        field="phase"
                        label="启动时间"
                        row-class="mb0"
                      >
                        <a-row style="width: 100%" :gutter="[16, 16]">
                          <a-col flex="505px">
                            <a-form-item no-style row-class="mb0">
                              <a-button-group size="large" shape="round">
                                <a-button
                                  v-for="item in filterDateList"
                                  :key="item.key"
                                  :type="changeStartAtBtnType(item.key)"
                                  @click="changeStartAt(item.key, item.value)"
                                >
                                  {{ item.title }}
                                </a-button>
                              </a-button-group>
                            </a-form-item>
                          </a-col>
                          <a-col flex="auto">
                            <a-form-item no-style row-class="mb0">
                              <a-range-picker
                                v-model="filterForm.startAt"
                                show-time
                                format="YYYY-MM-DD HH:mm:ss"
                              />
                            </a-form-item>
                          </a-col>
                        </a-row>
                      </a-form-item>
                    </a-col>
                    <a-col v-if="expandForm" :span="24">
                      <a-form-item field="phase" label="预计时间">
                        <a-row style="width: 100%" :gutter="[16, 16]">
                          <a-col flex="505px">
                            <a-form-item no-style>
                              <a-button-group size="large" shape="round">
                                <a-button
                                  v-for="item in filterDateList"
                                  :key="item.key"
                                  :type="changeDeliverAtBtnType(item.key)"
                                  @click="changeDeliverAt(item.key, item.value)"
                                >
                                  {{ item.title }}
                                </a-button>
                              </a-button-group>
                            </a-form-item>
                          </a-col>
                          <a-col flex="auto">
                            <a-form-item no-style>
                              <a-range-picker
                                v-model="filterForm.deliverAt"
                                show-time
                                format="YYYY-MM-DD HH:mm:ss"
                              />
                            </a-form-item>
                          </a-col>
                        </a-row>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-form>
              </template>
              <a-divider style="margin-top: 0" />
              <List
                ref="prjListRef"
                :filter-form="filterForm"
                :region-tree-data="regionTreeData"
                :account-list="accountList"
                :prj-type-tree-data="prjTypeTreeData"
                :prj-phase-list="prjPhaseList"
              ></List>
            </a-card>
          </a-col>
        </a-row>
      </a-space>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { format, startOfDay, subDays, subYears, subMonths } from 'date-fns'
import { filterDateList } from '@/enums/api'
import { DomainTree, DomainTreeResParams } from '@/types/domain'
import { getDomainTree } from '@/api/acs/domain'
import { getPrjPhaseList, getPrjTypeList } from '@/api/base/base'
import { getStaffList } from '@/api/base/staff'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { getRegionTree } from '@/api/base/region'
import DataOverview from './components/statistics.vue'
import List from './components/List.vue'

/**
 * 条件筛选表单
 */
const filterForm = reactive<{
  name?: string
  typeId?: string
  leaderId?: string
  regionId?: number
  customerName?: string
  phaseId?: string
  startAt?: string[]
  deliverAt?: string[]
}>({
  name: undefined,
  typeId: undefined,
  leaderId: undefined,
  regionId: undefined,
  customerName: undefined,
  phaseId: undefined,
  startAt: undefined,
  deliverAt: undefined
})

const filterFormRef = ref<FormInstance>()
const prjListRef = ref<any>(null)
const prjPhaseList = ref<{ id: string; name: string; color: string }[]>([])
const accountList = ref<{ id: string; name: string }[]>([]) // 分组树
const regionTreeData = ref<DomainTree[]>([]) // 区域树
const prjTypeTreeData = ref<DomainTree[]>([]) // 项目类型
const startAtRadioValue = ref('no-limit')
const deliverAtRadioValue = ref('no-limit')
const expandForm = ref(false)
const changeStartAtBtnType = (value: string) => {
  return startAtRadioValue.value === value ? 'outline' : undefined
}

const changeDeliverAtBtnType = (value: string) => {
  return deliverAtRadioValue.value === value ? 'outline' : undefined
}

/**
 * 设置时间范围快捷方式
 * @param type 0 今天，1 昨天，2 本周， 3，本月  4，上月
 */
const getDateRange = (type: number) => {
  let date: string[] | undefined = []
  switch (type) {
    case 1:
      date = [
        format(subDays(new Date(), 6), 'yyyy-MM-dd 00:00:00'),
        format(startOfDay(new Date()), 'yyyy-MM-dd 23:59:59')
      ]
      break
    case 2:
      date = [
        format(subMonths(new Date(), 1), 'yyyy-MM-dd 00:00:00'),
        format(startOfDay(new Date()), 'yyyy-MM-dd 23:59:59')
      ]
      break
    case 3:
      date = [
        format(subMonths(new Date(), 3), 'yyyy-MM-dd 00:00:00'),
        format(startOfDay(new Date()), 'yyyy-MM-dd 23:59:59')
      ]
      break
    case 4:
      date = [
        format(subMonths(new Date(), 6), 'yyyy-MM-dd 00:00:00'),
        format(startOfDay(new Date()), 'yyyy-MM-dd 23:59:59')
      ]
      break
    case 5:
      date = [
        format(subYears(new Date(), 1), 'yyyy-MM-dd 00:00:00'),
        format(startOfDay(new Date()), 'yyyy-MM-dd 23:59:59')
      ]
      break
    case 0:
    default:
      date = undefined
      break
  }
  return date
}

const changeStartAt = (value: string, type: number) => {
  startAtRadioValue.value = value
  filterForm.startAt = getDateRange(type)
}

const changeDeliverAt = (value: string, type: number) => {
  deliverAtRadioValue.value = value
  filterForm.deliverAt = getDateRange(type)
}

/**
 * 显示添加设备modal
 */
const showProjectModal = async () => {
  prjListRef.value?.showProjectModal()
}

/**
 * 递归获取ng-tree需要的结构体
 * @param domains 接口返回的树状数组
 */
const getNodesTree = (domains: DomainTree): DomainTree => {
  domains.key = domains.id.toString()
  domains.title = domains.name
  if (domains.children && domains.children.length > 0) {
    domains.children.map(res => getNodesTree(res))
  } else {
    domains.children = undefined
  }
  return domains
}

/**
 * 获取区域树
 */
const getRegions = async () => {
  const { tree }: DomainTreeResParams = await getRegionTree()
  regionTreeData.value = tree.map(domains => {
    return getNodesTree(domains)
  })
}

/**
 * 获取区域树
 */
const getProjectType = async () => {
  const { tree }: DomainTreeResParams = await getPrjTypeList()
  prjTypeTreeData.value = tree.map(domains => {
    return getNodesTree(domains)
  })
}

const getPrjPhase = async () => {
  const { list } = await getPrjPhaseList()
  prjPhaseList.value = list
}

/**
 * 获取用户列表
 */
const getAccountList = async () => {
  try {
    const { list } = await getStaffList({ page_no: 1, page_size: 9999 })
    accountList.value = list
  } catch (e) {
    console.error(e)
  }
}
// 重置条件
const resetFilter = (): void => {
  filterFormRef.value?.resetFields()
  filterProject()
}

/**
 * 筛选列表
 */
const filterProject = () => {
  prjListRef.value?.filterProject()
}

onMounted(async () => {
  try {
    getRegions().then(() => console.log('获取所在地区数据'))
    getProjectType().then(() => console.log('获取所在地区数据'))
    getPrjPhase().then(() => console.log('获取项目阶段状态列表数据'))
    getAccountList().then(() => console.log('获取相关负责人账号列表'))
    filterProject()
  } catch (e) {
    console.log(e)
  }
})
</script>

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

<style scoped lang="less">
.container {
  padding: 20px 20px 20px 20px;
  .general-card {
    :deep(.arco-card-header) {
      padding: 20px 20px 0 20px;
    }
  }
}
.dtree {
  padding: 0 10px;
  // max-height: 350px;
  :deep(.arco-tree-node-selected) {
    background-color: rgb(var(--gray-2));
  }
  :deep(.arco-tree-node:hover) {
    background-color: rgb(var(--gray-2));
  }
  :deep(.arco-tree-node-title:hover) {
    background-color: transparent;
  }
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
</style>
