<template>
  <div class="container">
    <a-row :gutter="20" align="stretch">
      <a-col :span="24">
        <a-scrollbar
          :style="{
            height: `${containerHeight}`,
            overflow: 'auto',
            background: ' var(--color-bg-2)'
          }"
        >
          <a-card class="general-card">
            <template #title>
              <a-row>
                <a-col :flex="1">
                  <a-form
                    ref="filterFormRef"
                    :model="filterForm"
                    :label-col-props="{ span: 6 }"
                    :wrapper-col-props="{ span: 18 }"
                    label-align="left"
                    auto-label-width
                  >
                    <a-row :gutter="[16, 16]">
                      <a-col :xxl="5" :xl="5" :lg="24" :md="24" :sm="24">
                        <a-form-item
                          field="reporterId"
                          label="填写人员"
                          row-class="mb0"
                        >
                          <a-select
                            v-model="filterForm.reporterId"
                            allow-clear
                            allow-search
                            placeholder="选择周报填写人"
                            @change="getList"
                          >
                            <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
                        v-if="prjList && prjList.length > 0"
                        :xxl="5"
                        :xl="5"
                        :lg="24"
                        :md="24"
                        :sm="24"
                      >
                        <a-form-item
                          field="prjId"
                          label="所属项目"
                          row-class="mb0"
                        >
                          <a-select
                            v-model="filterForm.prjId"
                            allow-clear
                            allow-search
                            placeholder="选择项目信息"
                            @change="getList"
                          >
                            <a-option
                              v-for="{ id, name } in prjList"
                              :key="id"
                              :value="id"
                              :label="name"
                            ></a-option>
                          </a-select>
                        </a-form-item>
                      </a-col>
                      <a-col :xxl="14" :xl="14" :lg="24" :md="24" :sm="24">
                        <a-form-item
                          field="keyword"
                          label="查询时间"
                          row-class="mb0"
                        >
                          <a-row style="width: 100%" :gutter="[16, 16]">
                            <a-col flex="155px">
                              <a-select
                                allow-clear
                                allow-search
                                placeholder="选择时间"
                                :default-value="0"
                              >
                                <a-option
                                  v-for="{
                                    title,
                                    value,
                                    key
                                  } in filterDateList"
                                  :key="key"
                                  :value="value"
                                  :label="title"
                                ></a-option>
                              </a-select>
                            </a-col>
                            <a-col flex="400px">
                              <a-form-item
                                no-style
                                row-class="mb0"
                                field="date"
                              >
                                <a-range-picker
                                  v-model="filterForm.date"
                                  style="width: 100%"
                                  format="YYYY-MM-DD"
                                  @change="getList"
                                />
                              </a-form-item>
                            </a-col>
                            <a-col flex="auto">
                              <a-affix :offset-top="70">
                                <div>
                                  <a-button
                                    type="outline"
                                    @click="redirectReportAddPage"
                                  >
                                    <template #icon>
                                      <icon-plus />
                                    </template>
                                    新建
                                  </a-button>
                                  <a-button
                                    type="primary"
                                    @click="resetFilter()"
                                  >
                                    重置
                                  </a-button>
                                </div>
                              </a-affix>
                            </a-col>
                          </a-row>
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-form>
                </a-col>
              </a-row>
            </template>
            <a-divider style="margin-top: 0" />
            <a-table
              :columns="tableColumns"
              :data="reportList"
              stripe
              :table-layout-fixed="true"
              :pagination="false"
              :bordered="{
                cell: false,
                headerCell: true,
                wrapper: false
              }"
              :hoverable="false"
            >
              <template #date="{ record }">
                {{ record.begin_time }}~{{ record.end_time }}
              </template>
              <template #status="{ record }">
                <a-tag
                  v-for="{ label, value, tagProps } in reportStatus(
                    record.status
                  )"
                  :key="value"
                  :color="tagProps?.color"
                  >{{ label }}</a-tag
                >
              </template>
              <template #operate="{ record }">
                <div class="operate-text-button">
                  <span>
                    <a-button
                      type="text"
                      @click="redirectReportDetailPage(record.id)"
                      >详情</a-button
                    >
                    <a-divider direction="vertical" />
                  </span>

                  <span v-if="record.status === ReportStatusItem.DRAFTING">
                    <a-button type="text">提交</a-button>
                    <a-divider direction="vertical" />
                  </span>
                  <span v-if="record.status === ReportStatusItem.SUMITTING">
                    <a-button type="text">撤回</a-button>
                    <a-divider direction="vertical" />
                  </span>
                  <span>
                    <a-button
                      type="text"
                      status="danger"
                      @click="handleRemoveWeekReport(record)"
                      >删除</a-button
                    >
                  </span>
                </div>
              </template>
            </a-table>
            <Page :page="page" @change="pageChangehandle" />
          </a-card>
        </a-scrollbar>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { PropType, reactive, ref, onMounted, h, computed } from 'vue'
import { ReportStatusItem, ReportStatusList, filterDateList } from '@/enums/api'
import {
  FormInstance,
  TableColumnData,
  Modal,
  Message
} from '@arco-design/web-vue'
import Page from '@/components/page/index.vue'
import usePage, { IPage } from '@/components/page/index'
import { useEmitt } from '@/logics/mitt/useEmitt'
import { getWeekReportList, removeWeekReport } from '@/api/project/week-report'
import { WeekReport, WeekReportListReqParams } from '@/types/week-report'

const { emitter } = useEmitt()

const { page } = usePage()

const props = defineProps({
  accountList: {
    type: Array as PropType<{ id: string; name: string }[]>
  },
  prjList: {
    type: Array as PropType<{ id: string; name: string }[]>
  },
  prjId: {
    type: String
  },
  containerHeight: {
    type: String,
    default: () => {
      return 'calc(100vh - 150px)'
    }
  }
})
console.log(props.prjList)
/**
 * 条件筛选表单
 */
const filterForm = reactive<{
  reporterId?: string
  date?: string[]
  prjId?: string
}>({
  reporterId: undefined,
  prjId: undefined,
  date: undefined
})

// const reporterIdList = ref<{ id: string; name: string }[]>([])
const reportList = ref<WeekReport[]>([])
const filterFormRef = ref<FormInstance>()
const tableColumns = computed(() => {
  const column: TableColumnData[] = [
    {
      title: '所属项目',
      dataIndex: 'prj_name'
    },
    {
      title: '年份',
      dataIndex: 'year'
      // align: 'center'
    },
    {
      title: '周数',
      dataIndex: 'week'
      // align: 'center'
    },
    {
      title: '周开始日',
      dataIndex: 'begin_from'
      // align: 'center'
    },
    {
      title: '周结束日',
      dataIndex: 'end_to'
      // align: 'center'
    },
    {
      title: '填报人',
      dataIndex: 'reporter_name'
      // align: 'right'
    },
    {
      title: '填报时间',
      dataIndex: 'created_at'
      // align: 'center'
    },
    {
      title: '操作',
      slotName: 'operate'
    }
  ]
  return props.prjList && props.prjList.length > 0
    ? column
    : column.filter(item => item.dataIndex !== 'prj_name')
})

/**
 * 获取筛选框列表
 */
const getFilterForm = () => {
  const { reporterId, date, prjId } = filterForm
  const startAtFrom = date ? date[0] : date
  const startAtTo = date ? date[1] : date
  return {
    reporterId: reporterId === '' ? undefined : reporterId,
    prjId: prjId === '' ? undefined : prjId,
    startAtFrom,
    startAtTo
  }
}

const reportStatus = (status: number) => {
  return ReportStatusList.filter(item => item.value === status)
}

/**
 * 获取项目周报列表
 */
const getList = async () => {
  const { reporterId, startAtFrom, startAtTo, prjId } = getFilterForm()
  const { pageIndex, pageSize } = page
  const params: WeekReportListReqParams = {
    prj_id: prjId || props.prjId,
    page_no: pageIndex,
    page_size: pageSize,
    begin_from: startAtFrom,
    end_to: startAtTo,
    reporter_id: reporterId
  }
  const { list, total } = await getWeekReportList(params)
  page.total = total
  reportList.value = list
}

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

const resetFilter = () => {
  filterFormRef.value?.resetFields()
  getList()
}
// const strategies = {
//   [ReportStatusItem.DRAFTING]: reportStatus(ReportStatusItem.DRAFTING)
// }
/**
 * 调整到项目周报详情页面
 * @param id 周报编号
 */
const redirectReportDetailPage = (id: string) => {
  emitter.emit('redirectReportDetailPage', id)
}

// 调整到项目周报创建页面
const redirectReportAddPage = () => {
  emitter.emit('redirectReportAddPage')
}

/**
 * 删除角色
 * @param role
 */
const handleRemoveWeekReport = async (weekReport: WeekReport) => {
  const {
    id,
    week,
    year,
    begin_from: begin,
    end_to: end,
    prj_name: name
  } = weekReport
  const title = {
    setup() {
      return () => h('strong', `警告`)
    }
  }
  const ModalContent = {
    setup() {
      return () =>
        h('span', { style: 'margin-left: 10px;' }, [
          h('span', `确认删除 `),
          h('strong', `${year}年 第${week}周（${begin} ~ ${end}）`),
          h('span', ` 周报吗？`)
        ])
    }
  }
  Modal.warning({
    title: () => h(title),
    content: () => h(ModalContent),
    alignCenter: true,
    titleAlign: 'start',
    draggable: true,
    escToClose: true,
    width: 400,
    simple: true,
    hideCancel: false,
    onOk: async () => {
      try {
        await removeWeekReport(id)
        const index = reportList.value.findIndex(
          (item: { id: string }) => item.id === id
        )
        reportList.value.splice(index, 1)
        Message.success('删除成功')
      } catch (e) {
        console.error(e)
      }
    }
  })
}

onMounted(() => {
  getList().then(() => console.log('获取列表'))
})
</script>

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

<style scoped lang="less">
.container {
  padding: 20px;
}
</style>
